text
stringlengths 5
1.04M
|
|---|
// dear imgui, v1.75
// (main code and documentation)
// Help:
// - Read FAQ at http://dearimgui.org/faq
// - Newcomers, read 'Programmer guide' below for notes on how to setup Dear ImGui in your codebase.
// - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp for demo code. All applications in examples/ are doing that.
// Resources:
// - FAQ http://dearimgui.org/faq
// - Homepage & latest https://github.com/ocornut/imgui
// - Releases & changelog https://github.com/ocornut/imgui/releases
// - Gallery https://github.com/ocornut/imgui/issues/2847 (please post your screenshots/video there!)
// - Glossary https://github.com/ocornut/imgui/wiki/Glossary
// - Wiki https://github.com/ocornut/imgui/wiki
// - Issues & support https://github.com/ocornut/imgui/issues
// Developed by Omar Cornut and every direct or indirect contributors to the GitHub.
// See LICENSE.txt for copyright and licensing details (standard MIT License).
// This library is free but I need your support to sustain development and maintenance.
// Businesses: you can support continued development via invoiced technical support, maintenance and sponsoring contracts. Please reach out to "contact AT dearimgui.org".
// Individuals: you can support continued development via donations. See docs/README or web page.
// It is recommended that you don't modify imgui.cpp! It will become difficult for you to update the library.
// Note that 'ImGui::' being a namespace, you can add functions into the namespace from your own source files, without
// modifying imgui.h or imgui.cpp. You may include imgui_internal.h to access internal data structures, but it doesn't
// come with any guarantee of forward compatibility. Discussing your changes on the GitHub Issue Tracker may lead you
// to a better solution or official support for them.
/*
Index of this file:
DOCUMENTATION
- MISSION STATEMENT
- END-USER GUIDE
- PROGRAMMER GUIDE
- READ FIRST
- HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
- GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
- HOW A SIMPLE APPLICATION MAY LOOK LIKE (2 variations)
- HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
- USING GAMEPAD/KEYBOARD NAVIGATION CONTROLS
- API BREAKING CHANGES (read me when you update!)
- FREQUENTLY ASKED QUESTIONS (FAQ)
- Read all answers online: https://www.dearimgui.org/faq, or in docs/FAQ.md (with a Markdown viewer)
CODE
(search for "[SECTION]" in the code to find them)
// [SECTION] FORWARD DECLARATIONS
// [SECTION] CONTEXT AND MEMORY ALLOCATORS
// [SECTION] MAIN USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
// [SECTION] MISC HELPERS/UTILITIES (File functions)
// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
// [SECTION] MISC HELPERS/UTILITIES (Color functions)
// [SECTION] ImGuiStorage
// [SECTION] ImGuiTextFilter
// [SECTION] ImGuiTextBuffer
// [SECTION] ImGuiListClipper
// [SECTION] RENDER HELPERS
// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
// [SECTION] ERROR CHECKING
// [SECTION] SCROLLING
// [SECTION] TOOLTIPS
// [SECTION] POPUPS
// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
// [SECTION] DRAG AND DROP
// [SECTION] LOGGING/CAPTURING
// [SECTION] SETTINGS
// [SECTION] PLATFORM DEPENDENT HELPERS
// [SECTION] METRICS/DEBUG WINDOW
*/
//-----------------------------------------------------------------------------
// DOCUMENTATION
//-----------------------------------------------------------------------------
/*
MISSION STATEMENT
=================
- Easy to use to create code-driven and data-driven tools.
- Easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools.
- Easy to hack and improve.
- Minimize screen real-estate usage.
- Minimize setup and maintenance.
- Minimize state storage on user side.
- Portable, minimize dependencies, run on target (consoles, phones, etc.).
- Efficient runtime and memory consumption (NB- we do allocate when "growing" content e.g. creating a window,.
opening a tree node for the first time, etc. but a typical frame should not allocate anything).
Designed for developers and content-creators, not the typical end-user! Some of the weaknesses includes:
- Doesn't look fancy, doesn't animate.
- Limited layout features, intricate layouts are typically crafted in code.
END-USER GUIDE
==============
- Double-click on title bar to collapse window.
- Click upper right corner to close a window, available when 'bool* p_open' is passed to ImGui::Begin().
- Click and drag on lower right corner to resize window (double-click to auto fit window to its contents).
- Click and drag on any empty space to move window.
- TAB/SHIFT+TAB to cycle through keyboard editable fields.
- CTRL+Click on a slider or drag box to input value as text.
- Use mouse wheel to scroll.
- Text editor:
- Hold SHIFT or use mouse to select text.
- CTRL+Left/Right to word jump.
- CTRL+Shift+Left/Right to select words.
- CTRL+A our Double-Click to select all.
- CTRL+X,CTRL+C,CTRL+V to use OS clipboard/
- CTRL+Z,CTRL+Y to undo/redo.
- ESCAPE to revert text to its original value.
- You can apply arithmetic operators +,*,/ on numerical values. Use +- to subtract (because - would set a negative value!)
- Controls are automatically adjusted for OSX to match standard OSX text editing operations.
- General Keyboard controls: enable with ImGuiConfigFlags_NavEnableKeyboard.
- General Gamepad controls: enable with ImGuiConfigFlags_NavEnableGamepad. See suggested mappings in imgui.h ImGuiNavInput_ + download PNG/PSD at http://goo.gl/9LgVZW
PROGRAMMER GUIDE
================
READ FIRST
----------
- Remember to read the FAQ (https://www.dearimgui.org/faq)
- Your code creates the UI, if your code doesn't run the UI is gone! The UI can be highly dynamic, there are no construction
or destruction steps, less superfluous data retention on your side, less state duplication, less state synchronization, less bugs.
- Call and read ImGui::ShowDemoWindow() for demo code demonstrating most features.
- The library is designed to be built from sources. Avoid pre-compiled binaries and packaged versions. See imconfig.h to configure your build.
- Dear ImGui is an implementation of the IMGUI paradigm (immediate-mode graphical user interface, a term coined by Casey Muratori).
You can learn about IMGUI principles at http://www.johno.se/book/imgui.html, http://mollyrocket.com/861 & more links docs/README.md.
- Dear ImGui is a "single pass" rasterizing implementation of the IMGUI paradigm, aimed at ease of use and high-performances.
For every application frame your UI code will be called only once. This is in contrast to e.g. Unity's own implementation of an IMGUI,
where the UI code is called multiple times ("multiple passes") from a single entry point. There are pros and cons to both approaches.
- Our origin are on the top-left. In axis aligned bounding boxes, Min = top-left, Max = bottom-right.
- This codebase is also optimized to yield decent performances with typical "Debug" builds settings.
- Please make sure you have asserts enabled (IM_ASSERT redirects to assert() by default, but can be redirected).
If you get an assert, read the messages and comments around the assert.
- C++: this is a very C-ish codebase: we don't rely on C++11, we don't include any C++ headers, and ImGui:: is a namespace.
- C++: ImVec2/ImVec4 do not expose math operators by default, because it is expected that you use your own math types.
See FAQ "How can I use my own math types instead of ImVec2/ImVec4?" for details about setting up imconfig.h for that.
However, imgui_internal.h can optionally export math operators for ImVec2/ImVec4, which we use in this codebase.
- C++: pay attention that ImVector<> manipulates plain-old-data and does not honor construction/destruction (avoid using it in your code!).
HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
----------------------------------------------
- Overwrite all the sources files except for imconfig.h (if you have made modification to your copy of imconfig.h)
- Or maintain your own branch where you have imconfig.h modified.
- Read the "API BREAKING CHANGES" section (below). This is where we list occasional API breaking changes.
If a function/type has been renamed / or marked obsolete, try to fix the name in your code before it is permanently removed
from the public API. If you have a problem with a missing function/symbols, search for its name in the code, there will
likely be a comment about it. Please report any issue to the GitHub page!
- Try to keep your copy of dear imgui reasonably up to date.
GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
---------------------------------------------------------------
- Run and study the examples and demo in imgui_demo.cpp to get acquainted with the library.
- In the majority of cases you should be able to use unmodified back-ends files available in the examples/ folder.
- Add the Dear ImGui source files to your projects or using your preferred build system.
It is recommended you build and statically link the .cpp files as part of your project and NOT as shared library (DLL).
- You can later customize the imconfig.h file to tweak some compile-time behavior, such as integrating Dear ImGui types with your own maths types.
- When using Dear ImGui, your programming IDE is your friend: follow the declaration of variables, functions and types to find comments about them.
- Dear ImGui never touches or knows about your GPU state. The only function that knows about GPU is the draw function that you provide.
Effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render"
phases of your own application. All rendering information are stored into command-lists that you will retrieve after calling ImGui::Render().
- Refer to the bindings and demo applications in the examples/ folder for instruction on how to setup your code.
- If you are running over a standard OS with a common graphics API, you should be able to use unmodified imgui_impl_*** files from the examples/ folder.
HOW A SIMPLE APPLICATION MAY LOOK LIKE
--------------------------------------
EXHIBIT 1: USING THE EXAMPLE BINDINGS (imgui_impl_XXX.cpp files from the examples/ folder).
// Application init: create a dear imgui context, setup some options, load fonts
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO();
// TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
// TODO: Fill optional fields of the io structure later.
// TODO: Load TTF/OTF fonts if you don't want to use the default font.
// Initialize helper Platform and Renderer bindings (here we are using imgui_impl_win32.cpp and imgui_impl_dx11.cpp)
ImGui_ImplWin32_Init(hwnd);
ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext);
// Application main loop
while (true)
{
// Feed inputs to dear imgui, start new frame
ImGui_ImplDX11_NewFrame();
ImGui_ImplWin32_NewFrame();
ImGui::NewFrame();
// Any application code here
ImGui::Text("Hello, world!");
// Render dear imgui into screen
ImGui::Render();
ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
g_pSwapChain->Present(1, 0);
}
// Shutdown
ImGui_ImplDX11_Shutdown();
ImGui_ImplWin32_Shutdown();
ImGui::DestroyContext();
EXHIBIT 2: IMPLEMENTING CUSTOM BINDING / CUSTOM ENGINE
// Application init: create a dear imgui context, setup some options, load fonts
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO();
// TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
// TODO: Fill optional fields of the io structure later.
// TODO: Load TTF/OTF fonts if you don't want to use the default font.
// Build and load the texture atlas into a texture
// (In the examples/ app this is usually done within the ImGui_ImplXXX_Init() function from one of the demo Renderer)
int width, height;
unsigned char* pixels = NULL;
io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
// At this point you've got the texture data and you need to upload that your your graphic system:
// After we have created the texture, store its pointer/identifier (_in whichever format your engine uses_) in 'io.Fonts->TexID'.
// This will be passed back to your via the renderer. Basically ImTextureID == void*. Read FAQ for details about ImTextureID.
MyTexture* texture = MyEngine::CreateTextureFromMemoryPixels(pixels, width, height, TEXTURE_TYPE_RGBA32)
io.Fonts->TexID = (void*)texture;
// Application main loop
while (true)
{
// Setup low-level inputs, e.g. on Win32: calling GetKeyboardState(), or write to those fields from your Windows message handlers, etc.
// (In the examples/ app this is usually done within the ImGui_ImplXXX_NewFrame() function from one of the demo Platform bindings)
io.DeltaTime = 1.0f/60.0f; // set the time elapsed since the previous frame (in seconds)
io.DisplaySize.x = 1920.0f; // set the current display width
io.DisplaySize.y = 1280.0f; // set the current display height here
io.MousePos = my_mouse_pos; // set the mouse position
io.MouseDown[0] = my_mouse_buttons[0]; // set the mouse button states
io.MouseDown[1] = my_mouse_buttons[1];
// Call NewFrame(), after this point you can use ImGui::* functions anytime
// (So you want to try calling NewFrame() as early as you can in your mainloop to be able to use Dear ImGui everywhere)
ImGui::NewFrame();
// Most of your application code here
ImGui::Text("Hello, world!");
MyGameUpdate(); // may use any Dear ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End();
MyGameRender(); // may use any Dear ImGui functions as well!
// Render dear imgui, swap buffers
// (You want to try calling EndFrame/Render as late as you can, to be able to use Dear ImGui in your own game rendering code)
ImGui::EndFrame();
ImGui::Render();
ImDrawData* draw_data = ImGui::GetDrawData();
MyImGuiRenderFunction(draw_data);
SwapBuffers();
}
// Shutdown
ImGui::DestroyContext();
HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
---------------------------------------------
void void MyImGuiRenderFunction(ImDrawData* draw_data)
{
// TODO: Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
// TODO: Setup viewport covering draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
// TODO: Setup orthographic projection matrix cover draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
// TODO: Setup shader: vertex { float2 pos, float2 uv, u32 color }, fragment shader sample color from 1 texture, multiply by vertex color.
for (int n = 0; n < draw_data->CmdListsCount; n++)
{
const ImDrawList* cmd_list = draw_data->CmdLists[n];
const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data; // vertex buffer generated by Dear ImGui
const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data; // index buffer generated by Dear ImGui
for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
{
const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
if (pcmd->UserCallback)
{
pcmd->UserCallback(cmd_list, pcmd);
}
else
{
// The texture for the draw call is specified by pcmd->TextureId.
// The vast majority of draw calls will use the Dear ImGui texture atlas, which value you have set yourself during initialization.
MyEngineBindTexture((MyTexture*)pcmd->TextureId);
// We are using scissoring to clip some objects. All low-level graphics API should supports it.
// - If your engine doesn't support scissoring yet, you may ignore this at first. You will get some small glitches
// (some elements visible outside their bounds) but you can fix that once everything else works!
// - Clipping coordinates are provided in imgui coordinates space (from draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize)
// In a single viewport application, draw_data->DisplayPos will always be (0,0) and draw_data->DisplaySize will always be == io.DisplaySize.
// However, in the interest of supporting multi-viewport applications in the future (see 'viewport' branch on github),
// always subtract draw_data->DisplayPos from clipping bounds to convert them to your viewport space.
// - Note that pcmd->ClipRect contains Min+Max bounds. Some graphics API may use Min+Max, other may use Min+Size (size being Max-Min)
ImVec2 pos = draw_data->DisplayPos;
MyEngineScissor((int)(pcmd->ClipRect.x - pos.x), (int)(pcmd->ClipRect.y - pos.y), (int)(pcmd->ClipRect.z - pos.x), (int)(pcmd->ClipRect.w - pos.y));
// Render 'pcmd->ElemCount/3' indexed triangles.
// By default the indices ImDrawIdx are 16-bit, you can change them to 32-bit in imconfig.h if your engine doesn't support 16-bit indices.
MyEngineDrawIndexedTriangles(pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer, vtx_buffer);
}
idx_buffer += pcmd->ElemCount;
}
}
}
- The examples/ folders contains many actual implementation of the pseudo-codes above.
- When calling NewFrame(), the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags are updated.
They tell you if Dear ImGui intends to use your inputs. When a flag is set you want to hide the corresponding inputs from the
rest of your application. In every cases you need to pass on the inputs to Dear ImGui.
- Refer to the FAQ for more information. Amusingly, it is called a FAQ because people frequently run into the same issues!
USING GAMEPAD/KEYBOARD NAVIGATION CONTROLS
------------------------------------------
- The gamepad/keyboard navigation is fairly functional and keeps being improved.
- Gamepad support is particularly useful to use Dear ImGui on a console system (e.g. PS4, Switch, XB1) without a mouse!
- You can ask questions and report issues at https://github.com/ocornut/imgui/issues/787
- The initial focus was to support game controllers, but keyboard is becoming increasingly and decently usable.
- Keyboard:
- Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard to enable.
NewFrame() will automatically fill io.NavInputs[] based on your io.KeysDown[] + io.KeyMap[] arrays.
- When keyboard navigation is active (io.NavActive + ImGuiConfigFlags_NavEnableKeyboard), the io.WantCaptureKeyboard flag
will be set. For more advanced uses, you may want to read from:
- io.NavActive: true when a window is focused and it doesn't have the ImGuiWindowFlags_NoNavInputs flag set.
- io.NavVisible: true when the navigation cursor is visible (and usually goes false when mouse is used).
- or query focus information with e.g. IsWindowFocused(ImGuiFocusedFlags_AnyWindow), IsItemFocused() etc. functions.
Please reach out if you think the game vs navigation input sharing could be improved.
- Gamepad:
- Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad to enable.
- Backend: Set io.BackendFlags |= ImGuiBackendFlags_HasGamepad + fill the io.NavInputs[] fields before calling NewFrame().
Note that io.NavInputs[] is cleared by EndFrame().
- See 'enum ImGuiNavInput_' in imgui.h for a description of inputs. For each entry of io.NavInputs[], set the following values:
0.0f= not held. 1.0f= fully held. Pass intermediate 0.0f..1.0f values for analog triggers/sticks.
- We uses a simple >0.0f test for activation testing, and won't attempt to test for a dead-zone.
Your code will probably need to transform your raw inputs (such as e.g. remapping your 0.2..0.9 raw input range to 0.0..1.0 imgui range, etc.).
- You can download PNG/PSD files depicting the gamepad controls for common controllers at: http://goo.gl/9LgVZW.
- If you need to share inputs between your game and the imgui parts, the easiest approach is to go all-or-nothing, with a buttons combo
to toggle the target. Please reach out if you think the game vs navigation input sharing could be improved.
- Mouse:
- PS4 users: Consider emulating a mouse cursor with DualShock4 touch pad or a spare analog stick as a mouse-emulation fallback.
- Consoles/Tablet/Phone users: Consider using a Synergy 1.x server (on your PC) + uSynergy.c (on your console/tablet/phone app) to share your PC mouse/keyboard.
- On a TV/console system where readability may be lower or mouse inputs may be awkward, you may want to set the ImGuiConfigFlags_NavEnableSetMousePos flag.
Enabling ImGuiConfigFlags_NavEnableSetMousePos + ImGuiBackendFlags_HasSetMousePos instructs dear imgui to move your mouse cursor along with navigation movements.
When enabled, the NewFrame() function may alter 'io.MousePos' and set 'io.WantSetMousePos' to notify you that it wants the mouse cursor to be moved.
When that happens your back-end NEEDS to move the OS or underlying mouse cursor on the next frame. Some of the binding in examples/ do that.
(If you set the NavEnableSetMousePos flag but don't honor 'io.WantSetMousePos' properly, imgui will misbehave as it will see your mouse as moving back and forth!)
(In a setup when you may not have easy control over the mouse cursor, e.g. uSynergy.c doesn't expose moving remote mouse cursor, you may want
to set a boolean to ignore your other external mouse positions until the external source is moved again.)
API BREAKING CHANGES
====================
Occasionally introducing changes that are breaking the API. We try to make the breakage minor and easy to fix.
Below is a change-log of API breaking changes only. If you are using one of the functions listed, expect to have to fix some code.
When you are not sure about a old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files.
You can read releases logs https://github.com/ocornut/imgui/releases for more details.
- 2020/01/22 (1.75) - ImDrawList::AddCircle()/AddCircleFilled() functions don't accept negative radius any more.
- 2019/12/17 (1.75) - made Columns() limited to 64 columns by asserting above that limit. While the current code technically supports it, future code may not so we're putting the restriction ahead.
- 2019/12/13 (1.75) - [imgui_internal.h] changed ImRect() default constructor initializes all fields to 0.0f instead of (FLT_MAX,FLT_MAX,-FLT_MAX,-FLT_MAX). If you used ImRect::Add() to create bounding boxes by adding multiple points into it, you may need to fix your initial value.
- 2019/12/08 (1.75) - removed redirecting functions/enums that were marked obsolete in 1.53 (December 2017):
- ShowTestWindow() -> use ShowDemoWindow()
- IsRootWindowFocused() -> use IsWindowFocused(ImGuiFocusedFlags_RootWindow)
- IsRootWindowOrAnyChildFocused() -> use IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows)
- SetNextWindowContentWidth(w) -> use SetNextWindowContentSize(ImVec2(w, 0.0f)
- GetItemsLineHeightWithSpacing() -> use GetFrameHeightWithSpacing()
- ImGuiCol_ChildWindowBg -> use ImGuiCol_ChildBg
- ImGuiStyleVar_ChildWindowRounding -> use ImGuiStyleVar_ChildRounding
- ImGuiTreeNodeFlags_AllowOverlapMode -> use ImGuiTreeNodeFlags_AllowItemOverlap
- IMGUI_DISABLE_TEST_WINDOWS -> use IMGUI_DISABLE_DEMO_WINDOWS
- 2019/12/08 (1.75) - obsoleted calling ImDrawList::PrimReserve() with a negative count (which was the vaguely documented and rarely if ever used). Instead we added an explicit PrimUnreserve() API.
- 2019/12/06 (1.75) - removed implicit default parameter to IsMouseDragging(int button = 0) to be consistent with other mouse functions (none of the other functions have it).
- 2019/11/21 (1.74) - ImFontAtlas::AddCustomRectRegular() now requires an ID larger than 0x110000 (instead of 0x10000) to conform with supporting Unicode planes 1-16 in a future update. ID below 0x110000 will now assert.
- 2019/11/19 (1.74) - renamed IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS to IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS for consistency.
- 2019/11/19 (1.74) - renamed IMGUI_DISABLE_MATH_FUNCTIONS to IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS for consistency.
- 2019/10/22 (1.74) - removed redirecting functions/enums that were marked obsolete in 1.52 (October 2017):
- Begin() [old 5 args version] -> use Begin() [3 args], use SetNextWindowSize() SetNextWindowBgAlpha() if needed
- IsRootWindowOrAnyChildHovered() -> use IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows)
- AlignFirstTextHeightToWidgets() -> use AlignTextToFramePadding()
- SetNextWindowPosCenter() -> use SetNextWindowPos() with a pivot of (0.5f, 0.5f)
- ImFont::Glyph -> use ImFontGlyph
- 2019/10/14 (1.74) - inputs: Fixed a miscalculation in the keyboard/mouse "typematic" repeat delay/rate calculation, used by keys and e.g. repeating mouse buttons as well as the GetKeyPressedAmount() function.
if you were using a non-default value for io.KeyRepeatRate (previous default was 0.250), you can add +io.KeyRepeatDelay to it to compensate for the fix.
The function was triggering on: 0.0 and (delay+rate*N) where (N>=1). Fixed formula responds to (N>=0). Effectively it made io.KeyRepeatRate behave like it was set to (io.KeyRepeatRate + io.KeyRepeatDelay).
If you never altered io.KeyRepeatRate nor used GetKeyPressedAmount() this won't affect you.
- 2019/07/15 (1.72) - removed TreeAdvanceToLabelPos() which is rarely used and only does SetCursorPosX(GetCursorPosX() + GetTreeNodeToLabelSpacing()). Kept redirection function (will obsolete).
- 2019/07/12 (1.72) - renamed ImFontAtlas::CustomRect to ImFontAtlasCustomRect. Kept redirection typedef (will obsolete).
- 2019/06/14 (1.72) - removed redirecting functions/enums names that were marked obsolete in 1.51 (June 2017): ImGuiCol_Column*, ImGuiSetCond_*, IsItemHoveredRect(), IsPosHoveringAnyWindow(), IsMouseHoveringAnyWindow(), IsMouseHoveringWindow(), IMGUI_ONCE_UPON_A_FRAME. Grep this log for details and new names, or see how they were implemented until 1.71.
- 2019/06/07 (1.71) - rendering of child window outer decorations (bg color, border, scrollbars) is now performed as part of the parent window. If you have
overlapping child windows in a same parent, and relied on their relative z-order to be mapped to their submission order, this will affect your rendering.
This optimization is disabled if the parent window has no visual output, because it appears to be the most common situation leading to the creation of overlapping child windows.
Please reach out if you are affected.
- 2019/05/13 (1.71) - renamed SetNextTreeNodeOpen() to SetNextItemOpen(). Kept inline redirection function (will obsolete).
- 2019/05/11 (1.71) - changed io.AddInputCharacter(unsigned short c) signature to io.AddInputCharacter(unsigned int c).
- 2019/04/29 (1.70) - improved ImDrawList thick strokes (>1.0f) preserving correct thickness up to 90 degrees angles (e.g. rectangles). If you have custom rendering using thick lines, they will appear thicker now.
- 2019/04/29 (1.70) - removed GetContentRegionAvailWidth(), use GetContentRegionAvail().x instead. Kept inline redirection function (will obsolete).
- 2019/03/04 (1.69) - renamed GetOverlayDrawList() to GetForegroundDrawList(). Kept redirection function (will obsolete).
- 2019/02/26 (1.69) - renamed ImGuiColorEditFlags_RGB/ImGuiColorEditFlags_HSV/ImGuiColorEditFlags_HEX to ImGuiColorEditFlags_DisplayRGB/ImGuiColorEditFlags_DisplayHSV/ImGuiColorEditFlags_DisplayHex. Kept redirection enums (will obsolete).
- 2019/02/14 (1.68) - made it illegal/assert when io.DisplayTime == 0.0f (with an exception for the first frame). If for some reason your time step calculation gives you a zero value, replace it with a dummy small value!
- 2019/02/01 (1.68) - removed io.DisplayVisibleMin/DisplayVisibleMax (which were marked obsolete and removed from viewport/docking branch already).
- 2019/01/06 (1.67) - renamed io.InputCharacters[], marked internal as was always intended. Please don't access directly, and use AddInputCharacter() instead!
- 2019/01/06 (1.67) - renamed ImFontAtlas::GlyphRangesBuilder to ImFontGlyphRangesBuilder. Kept redirection typedef (will obsolete).
- 2018/12/20 (1.67) - made it illegal to call Begin("") with an empty string. This somehow half-worked before but had various undesirable side-effects.
- 2018/12/10 (1.67) - renamed io.ConfigResizeWindowsFromEdges to io.ConfigWindowsResizeFromEdges as we are doing a large pass on configuration flags.
- 2018/10/12 (1.66) - renamed misc/stl/imgui_stl.* to misc/cpp/imgui_stdlib.* in prevision for other C++ helper files.
- 2018/09/28 (1.66) - renamed SetScrollHere() to SetScrollHereY(). Kept redirection function (will obsolete).
- 2018/09/06 (1.65) - renamed stb_truetype.h to imstb_truetype.h, stb_textedit.h to imstb_textedit.h, and stb_rect_pack.h to imstb_rectpack.h.
If you were conveniently using the imgui copy of those STB headers in your project you will have to update your include paths.
- 2018/09/05 (1.65) - renamed io.OptCursorBlink/io.ConfigCursorBlink to io.ConfigInputTextCursorBlink. (#1427)
- 2018/08/31 (1.64) - added imgui_widgets.cpp file, extracted and moved widgets code out of imgui.cpp into imgui_widgets.cpp. Re-ordered some of the code remaining in imgui.cpp.
NONE OF THE FUNCTIONS HAVE CHANGED. THE CODE IS SEMANTICALLY 100% IDENTICAL, BUT _EVERY_ FUNCTION HAS BEEN MOVED.
Because of this, any local modifications to imgui.cpp will likely conflict when you update. Read docs/CHANGELOG.txt for suggestions.
- 2018/08/22 (1.63) - renamed IsItemDeactivatedAfterChange() to IsItemDeactivatedAfterEdit() for consistency with new IsItemEdited() API. Kept redirection function (will obsolete soonish as IsItemDeactivatedAfterChange() is very recent).
- 2018/08/21 (1.63) - renamed ImGuiTextEditCallback to ImGuiInputTextCallback, ImGuiTextEditCallbackData to ImGuiInputTextCallbackData for consistency. Kept redirection types (will obsolete).
- 2018/08/21 (1.63) - removed ImGuiInputTextCallbackData::ReadOnly since it is a duplication of (ImGuiInputTextCallbackData::Flags & ImGuiInputTextFlags_ReadOnly).
- 2018/08/01 (1.63) - removed per-window ImGuiWindowFlags_ResizeFromAnySide beta flag in favor of a global io.ConfigResizeWindowsFromEdges [update 1.67 renamed to ConfigWindowsResizeFromEdges] to enable the feature.
- 2018/08/01 (1.63) - renamed io.OptCursorBlink to io.ConfigCursorBlink [-> io.ConfigInputTextCursorBlink in 1.65], io.OptMacOSXBehaviors to ConfigMacOSXBehaviors for consistency.
- 2018/07/22 (1.63) - changed ImGui::GetTime() return value from float to double to avoid accumulating floating point imprecisions over time.
- 2018/07/08 (1.63) - style: renamed ImGuiCol_ModalWindowDarkening to ImGuiCol_ModalWindowDimBg for consistency with other features. Kept redirection enum (will obsolete).
- 2018/06/08 (1.62) - examples: the imgui_impl_xxx files have been split to separate platform (Win32, Glfw, SDL2, etc.) from renderer (DX11, OpenGL, Vulkan, etc.).
old bindings will still work as is, however prefer using the separated bindings as they will be updated to support multi-viewports.
when adopting new bindings follow the main.cpp code of your preferred examples/ folder to know which functions to call.
in particular, note that old bindings called ImGui::NewFrame() at the end of their ImGui_ImplXXXX_NewFrame() function.
- 2018/06/06 (1.62) - renamed GetGlyphRangesChinese() to GetGlyphRangesChineseFull() to distinguish other variants and discourage using the full set.
- 2018/06/06 (1.62) - TreeNodeEx()/TreeNodeBehavior(): the ImGuiTreeNodeFlags_CollapsingHeader helper now include the ImGuiTreeNodeFlags_NoTreePushOnOpen flag. See Changelog for details.
- 2018/05/03 (1.61) - DragInt(): the default compile-time format string has been changed from "%.0f" to "%d", as we are not using integers internally any more.
If you used DragInt() with custom format strings, make sure you change them to use %d or an integer-compatible format.
To honor backward-compatibility, the DragInt() code will currently parse and modify format strings to replace %*f with %d, giving time to users to upgrade their code.
If you have IMGUI_DISABLE_OBSOLETE_FUNCTIONS enabled, the code will instead assert! You may run a reg-exp search on your codebase for e.g. "DragInt.*%f" to help you find them.
- 2018/04/28 (1.61) - obsoleted InputFloat() functions taking an optional "int decimal_precision" in favor of an equivalent and more flexible "const char* format",
consistent with other functions. Kept redirection functions (will obsolete).
- 2018/04/09 (1.61) - IM_DELETE() helper function added in 1.60 doesn't clear the input _pointer_ reference, more consistent with expectation and allows passing r-value.
- 2018/03/20 (1.60) - renamed io.WantMoveMouse to io.WantSetMousePos for consistency and ease of understanding (was added in 1.52, _not_ used by core and only honored by some binding ahead of merging the Nav branch).
- 2018/03/12 (1.60) - removed ImGuiCol_CloseButton, ImGuiCol_CloseButtonActive, ImGuiCol_CloseButtonHovered as the closing cross uses regular button colors now.
- 2018/03/08 (1.60) - changed ImFont::DisplayOffset.y to default to 0 instead of +1. Fixed rounding of Ascent/Descent to match TrueType renderer. If you were adding or subtracting to ImFont::DisplayOffset check if your fonts are correctly aligned vertically.
- 2018/03/03 (1.60) - renamed ImGuiStyleVar_Count_ to ImGuiStyleVar_COUNT and ImGuiMouseCursor_Count_ to ImGuiMouseCursor_COUNT for consistency with other public enums.
- 2018/02/18 (1.60) - BeginDragDropSource(): temporarily removed the optional mouse_button=0 parameter because it is not really usable in many situations at the moment.
- 2018/02/16 (1.60) - obsoleted the io.RenderDrawListsFn callback, you can call your graphics engine render function after ImGui::Render(). Use ImGui::GetDrawData() to retrieve the ImDrawData* to display.
- 2018/02/07 (1.60) - reorganized context handling to be more explicit,
- YOU NOW NEED TO CALL ImGui::CreateContext() AT THE BEGINNING OF YOUR APP, AND CALL ImGui::DestroyContext() AT THE END.
- removed Shutdown() function, as DestroyContext() serve this purpose.
- you may pass a ImFontAtlas* pointer to CreateContext() to share a font atlas between contexts. Otherwise CreateContext() will create its own font atlas instance.
- removed allocator parameters from CreateContext(), they are now setup with SetAllocatorFunctions(), and shared by all contexts.
- removed the default global context and font atlas instance, which were confusing for users of DLL reloading and users of multiple contexts.
- 2018/01/31 (1.60) - moved sample TTF files from extra_fonts/ to misc/fonts/. If you loaded files directly from the imgui repo you may need to update your paths.
- 2018/01/11 (1.60) - obsoleted IsAnyWindowHovered() in favor of IsWindowHovered(ImGuiHoveredFlags_AnyWindow). Kept redirection function (will obsolete).
- 2018/01/11 (1.60) - obsoleted IsAnyWindowFocused() in favor of IsWindowFocused(ImGuiFocusedFlags_AnyWindow). Kept redirection function (will obsolete).
- 2018/01/03 (1.60) - renamed ImGuiSizeConstraintCallback to ImGuiSizeCallback, ImGuiSizeConstraintCallbackData to ImGuiSizeCallbackData.
- 2017/12/29 (1.60) - removed CalcItemRectClosestPoint() which was weird and not really used by anyone except demo code. If you need it it's easy to replicate on your side.
- 2017/12/24 (1.53) - renamed the emblematic ShowTestWindow() function to ShowDemoWindow(). Kept redirection function (will obsolete).
- 2017/12/21 (1.53) - ImDrawList: renamed style.AntiAliasedShapes to style.AntiAliasedFill for consistency and as a way to explicitly break code that manipulate those flag at runtime. You can now manipulate ImDrawList::Flags
- 2017/12/21 (1.53) - ImDrawList: removed 'bool anti_aliased = true' final parameter of ImDrawList::AddPolyline() and ImDrawList::AddConvexPolyFilled(). Prefer manipulating ImDrawList::Flags if you need to toggle them during the frame.
- 2017/12/14 (1.53) - using the ImGuiWindowFlags_NoScrollWithMouse flag on a child window forwards the mouse wheel event to the parent window, unless either ImGuiWindowFlags_NoInputs or ImGuiWindowFlags_NoScrollbar are also set.
- 2017/12/13 (1.53) - renamed GetItemsLineHeightWithSpacing() to GetFrameHeightWithSpacing(). Kept redirection function (will obsolete).
- 2017/12/13 (1.53) - obsoleted IsRootWindowFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootWindow). Kept redirection function (will obsolete).
- obsoleted IsRootWindowOrAnyChildFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows). Kept redirection function (will obsolete).
- 2017/12/12 (1.53) - renamed ImGuiTreeNodeFlags_AllowOverlapMode to ImGuiTreeNodeFlags_AllowItemOverlap. Kept redirection enum (will obsolete).
- 2017/12/10 (1.53) - removed SetNextWindowContentWidth(), prefer using SetNextWindowContentSize(). Kept redirection function (will obsolete).
- 2017/11/27 (1.53) - renamed ImGuiTextBuffer::append() helper to appendf(), appendv() to appendfv(). If you copied the 'Log' demo in your code, it uses appendv() so that needs to be renamed.
- 2017/11/18 (1.53) - Style, Begin: removed ImGuiWindowFlags_ShowBorders window flag. Borders are now fully set up in the ImGuiStyle structure (see e.g. style.FrameBorderSize, style.WindowBorderSize). Use ImGui::ShowStyleEditor() to look them up.
Please note that the style system will keep evolving (hopefully stabilizing in Q1 2018), and so custom styles will probably subtly break over time. It is recommended you use the StyleColorsClassic(), StyleColorsDark(), StyleColorsLight() functions.
- 2017/11/18 (1.53) - Style: removed ImGuiCol_ComboBg in favor of combo boxes using ImGuiCol_PopupBg for consistency.
- 2017/11/18 (1.53) - Style: renamed ImGuiCol_ChildWindowBg to ImGuiCol_ChildBg.
- 2017/11/18 (1.53) - Style: renamed style.ChildWindowRounding to style.ChildRounding, ImGuiStyleVar_ChildWindowRounding to ImGuiStyleVar_ChildRounding.
- 2017/11/02 (1.53) - obsoleted IsRootWindowOrAnyChildHovered() in favor of using IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows);
- 2017/10/24 (1.52) - renamed IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS to IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS for consistency.
- 2017/10/20 (1.52) - changed IsWindowHovered() default parameters behavior to return false if an item is active in another window (e.g. click-dragging item from another window to this window). You can use the newly introduced IsWindowHovered() flags to requests this specific behavior if you need it.
- 2017/10/20 (1.52) - marked IsItemHoveredRect()/IsMouseHoveringWindow() as obsolete, in favor of using the newly introduced flags for IsItemHovered() and IsWindowHovered(). See https://github.com/ocornut/imgui/issues/1382 for details.
removed the IsItemRectHovered()/IsWindowRectHovered() names introduced in 1.51 since they were merely more consistent names for the two functions we are now obsoleting.
IsItemHoveredRect() --> IsItemHovered(ImGuiHoveredFlags_RectOnly)
IsMouseHoveringAnyWindow() --> IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
IsMouseHoveringWindow() --> IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) [weird, old behavior]
- 2017/10/17 (1.52) - marked the old 5-parameters version of Begin() as obsolete (still available). Use SetNextWindowSize()+Begin() instead!
- 2017/10/11 (1.52) - renamed AlignFirstTextHeightToWidgets() to AlignTextToFramePadding(). Kept inline redirection function (will obsolete).
- 2017/09/26 (1.52) - renamed ImFont::Glyph to ImFontGlyph. Kept redirection typedef (will obsolete).
- 2017/09/25 (1.52) - removed SetNextWindowPosCenter() because SetNextWindowPos() now has the optional pivot information to do the same and more. Kept redirection function (will obsolete).
- 2017/08/25 (1.52) - io.MousePos needs to be set to ImVec2(-FLT_MAX,-FLT_MAX) when mouse is unavailable/missing. Previously ImVec2(-1,-1) was enough but we now accept negative mouse coordinates. In your binding if you need to support unavailable mouse, make sure to replace "io.MousePos = ImVec2(-1,-1)" with "io.MousePos = ImVec2(-FLT_MAX,-FLT_MAX)".
- 2017/08/22 (1.51) - renamed IsItemHoveredRect() to IsItemRectHovered(). Kept inline redirection function (will obsolete). -> (1.52) use IsItemHovered(ImGuiHoveredFlags_RectOnly)!
- renamed IsMouseHoveringAnyWindow() to IsAnyWindowHovered() for consistency. Kept inline redirection function (will obsolete).
- renamed IsMouseHoveringWindow() to IsWindowRectHovered() for consistency. Kept inline redirection function (will obsolete).
- 2017/08/20 (1.51) - renamed GetStyleColName() to GetStyleColorName() for consistency.
- 2017/08/20 (1.51) - added PushStyleColor(ImGuiCol idx, ImU32 col) overload, which _might_ cause an "ambiguous call" compilation error if you are using ImColor() with implicit cast. Cast to ImU32 or ImVec4 explicily to fix.
- 2017/08/15 (1.51) - marked the weird IMGUI_ONCE_UPON_A_FRAME helper macro as obsolete. prefer using the more explicit ImGuiOnceUponAFrame type.
- 2017/08/15 (1.51) - changed parameter order for BeginPopupContextWindow() from (const char*,int buttons,bool also_over_items) to (const char*,int buttons,bool also_over_items). Note that most calls relied on default parameters completely.
- 2017/08/13 (1.51) - renamed ImGuiCol_Column to ImGuiCol_Separator, ImGuiCol_ColumnHovered to ImGuiCol_SeparatorHovered, ImGuiCol_ColumnActive to ImGuiCol_SeparatorActive. Kept redirection enums (will obsolete).
- 2017/08/11 (1.51) - renamed ImGuiSetCond_Always to ImGuiCond_Always, ImGuiSetCond_Once to ImGuiCond_Once, ImGuiSetCond_FirstUseEver to ImGuiCond_FirstUseEver, ImGuiSetCond_Appearing to ImGuiCond_Appearing. Kept redirection enums (will obsolete).
- 2017/08/09 (1.51) - removed ValueColor() helpers, they are equivalent to calling Text(label) + SameLine() + ColorButton().
- 2017/08/08 (1.51) - removed ColorEditMode() and ImGuiColorEditMode in favor of ImGuiColorEditFlags and parameters to the various Color*() functions. The SetColorEditOptions() allows to initialize default but the user can still change them with right-click context menu.
- changed prototype of 'ColorEdit4(const char* label, float col[4], bool show_alpha = true)' to 'ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0)', where passing flags = 0x01 is a safe no-op (hello dodgy backward compatibility!). - check and run the demo window, under "Color/Picker Widgets", to understand the various new options.
- changed prototype of rarely used 'ColorButton(ImVec4 col, bool small_height = false, bool outline_border = true)' to 'ColorButton(const char* desc_id, ImVec4 col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0,0))'
- 2017/07/20 (1.51) - removed IsPosHoveringAnyWindow(ImVec2), which was partly broken and misleading. ASSERT + redirect user to io.WantCaptureMouse
- 2017/05/26 (1.50) - removed ImFontConfig::MergeGlyphCenterV in favor of a more multipurpose ImFontConfig::GlyphOffset.
- 2017/05/01 (1.50) - renamed ImDrawList::PathFill() (rarely used directly) to ImDrawList::PathFillConvex() for clarity.
- 2016/11/06 (1.50) - BeginChild(const char*) now applies the stack id to the provided label, consistently with other functions as it should always have been. It shouldn't affect you unless (extremely unlikely) you were appending multiple times to a same child from different locations of the stack id. If that's the case, generate an id with GetId() and use it instead of passing string to BeginChild().
- 2016/10/15 (1.50) - avoid 'void* user_data' parameter to io.SetClipboardTextFn/io.GetClipboardTextFn pointers. We pass io.ClipboardUserData to it.
- 2016/09/25 (1.50) - style.WindowTitleAlign is now a ImVec2 (ImGuiAlign enum was removed). set to (0.5f,0.5f) for horizontal+vertical centering, (0.0f,0.0f) for upper-left, etc.
- 2016/07/30 (1.50) - SameLine(x) with x>0.0f is now relative to left of column/group if any, and not always to left of window. This was sort of always the intent and hopefully breakage should be minimal.
- 2016/05/12 (1.49) - title bar (using ImGuiCol_TitleBg/ImGuiCol_TitleBgActive colors) isn't rendered over a window background (ImGuiCol_WindowBg color) anymore.
If your TitleBg/TitleBgActive alpha was 1.0f or you are using the default theme it will not affect you, otherwise if <1.0f you need tweak your custom theme to readjust for the fact that we don't draw a WindowBg background behind the title bar.
This helper function will convert an old TitleBg/TitleBgActive color into a new one with the same visual output, given the OLD color and the OLD WindowBg color:
ImVec4 ConvertTitleBgCol(const ImVec4& win_bg_col, const ImVec4& title_bg_col) { float new_a = 1.0f - ((1.0f - win_bg_col.w) * (1.0f - title_bg_col.w)), k = title_bg_col.w / new_a; return ImVec4((win_bg_col.x * win_bg_col.w + title_bg_col.x) * k, (win_bg_col.y * win_bg_col.w + title_bg_col.y) * k, (win_bg_col.z * win_bg_col.w + title_bg_col.z) * k, new_a); }
If this is confusing, pick the RGB value from title bar from an old screenshot and apply this as TitleBg/TitleBgActive. Or you may just create TitleBgActive from a tweaked TitleBg color.
- 2016/05/07 (1.49) - removed confusing set of GetInternalState(), GetInternalStateSize(), SetInternalState() functions. Now using CreateContext(), DestroyContext(), GetCurrentContext(), SetCurrentContext().
- 2016/05/02 (1.49) - renamed SetNextTreeNodeOpened() to SetNextTreeNodeOpen(), no redirection.
- 2016/05/01 (1.49) - obsoleted old signature of CollapsingHeader(const char* label, const char* str_id = NULL, bool display_frame = true, bool default_open = false) as extra parameters were badly designed and rarely used. You can replace the "default_open = true" flag in new API with CollapsingHeader(label, ImGuiTreeNodeFlags_DefaultOpen).
- 2016/04/26 (1.49) - changed ImDrawList::PushClipRect(ImVec4 rect) to ImDrawList::PushClipRect(Imvec2 min,ImVec2 max,bool intersect_with_current_clip_rect=false). Note that higher-level ImGui::PushClipRect() is preferable because it will clip at logic/widget level, whereas ImDrawList::PushClipRect() only affect your renderer.
- 2016/04/03 (1.48) - removed style.WindowFillAlphaDefault setting which was redundant. Bake default BG alpha inside style.Colors[ImGuiCol_WindowBg] and all other Bg color values. (ref github issue #337).
- 2016/04/03 (1.48) - renamed ImGuiCol_TooltipBg to ImGuiCol_PopupBg, used by popups/menus and tooltips. popups/menus were previously using ImGuiCol_WindowBg. (ref github issue #337)
- 2016/03/21 (1.48) - renamed GetWindowFont() to GetFont(), GetWindowFontSize() to GetFontSize(). Kept inline redirection function (will obsolete).
- 2016/03/02 (1.48) - InputText() completion/history/always callbacks: if you modify the text buffer manually (without using DeleteChars()/InsertChars() helper) you need to maintain the BufTextLen field. added an assert.
- 2016/01/23 (1.48) - fixed not honoring exact width passed to PushItemWidth(), previously it would add extra FramePadding.x*2 over that width. if you had manual pixel-perfect alignment in place it might affect you.
- 2015/12/27 (1.48) - fixed ImDrawList::AddRect() which used to render a rectangle 1 px too large on each axis.
- 2015/12/04 (1.47) - renamed Color() helpers to ValueColor() - dangerously named, rarely used and probably to be made obsolete.
- 2015/08/29 (1.45) - with the addition of horizontal scrollbar we made various fixes to inconsistencies with dealing with cursor position.
GetCursorPos()/SetCursorPos() functions now include the scrolled amount. It shouldn't affect the majority of users, but take note that SetCursorPosX(100.0f) puts you at +100 from the starting x position which may include scrolling, not at +100 from the window left side.
GetContentRegionMax()/GetWindowContentRegionMin()/GetWindowContentRegionMax() functions allow include the scrolled amount. Typically those were used in cases where no scrolling would happen so it may not be a problem, but watch out!
- 2015/08/29 (1.45) - renamed style.ScrollbarWidth to style.ScrollbarSize
- 2015/08/05 (1.44) - split imgui.cpp into extra files: imgui_demo.cpp imgui_draw.cpp imgui_internal.h that you need to add to your project.
- 2015/07/18 (1.44) - fixed angles in ImDrawList::PathArcTo(), PathArcToFast() (introduced in 1.43) being off by an extra PI for no justifiable reason
- 2015/07/14 (1.43) - add new ImFontAtlas::AddFont() API. For the old AddFont***, moved the 'font_no' parameter of ImFontAtlas::AddFont** functions to the ImFontConfig structure.
you need to render your textured triangles with bilinear filtering to benefit from sub-pixel positioning of text.
- 2015/07/08 (1.43) - switched rendering data to use indexed rendering. this is saving a fair amount of CPU/GPU and enables us to get anti-aliasing for a marginal cost.
this necessary change will break your rendering function! the fix should be very easy. sorry for that :(
- if you are using a vanilla copy of one of the imgui_impl_XXXX.cpp provided in the example, you just need to update your copy and you can ignore the rest.
- the signature of the io.RenderDrawListsFn handler has changed!
old: ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
new: ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data).
parameters: 'cmd_lists' becomes 'draw_data->CmdLists', 'cmd_lists_count' becomes 'draw_data->CmdListsCount'
ImDrawList: 'commands' becomes 'CmdBuffer', 'vtx_buffer' becomes 'VtxBuffer', 'IdxBuffer' is new.
ImDrawCmd: 'vtx_count' becomes 'ElemCount', 'clip_rect' becomes 'ClipRect', 'user_callback' becomes 'UserCallback', 'texture_id' becomes 'TextureId'.
- each ImDrawList now contains both a vertex buffer and an index buffer. For each command, render ElemCount/3 triangles using indices from the index buffer.
- if you REALLY cannot render indexed primitives, you can call the draw_data->DeIndexAllBuffers() method to de-index the buffers. This is slow and a waste of CPU/GPU. Prefer using indexed rendering!
- refer to code in the examples/ folder or ask on the GitHub if you are unsure of how to upgrade. please upgrade!
- 2015/07/10 (1.43) - changed SameLine() parameters from int to float.
- 2015/07/02 (1.42) - renamed SetScrollPosHere() to SetScrollFromCursorPos(). Kept inline redirection function (will obsolete).
- 2015/07/02 (1.42) - renamed GetScrollPosY() to GetScrollY(). Necessary to reduce confusion along with other scrolling functions, because positions (e.g. cursor position) are not equivalent to scrolling amount.
- 2015/06/14 (1.41) - changed ImageButton() default bg_col parameter from (0,0,0,1) (black) to (0,0,0,0) (transparent) - makes a difference when texture have transparence
- 2015/06/14 (1.41) - changed Selectable() API from (label, selected, size) to (label, selected, flags, size). Size override should have been rarely be used. Sorry!
- 2015/05/31 (1.40) - renamed GetWindowCollapsed() to IsWindowCollapsed() for consistency. Kept inline redirection function (will obsolete).
- 2015/05/31 (1.40) - renamed IsRectClipped() to IsRectVisible() for consistency. Note that return value is opposite! Kept inline redirection function (will obsolete).
- 2015/05/27 (1.40) - removed the third 'repeat_if_held' parameter from Button() - sorry! it was rarely used and inconsistent. Use PushButtonRepeat(true) / PopButtonRepeat() to enable repeat on desired buttons.
- 2015/05/11 (1.40) - changed BeginPopup() API, takes a string identifier instead of a bool. ImGui needs to manage the open/closed state of popups. Call OpenPopup() to actually set the "open" state of a popup. BeginPopup() returns true if the popup is opened.
- 2015/05/03 (1.40) - removed style.AutoFitPadding, using style.WindowPadding makes more sense (the default values were already the same).
- 2015/04/13 (1.38) - renamed IsClipped() to IsRectClipped(). Kept inline redirection function until 1.50.
- 2015/04/09 (1.38) - renamed ImDrawList::AddArc() to ImDrawList::AddArcFast() for compatibility with future API
- 2015/04/03 (1.38) - removed ImGuiCol_CheckHovered, ImGuiCol_CheckActive, replaced with the more general ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive.
- 2014/04/03 (1.38) - removed support for passing -FLT_MAX..+FLT_MAX as the range for a SliderFloat(). Use DragFloat() or Inputfloat() instead.
- 2015/03/17 (1.36) - renamed GetItemBoxMin()/GetItemBoxMax()/IsMouseHoveringBox() to GetItemRectMin()/GetItemRectMax()/IsMouseHoveringRect(). Kept inline redirection function until 1.50.
- 2015/03/15 (1.36) - renamed style.TreeNodeSpacing to style.IndentSpacing, ImGuiStyleVar_TreeNodeSpacing to ImGuiStyleVar_IndentSpacing
- 2015/03/13 (1.36) - renamed GetWindowIsFocused() to IsWindowFocused(). Kept inline redirection function until 1.50.
- 2015/03/08 (1.35) - renamed style.ScrollBarWidth to style.ScrollbarWidth (casing)
- 2015/02/27 (1.34) - renamed OpenNextNode(bool) to SetNextTreeNodeOpened(bool, ImGuiSetCond). Kept inline redirection function until 1.50.
- 2015/02/27 (1.34) - renamed ImGuiSetCondition_*** to ImGuiSetCond_***, and _FirstUseThisSession becomes _Once.
- 2015/02/11 (1.32) - changed text input callback ImGuiTextEditCallback return type from void-->int. reserved for future use, return 0 for now.
- 2015/02/10 (1.32) - renamed GetItemWidth() to CalcItemWidth() to clarify its evolving behavior
- 2015/02/08 (1.31) - renamed GetTextLineSpacing() to GetTextLineHeightWithSpacing()
- 2015/02/01 (1.31) - removed IO.MemReallocFn (unused)
- 2015/01/19 (1.30) - renamed ImGuiStorage::GetIntPtr()/GetFloatPtr() to GetIntRef()/GetIntRef() because Ptr was conflicting with actual pointer storage functions.
- 2015/01/11 (1.30) - big font/image API change! now loads TTF file. allow for multiple fonts. no need for a PNG loader.
- 2015/01/11 (1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels.
- old: const void* png_data; unsigned int png_size; ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); [..Upload texture to GPU..];
- new: unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); [..Upload texture to GPU..]; io.Fonts->TexId = YourTexIdentifier;
you now have more flexibility to load multiple TTF fonts and manage the texture buffer for internal needs. It is now recommended that you sample the font texture with bilinear interpolation.
- 2015/01/11 (1.30) - added texture identifier in ImDrawCmd passed to your render function (we can now render images). make sure to set io.Fonts->TexID.
- 2015/01/11 (1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix)
- 2015/01/11 (1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets
- 2014/12/10 (1.18) - removed SetNewWindowDefaultPos() in favor of new generic API SetNextWindowPos(pos, ImGuiSetCondition_FirstUseEver)
- 2014/11/28 (1.17) - moved IO.Font*** options to inside the IO.Font-> structure (FontYOffset, FontTexUvForWhite, FontBaseScale, FontFallbackGlyph)
- 2014/11/26 (1.17) - reworked syntax of IMGUI_ONCE_UPON_A_FRAME helper macro to increase compiler compatibility
- 2014/11/07 (1.15) - renamed IsHovered() to IsItemHovered()
- 2014/10/02 (1.14) - renamed IMGUI_INCLUDE_IMGUI_USER_CPP to IMGUI_INCLUDE_IMGUI_USER_INL and imgui_user.cpp to imgui_user.inl (more IDE friendly)
- 2014/09/25 (1.13) - removed 'text_end' parameter from IO.SetClipboardTextFn (the string is now always zero-terminated for simplicity)
- 2014/09/24 (1.12) - renamed SetFontScale() to SetWindowFontScale()
- 2014/09/24 (1.12) - moved IM_MALLOC/IM_REALLOC/IM_FREE preprocessor defines to IO.MemAllocFn/IO.MemReallocFn/IO.MemFreeFn
- 2014/08/30 (1.09) - removed IO.FontHeight (now computed automatically)
- 2014/08/30 (1.09) - moved IMGUI_FONT_TEX_UV_FOR_WHITE preprocessor define to IO.FontTexUvForWhite
- 2014/08/28 (1.09) - changed the behavior of IO.PixelCenterOffset following various rendering fixes
FREQUENTLY ASKED QUESTIONS (FAQ)
================================
Read all answers online: https://www.dearimgui.org/faq, or in docs/FAQ.md (with a Markdown viewer)
Some answers are copied down here to facilitate searching in code.
Q&A: Basics
===========
Q: Where is the documentation?
A: This library is poorly documented at the moment and expects of the user to be acquainted with C/C++.
- Run the examples/ and explore them.
- See demo code in imgui_demo.cpp and particularly the ImGui::ShowDemoWindow() function.
- The demo covers most features of Dear ImGui, so you can read the code and see its output.
- See documentation and comments at the top of imgui.cpp + effectively imgui.h.
- Dozens of standalone example applications using e.g. OpenGL/DirectX are provided in the
examples/ folder to explain how to integrate Dear ImGui with your own engine/application.
- The Wiki (https://github.com/ocornut/imgui/wiki) has many resources and links.
- The Glossary (https://github.com/ocornut/imgui/wiki/Glossary) page also may be useful.
- Your programming IDE is your friend, find the type or function declaration to find comments
associated to it.
Q: What is this library called?
Q: Which version should I get?
>> This library is called "Dear ImGui", please don't call it "ImGui" :)
>> See https://www.dearimgui.org/faq
Q&A: Integration
================
Q: How can I tell whether to dispatch mouse/keyboard to Dear ImGui or to my application?
A: You should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
>> See https://www.dearimgui.org/faq for fully detailed answer. You really want to read this.
Q. How can I enable keyboard controls?
Q: How can I use this without a mouse, without a keyboard or without a screen? (gamepad, input share, remote display)
Q: I integrated Dear ImGui in my engine and the text or lines are blurry..
Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around..
>> See https://www.dearimgui.org/faq
Q&A: Usage
----------
Q: Why are multiple widgets reacting when I interact with a single one?
Q: How can I have multiple widgets with the same label or with an empty label?
A: A primer on labels and the ID Stack...
Dear ImGui internally need to uniquely identify UI elements.
Elements that are typically not clickable (such as calls to the Text functions) don't need an ID.
Interactive widgets (such as calls to Button buttons) need a unique ID.
Unique ID are used internally to track active widgets and occasionally associate state to widgets.
Unique ID are implicitly built from the hash of multiple elements that identify the "path" to the UI element.
- Unique ID are often derived from a string label:
Button("OK"); // Label = "OK", ID = hash of (..., "OK")
Button("Cancel"); // Label = "Cancel", ID = hash of (..., "Cancel")
- ID are uniquely scoped within windows, tree nodes, etc. which all pushes to the ID stack. Having
two buttons labeled "OK" in different windows or different tree locations is fine.
We used "..." above to signify whatever was already pushed to the ID stack previously:
Begin("MyWindow");
Button("OK"); // Label = "OK", ID = hash of ("MyWindow", "OK")
End();
Begin("MyOtherWindow");
Button("OK"); // Label = "OK", ID = hash of ("MyOtherWindow", "OK")
End();
- If you have a same ID twice in the same location, you'll have a conflict:
Button("OK");
Button("OK"); // ID collision! Interacting with either button will trigger the first one.
Fear not! this is easy to solve and there are many ways to solve it!
- Solving ID conflict in a simple/local context:
When passing a label you can optionally specify extra ID information within string itself.
Use "##" to pass a complement to the ID that won't be visible to the end-user.
This helps solving the simple collision cases when you know e.g. at compilation time which items
are going to be created:
Begin("MyWindow");
Button("Play"); // Label = "Play", ID = hash of ("MyWindow", "Play")
Button("Play##foo1"); // Label = "Play", ID = hash of ("MyWindow", "Play##foo1") // Different from above
Button("Play##foo2"); // Label = "Play", ID = hash of ("MyWindow", "Play##foo2") // Different from above
End();
- If you want to completely hide the label, but still need an ID:
Checkbox("##On", &b); // Label = "", ID = hash of (..., "##On") // No visible label, just a checkbox!
- Occasionally/rarely you might want change a label while preserving a constant ID. This allows
you to animate labels. For example you may want to include varying information in a window title bar,
but windows are uniquely identified by their ID. Use "###" to pass a label that isn't part of ID:
Button("Hello###ID"); // Label = "Hello", ID = hash of (..., "###ID")
Button("World###ID"); // Label = "World", ID = hash of (..., "###ID") // Same as above, even though the label looks different
sprintf(buf, "My game (%f FPS)###MyGame", fps);
Begin(buf); // Variable title, ID = hash of "MyGame"
- Solving ID conflict in a more general manner:
Use PushID() / PopID() to create scopes and manipulate the ID stack, as to avoid ID conflicts
within the same window. This is the most convenient way of distinguishing ID when iterating and
creating many UI elements programmatically.
You can push a pointer, a string or an integer value into the ID stack.
Remember that ID are formed from the concatenation of _everything_ pushed into the ID stack.
At each level of the stack we store the seed used for items at this level of the ID stack.
Begin("Window");
for (int i = 0; i < 100; i++)
{
PushID(i); // Push i to the id tack
Button("Click"); // Label = "Click", ID = hash of ("Window", i, "Click")
PopID();
}
for (int i = 0; i < 100; i++)
{
MyObject* obj = Objects[i];
PushID(obj);
Button("Click"); // Label = "Click", ID = hash of ("Window", obj pointer, "Click")
PopID();
}
for (int i = 0; i < 100; i++)
{
MyObject* obj = Objects[i];
PushID(obj->Name);
Button("Click"); // Label = "Click", ID = hash of ("Window", obj->Name, "Click")
PopID();
}
End();
- You can stack multiple prefixes into the ID stack:
Button("Click"); // Label = "Click", ID = hash of (..., "Click")
PushID("node");
Button("Click"); // Label = "Click", ID = hash of (..., "node", "Click")
PushID(my_ptr);
Button("Click"); // Label = "Click", ID = hash of (..., "node", my_ptr, "Click")
PopID();
PopID();
- Tree nodes implicitly creates a scope for you by calling PushID().
Button("Click"); // Label = "Click", ID = hash of (..., "Click")
if (TreeNode("node")) // <-- this function call will do a PushID() for you (unless instructed not to, with a special flag)
{
Button("Click"); // Label = "Click", ID = hash of (..., "node", "Click")
TreePop();
}
- When working with trees, ID are used to preserve the open/close state of each tree node.
Depending on your use cases you may want to use strings, indices or pointers as ID.
e.g. when following a single pointer that may change over time, using a static string as ID
will preserve your node open/closed state when the targeted object change.
e.g. when displaying a list of objects, using indices or pointers as ID will preserve the
node open/closed state differently. See what makes more sense in your situation!
Q: How can I display an image? What is ImTextureID, how does it works?
>> See https://www.dearimgui.org/faq and https://github.com/ocornut/imgui/wiki/Image-Loading-and-Displaying-Examples
Q: How can I use my own math types instead of ImVec2/ImVec4?
Q: How can I interact with standard C++ types (such as std::string and std::vector)?
Q: How can I display custom shapes? (using low-level ImDrawList API)
>> See https://www.dearimgui.org/faq
Q&A: Fonts, Text
================
Q: How can I load a different font than the default?
Q: How can I easily use icons in my application?
Q: How can I load multiple fonts?
Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic?
>> See https://www.dearimgui.org/faq and docs/FONTS.txt
Q&A: Concerns
=============
Q: Who uses Dear ImGui?
Q: Can you create elaborate/serious tools with Dear ImGui?
Q: Can you reskin the look of Dear ImGui?
Q: Why using C++ (as opposed to C)?
>> See https://www.dearimgui.org/faq
Q&A: Community
==============
Q: How can I help?
A: - Businesses: please reach out to "contact AT dearimgui.org" if you work in a place using Dear ImGui!
We can discuss ways for your company to fund development via invoiced technical support, maintenance or sponsoring contacts.
This is among the most useful thing you can do for Dear ImGui. With increased funding we can hire more people working on this project.
- Individuals: you can support continued development via PayPal donations. See README.
- If you are experienced with Dear ImGui and C++, look at the github issues, look at the Wiki, read docs/TODO.txt
and see how you want to help and can help!
- Disclose your usage of Dear ImGui via a dev blog post, a tweet, a screenshot, a mention somewhere etc.
You may post screenshot or links in the gallery threads (github.com/ocornut/imgui/issues/2847). Visuals are ideal as they inspire other programmers.
But even without visuals, disclosing your use of dear imgui help the library grow credibility, and help other teams and programmers with taking decisions.
- If you have issues or if you need to hack into the library, even if you don't expect any support it is useful that you share your issues (on github or privately).
*/
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
#define _CRT_SECURE_NO_WARNINGS
#endif
#include "imgui.h"
#ifndef IMGUI_DISABLE
#ifndef IMGUI_DEFINE_MATH_OPERATORS
#define IMGUI_DEFINE_MATH_OPERATORS
#endif
#include "imgui_internal.h"
#include <ctype.h> // toupper
#include <stdio.h> // vsnprintf, sscanf, printf
#if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier
#include <stddef.h> // intptr_t
#else
#include <stdint.h> // intptr_t
#endif
// Debug options
#define IMGUI_DEBUG_NAV_SCORING 0 // Display navigation scoring preview when hovering items. Display last moving direction matches when holding CTRL
#define IMGUI_DEBUG_NAV_RECTS 0 // Display the reference navigation rectangle for each window
#define IMGUI_DEBUG_INI_SETTINGS 0 // Save additional comments in .ini file (particularly helps for Docking, but makes saving slower)
// Visual Studio warnings
#ifdef _MSC_VER
#pragma warning (disable: 4127) // condition expression is constant
#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
#if defined(_MSC_VER) && _MSC_VER >= 1922 // MSVC 2019 16.2 or later
#pragma warning (disable: 5054) // operator '|': deprecated between enumerations of different types
#endif
#endif
// Clang/GCC warnings with -Weverything
#if defined(__clang__)
#pragma clang diagnostic ignored "-Wunknown-pragmas" // warning : unknown warning group '-Wformat-pedantic *' // not all warnings are known by all clang versions.. so ignoring warnings triggers new warnings on some configuration. great!
#pragma clang diagnostic ignored "-Wold-style-cast" // warning : use of old-style cast // yes, they are more terse.
#pragma clang diagnostic ignored "-Wfloat-equal" // warning : comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok.
#pragma clang diagnostic ignored "-Wformat-nonliteral" // warning : format string is not a string literal // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code.
#pragma clang diagnostic ignored "-Wexit-time-destructors" // warning : declaration requires an exit-time destructor // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals.
#pragma clang diagnostic ignored "-Wglobal-constructors" // warning : declaration requires a global destructor // similar to above, not sure what the exact difference is.
#pragma clang diagnostic ignored "-Wsign-conversion" // warning : implicit conversion changes signedness //
#pragma clang diagnostic ignored "-Wformat-pedantic" // warning : format specifies type 'void *' but the argument has type 'xxxx *' // unreasonable, would lead to casting every %p arg to void*. probably enabled by -pedantic.
#pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning : cast to 'void *' from smaller integer type 'int'
#if __has_warning("-Wzero-as-null-pointer-constant")
#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning : zero as null pointer constant // some standard header variations use #define NULL 0
#endif
#if __has_warning("-Wdouble-promotion")
#pragma clang diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function // using printf() is a misery with this as C++ va_arg ellipsis changes float to double.
#endif
#elif defined(__GNUC__)
// We disable -Wpragmas because GCC doesn't provide an has_warning equivalent and some forks/patches may not following the warning/version association.
#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind
#pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used
#pragma GCC diagnostic ignored "-Wint-to-pointer-cast" // warning: cast to pointer from integer of different size
#pragma GCC diagnostic ignored "-Wformat" // warning: format '%p' expects argument of type 'void*', but argument 6 has type 'ImGuiWindow*'
#pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function
#pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value
#pragma GCC diagnostic ignored "-Wformat-nonliteral" // warning: format not a string literal, format string not checked
#pragma GCC diagnostic ignored "-Wstrict-overflow" // warning: assuming signed overflow does not occur when assuming that (X - c) > X is always false
#pragma GCC diagnostic ignored "-Wclass-memaccess" // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead
#endif
// When using CTRL+TAB (or Gamepad Square+L/R) we delay the visual a little in order to reduce visual noise doing a fast switch.
static const float NAV_WINDOWING_HIGHLIGHT_DELAY = 0.20f; // Time before the highlight and screen dimming starts fading in
static const float NAV_WINDOWING_LIST_APPEAR_DELAY = 0.15f; // Time before the window list starts to appear
// Window resizing from edges (when io.ConfigWindowsResizeFromEdges = true and ImGuiBackendFlags_HasMouseCursors is set in io.BackendFlags by back-end)
static const float WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS = 4.0f; // Extend outside and inside windows. Affect FindHoveredWindow().
static const float WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04f; // Reduce visual noise by only highlighting the border after a certain time.
static const float WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER = 2.00f; // Lock scrolled window (so it doesn't pick child windows that are scrolling through) for a certaint time, unless mouse moved.
//-------------------------------------------------------------------------
// [SECTION] FORWARD DECLARATIONS
//-------------------------------------------------------------------------
static void SetCurrentWindow(ImGuiWindow* window);
static void FindHoveredWindow();
static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags);
static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window, bool snap_on_edges);
static void AddDrawListToDrawData(ImVector<ImDrawList*>* out_list, ImDrawList* draw_list);
static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window);
static ImRect GetViewportRect();
// Settings
static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
static void WindowSettingsHandler_WriteAll(ImGuiContext*, ImGuiSettingsHandler*, ImGuiTextBuffer* buf);
// Platform Dependents default implementation for IO functions
static const char* GetClipboardTextFn_DefaultImpl(void* user_data);
static void SetClipboardTextFn_DefaultImpl(void* user_data, const char* text);
static void ImeSetInputScreenPosFn_DefaultImpl(int x, int y);
namespace ImGui
{
// Navigation
static void NavUpdate();
static void NavUpdateWindowing();
static void NavUpdateWindowingOverlay();
static void NavUpdateMoveResult();
static float NavUpdatePageUpPageDown();
static inline void NavUpdateAnyRequestFlag();
static bool NavScoreItem(ImGuiNavMoveResult* result, ImRect cand);
static void NavProcessItem(ImGuiWindow* window, const ImRect& nav_bb, ImGuiID id);
static ImVec2 NavCalcPreferredRefPos();
static void NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window);
static ImGuiWindow* NavRestoreLastChildNavWindow(ImGuiWindow* window);
static int FindWindowFocusIndex(ImGuiWindow* window);
// Error Checking
static void ErrorCheckEndFrame();
static void ErrorCheckBeginEndCompareStacksSize(ImGuiWindow* window, bool write);
// Misc
static void UpdateMouseInputs();
static void UpdateMouseWheel();
static bool UpdateManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4]);
static void UpdateDebugToolItemPicker();
static void RenderWindowOuterBorders(ImGuiWindow* window);
static void RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size);
static void RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open);
}
//-----------------------------------------------------------------------------
// [SECTION] CONTEXT AND MEMORY ALLOCATORS
//-----------------------------------------------------------------------------
// Current context pointer. Implicitly used by all Dear ImGui functions. Always assumed to be != NULL.
// ImGui::CreateContext() will automatically set this pointer if it is NULL. Change to a different context by calling ImGui::SetCurrentContext().
// 1) Important: globals are not shared across DLL boundaries! If you use DLLs or any form of hot-reloading: you will need to call
// SetCurrentContext() (with the pointer you got from CreateContext) from each unique static/DLL boundary, and after each hot-reloading.
// In your debugger, add GImGui to your watch window and notice how its value changes depending on which location you are currently stepping into.
// 2) Important: Dear ImGui functions are not thread-safe because of this pointer.
// If you want thread-safety to allow N threads to access N different contexts, you can:
// - Change this variable to use thread local storage so each thread can refer to a different context, in imconfig.h:
// struct ImGuiContext;
// extern thread_local ImGuiContext* MyImGuiTLS;
// #define GImGui MyImGuiTLS
// And then define MyImGuiTLS in one of your cpp file. Note that thread_local is a C++11 keyword, earlier C++ uses compiler-specific keyword.
// - Future development aim to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586
// - If you need a finite number of contexts, you may compile and use multiple instances of the ImGui code from different namespace.
#ifndef GImGui
ImGuiContext* GImGui = NULL;
#endif
// Memory Allocator functions. Use SetAllocatorFunctions() to change them.
// If you use DLL hotreloading you might need to call SetAllocatorFunctions() after reloading code from this file.
// Otherwise, you probably don't want to modify them mid-program, and if you use global/static e.g. ImVector<> instances you may need to keep them accessible during program destruction.
#ifndef IMGUI_DISABLE_DEFAULT_ALLOCATORS
static void* MallocWrapper(size_t size, void* user_data) { IM_UNUSED(user_data); return malloc(size); }
static void FreeWrapper(void* ptr, void* user_data) { IM_UNUSED(user_data); free(ptr); }
#else
static void* MallocWrapper(size_t size, void* user_data) { IM_UNUSED(user_data); IM_UNUSED(size); IM_ASSERT(0); return NULL; }
static void FreeWrapper(void* ptr, void* user_data) { IM_UNUSED(user_data); IM_UNUSED(ptr); IM_ASSERT(0); }
#endif
static void* (*GImAllocatorAllocFunc)(size_t size, void* user_data) = MallocWrapper;
static void (*GImAllocatorFreeFunc)(void* ptr, void* user_data) = FreeWrapper;
static void* GImAllocatorUserData = NULL;
//-----------------------------------------------------------------------------
// [SECTION] MAIN USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
//-----------------------------------------------------------------------------
ImGuiStyle::ImGuiStyle()
{
Alpha = 1.0f; // Global alpha applies to everything in ImGui
WindowPadding = ImVec2(8,8); // Padding within a window
WindowRounding = 7.0f; // Radius of window corners rounding. Set to 0.0f to have rectangular windows
WindowBorderSize = 1.0f; // Thickness of border around windows. Generally set to 0.0f or 1.0f. Other values not well tested.
WindowMinSize = ImVec2(32,32); // Minimum window size
WindowTitleAlign = ImVec2(0.0f,0.5f);// Alignment for title bar text
WindowMenuButtonPosition= ImGuiDir_Left; // Position of the collapsing/docking button in the title bar (left/right). Defaults to ImGuiDir_Left.
ChildRounding = 0.0f; // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows
ChildBorderSize = 1.0f; // Thickness of border around child windows. Generally set to 0.0f or 1.0f. Other values not well tested.
PopupRounding = 0.0f; // Radius of popup window corners rounding. Set to 0.0f to have rectangular child windows
PopupBorderSize = 1.0f; // Thickness of border around popup or tooltip windows. Generally set to 0.0f or 1.0f. Other values not well tested.
FramePadding = ImVec2(4,3); // Padding within a framed rectangle (used by most widgets)
FrameRounding = 4.0f; // Radius of frame corners rounding. Set to 0.0f to have rectangular frames (used by most widgets).
FrameBorderSize = 1.0f; // Thickness of border around frames. Generally set to 0.0f or 1.0f. Other values not well tested.
ItemSpacing = ImVec2(8,4); // Horizontal and vertical spacing between widgets/lines
ItemInnerSpacing = ImVec2(4,4); // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label)
TouchExtraPadding = ImVec2(0,0); // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much!
IndentSpacing = 21.0f; // Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2).
ColumnsMinSpacing = 6.0f; // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1).
ScrollbarSize = 14.0f; // Width of the vertical scrollbar, Height of the horizontal scrollbar
ScrollbarRounding = 9.0f; // Radius of grab corners rounding for scrollbar
GrabMinSize = 10.0f; // Minimum width/height of a grab box for slider/scrollbar
GrabRounding = 0.0f; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs.
TabRounding = 4.0f; // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs.
TabBorderSize = 0.0f; // Thickness of border around tabs.
ColorButtonPosition = ImGuiDir_Right; // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right.
ButtonTextAlign = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text.
SelectableTextAlign = ImVec2(0.0f,0.0f);// Alignment of selectable text when button is larger than text.
DisplayWindowPadding = ImVec2(19,19); // Window position are clamped to be visible within the display area or monitors by at least this amount. Only applies to regular windows.
DisplaySafeAreaPadding = ImVec2(3,3); // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows.
MouseCursorScale = 1.0f; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later.
AntiAliasedLines = true; // Enable anti-aliasing on lines/borders. Disable if you are really short on CPU/GPU.
AntiAliasedFill = true; // Enable anti-aliasing on filled shapes (rounded rectangles, circles, etc.)
CurveTessellationTol = 1.25f; // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality.
CircleSegmentMaxError = 1.60f; // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry.
// Default theme
ImGui::StyleColorsDark(this);
}
// To scale your entire UI (e.g. if you want your app to use High DPI or generally be DPI aware) you may use this helper function. Scaling the fonts is done separately and is up to you.
// Important: This operation is lossy because we round all sizes to integer. If you need to change your scale multiples, call this over a freshly initialized ImGuiStyle structure rather than scaling multiple times.
void ImGuiStyle::ScaleAllSizes(float scale_factor)
{
WindowPadding = ImFloor(WindowPadding * scale_factor);
WindowRounding = ImFloor(WindowRounding * scale_factor);
WindowMinSize = ImFloor(WindowMinSize * scale_factor);
ChildRounding = ImFloor(ChildRounding * scale_factor);
PopupRounding = ImFloor(PopupRounding * scale_factor);
FramePadding = ImFloor(FramePadding * scale_factor);
FrameRounding = ImFloor(FrameRounding * scale_factor);
ItemSpacing = ImFloor(ItemSpacing * scale_factor);
ItemInnerSpacing = ImFloor(ItemInnerSpacing * scale_factor);
TouchExtraPadding = ImFloor(TouchExtraPadding * scale_factor);
IndentSpacing = ImFloor(IndentSpacing * scale_factor);
ColumnsMinSpacing = ImFloor(ColumnsMinSpacing * scale_factor);
ScrollbarSize = ImFloor(ScrollbarSize * scale_factor);
ScrollbarRounding = ImFloor(ScrollbarRounding * scale_factor);
GrabMinSize = ImFloor(GrabMinSize * scale_factor);
GrabRounding = ImFloor(GrabRounding * scale_factor);
TabRounding = ImFloor(TabRounding * scale_factor);
DisplayWindowPadding = ImFloor(DisplayWindowPadding * scale_factor);
DisplaySafeAreaPadding = ImFloor(DisplaySafeAreaPadding * scale_factor);
MouseCursorScale = ImFloor(MouseCursorScale * scale_factor);
}
ImGuiIO::ImGuiIO()
{
// Most fields are initialized with zero
memset(this, 0, sizeof(*this));
IM_ASSERT(IM_ARRAYSIZE(ImGuiIO::MouseDown) == ImGuiMouseButton_COUNT && IM_ARRAYSIZE(ImGuiIO::MouseClicked) == ImGuiMouseButton_COUNT); // Our pre-C++11 IM_STATIC_ASSERT() macros triggers warning on modern compilers so we don't use it here.
// Settings
ConfigFlags = ImGuiConfigFlags_None;
BackendFlags = ImGuiBackendFlags_None;
DisplaySize = ImVec2(-1.0f, -1.0f);
DeltaTime = 1.0f/60.0f;
IniSavingRate = 5.0f;
IniFilename = "imgui.ini";
LogFilename = "imgui_log.txt";
MouseDoubleClickTime = 0.30f;
MouseDoubleClickMaxDist = 6.0f;
for (int i = 0; i < ImGuiKey_COUNT; i++)
KeyMap[i] = -1;
KeyRepeatDelay = 0.275f;
KeyRepeatRate = 0.050f;
UserData = NULL;
Fonts = NULL;
FontGlobalScale = 1.0f;
FontDefault = NULL;
FontAllowUserScaling = false;
DisplayFramebufferScale = ImVec2(1.0f, 1.0f);
// Miscellaneous options
MouseDrawCursor = false;
#ifdef __APPLE__
ConfigMacOSXBehaviors = true; // Set Mac OS X style defaults based on __APPLE__ compile time flag
#else
ConfigMacOSXBehaviors = false;
#endif
ConfigInputTextCursorBlink = true;
ConfigWindowsResizeFromEdges = true;
ConfigWindowsMoveFromTitleBarOnly = false;
ConfigWindowsMemoryCompactTimer = 60.0f;
// Platform Functions
BackendPlatformName = BackendRendererName = NULL;
BackendPlatformUserData = BackendRendererUserData = BackendLanguageUserData = NULL;
GetClipboardTextFn = GetClipboardTextFn_DefaultImpl; // Platform dependent default implementations
SetClipboardTextFn = SetClipboardTextFn_DefaultImpl;
ClipboardUserData = NULL;
ImeSetInputScreenPosFn = ImeSetInputScreenPosFn_DefaultImpl;
ImeWindowHandle = NULL;
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
RenderDrawListsFn = NULL;
#endif
// Input (NB: we already have memset zero the entire structure!)
MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
MousePosPrev = ImVec2(-FLT_MAX, -FLT_MAX);
MouseDragThreshold = 6.0f;
for (int i = 0; i < IM_ARRAYSIZE(MouseDownDuration); i++) MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f;
for (int i = 0; i < IM_ARRAYSIZE(KeysDownDuration); i++) KeysDownDuration[i] = KeysDownDurationPrev[i] = -1.0f;
for (int i = 0; i < IM_ARRAYSIZE(NavInputsDownDuration); i++) NavInputsDownDuration[i] = -1.0f;
}
// Pass in translated ASCII characters for text input.
// - with glfw you can get those from the callback set in glfwSetCharCallback()
// - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message
void ImGuiIO::AddInputCharacter(unsigned int c)
{
if (c > 0 && c <= IM_UNICODE_CODEPOINT_MAX)
InputQueueCharacters.push_back((ImWchar)c);
}
void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars)
{
while (*utf8_chars != 0)
{
unsigned int c = 0;
utf8_chars += ImTextCharFromUtf8(&c, utf8_chars, NULL);
if (c > 0 && c <= IM_UNICODE_CODEPOINT_MAX)
InputQueueCharacters.push_back((ImWchar)c);
}
}
void ImGuiIO::ClearInputCharacters()
{
InputQueueCharacters.resize(0);
}
//-----------------------------------------------------------------------------
// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
//-----------------------------------------------------------------------------
ImVec2 ImBezierClosestPoint(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, int num_segments)
{
IM_ASSERT(num_segments > 0); // Use ImBezierClosestPointCasteljau()
ImVec2 p_last = p1;
ImVec2 p_closest;
float p_closest_dist2 = FLT_MAX;
float t_step = 1.0f / (float)num_segments;
for (int i_step = 1; i_step <= num_segments; i_step++)
{
ImVec2 p_current = ImBezierCalc(p1, p2, p3, p4, t_step * i_step);
ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
float dist2 = ImLengthSqr(p - p_line);
if (dist2 < p_closest_dist2)
{
p_closest = p_line;
p_closest_dist2 = dist2;
}
p_last = p_current;
}
return p_closest;
}
// Closely mimics PathBezierToCasteljau() in imgui_draw.cpp
static void BezierClosestPointCasteljauStep(const ImVec2& p, ImVec2& p_closest, ImVec2& p_last, float& p_closest_dist2, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, float tess_tol, int level)
{
float dx = x4 - x1;
float dy = y4 - y1;
float d2 = ((x2 - x4) * dy - (y2 - y4) * dx);
float d3 = ((x3 - x4) * dy - (y3 - y4) * dx);
d2 = (d2 >= 0) ? d2 : -d2;
d3 = (d3 >= 0) ? d3 : -d3;
if ((d2+d3) * (d2+d3) < tess_tol * (dx*dx + dy*dy))
{
ImVec2 p_current(x4, y4);
ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
float dist2 = ImLengthSqr(p - p_line);
if (dist2 < p_closest_dist2)
{
p_closest = p_line;
p_closest_dist2 = dist2;
}
p_last = p_current;
}
else if (level < 10)
{
float x12 = (x1+x2)*0.5f, y12 = (y1+y2)*0.5f;
float x23 = (x2+x3)*0.5f, y23 = (y2+y3)*0.5f;
float x34 = (x3+x4)*0.5f, y34 = (y3+y4)*0.5f;
float x123 = (x12+x23)*0.5f, y123 = (y12+y23)*0.5f;
float x234 = (x23+x34)*0.5f, y234 = (y23+y34)*0.5f;
float x1234 = (x123+x234)*0.5f, y1234 = (y123+y234)*0.5f;
BezierClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1, y1, x12, y12, x123, y123, x1234, y1234, tess_tol, level + 1);
BezierClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1234, y1234, x234, y234, x34, y34, x4, y4, tess_tol, level + 1);
}
}
// tess_tol is generally the same value you would find in ImGui::GetStyle().CurveTessellationTol
// Because those ImXXX functions are lower-level than ImGui:: we cannot access this value automatically.
ImVec2 ImBezierClosestPointCasteljau(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, float tess_tol)
{
IM_ASSERT(tess_tol > 0.0f);
ImVec2 p_last = p1;
ImVec2 p_closest;
float p_closest_dist2 = FLT_MAX;
BezierClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, tess_tol, 0);
return p_closest;
}
ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p)
{
ImVec2 ap = p - a;
ImVec2 ab_dir = b - a;
float dot = ap.x * ab_dir.x + ap.y * ab_dir.y;
if (dot < 0.0f)
return a;
float ab_len_sqr = ab_dir.x * ab_dir.x + ab_dir.y * ab_dir.y;
if (dot > ab_len_sqr)
return b;
return a + ab_dir * dot / ab_len_sqr;
}
bool ImTriangleContainsPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
{
bool b1 = ((p.x - b.x) * (a.y - b.y) - (p.y - b.y) * (a.x - b.x)) < 0.0f;
bool b2 = ((p.x - c.x) * (b.y - c.y) - (p.y - c.y) * (b.x - c.x)) < 0.0f;
bool b3 = ((p.x - a.x) * (c.y - a.y) - (p.y - a.y) * (c.x - a.x)) < 0.0f;
return ((b1 == b2) && (b2 == b3));
}
void ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p, float& out_u, float& out_v, float& out_w)
{
ImVec2 v0 = b - a;
ImVec2 v1 = c - a;
ImVec2 v2 = p - a;
const float denom = v0.x * v1.y - v1.x * v0.y;
out_v = (v2.x * v1.y - v1.x * v2.y) / denom;
out_w = (v0.x * v2.y - v2.x * v0.y) / denom;
out_u = 1.0f - out_v - out_w;
}
ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
{
ImVec2 proj_ab = ImLineClosestPoint(a, b, p);
ImVec2 proj_bc = ImLineClosestPoint(b, c, p);
ImVec2 proj_ca = ImLineClosestPoint(c, a, p);
float dist2_ab = ImLengthSqr(p - proj_ab);
float dist2_bc = ImLengthSqr(p - proj_bc);
float dist2_ca = ImLengthSqr(p - proj_ca);
float m = ImMin(dist2_ab, ImMin(dist2_bc, dist2_ca));
if (m == dist2_ab)
return proj_ab;
if (m == dist2_bc)
return proj_bc;
return proj_ca;
}
//-----------------------------------------------------------------------------
// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
//-----------------------------------------------------------------------------
// Consider using _stricmp/_strnicmp under Windows or strcasecmp/strncasecmp. We don't actually use either ImStricmp/ImStrnicmp in the codebase any more.
int ImStricmp(const char* str1, const char* str2)
{
int d;
while ((d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; }
return d;
}
int ImStrnicmp(const char* str1, const char* str2, size_t count)
{
int d = 0;
while (count > 0 && (d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; count--; }
return d;
}
void ImStrncpy(char* dst, const char* src, size_t count)
{
if (count < 1)
return;
if (count > 1)
strncpy(dst, src, count - 1);
dst[count - 1] = 0;
}
char* ImStrdup(const char* str)
{
size_t len = strlen(str);
void* buf = IM_ALLOC(len + 1);
return (char*)memcpy(buf, (const void*)str, len + 1);
}
char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* src)
{
size_t dst_buf_size = p_dst_size ? *p_dst_size : strlen(dst) + 1;
size_t src_size = strlen(src) + 1;
if (dst_buf_size < src_size)
{
IM_FREE(dst);
dst = (char*)IM_ALLOC(src_size);
if (p_dst_size)
*p_dst_size = src_size;
}
return (char*)memcpy(dst, (const void*)src, src_size);
}
const char* ImStrchrRange(const char* str, const char* str_end, char c)
{
const char* p = (const char*)memchr(str, (int)c, str_end - str);
return p;
}
int ImStrlenW(const ImWchar* str)
{
//return (int)wcslen((const wchar_t*)str); // FIXME-OPT: Could use this when wchar_t are 16-bit
int n = 0;
while (*str++) n++;
return n;
}
// Find end-of-line. Return pointer will point to either first \n, either str_end.
const char* ImStreolRange(const char* str, const char* str_end)
{
const char* p = (const char*)memchr(str, '\n', str_end - str);
return p ? p : str_end;
}
const ImWchar* ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin) // find beginning-of-line
{
while (buf_mid_line > buf_begin && buf_mid_line[-1] != '\n')
buf_mid_line--;
return buf_mid_line;
}
const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end)
{
if (!needle_end)
needle_end = needle + strlen(needle);
const char un0 = (char)toupper(*needle);
while ((!haystack_end && *haystack) || (haystack_end && haystack < haystack_end))
{
if (toupper(*haystack) == un0)
{
const char* b = needle + 1;
for (const char* a = haystack + 1; b < needle_end; a++, b++)
if (toupper(*a) != toupper(*b))
break;
if (b == needle_end)
return haystack;
}
haystack++;
}
return NULL;
}
// Trim str by offsetting contents when there's leading data + writing a \0 at the trailing position. We use this in situation where the cost is negligible.
void ImStrTrimBlanks(char* buf)
{
char* p = buf;
while (p[0] == ' ' || p[0] == '\t') // Leading blanks
p++;
char* p_start = p;
while (*p != 0) // Find end of string
p++;
while (p > p_start && (p[-1] == ' ' || p[-1] == '\t')) // Trailing blanks
p--;
if (p_start != buf) // Copy memory if we had leading blanks
memmove(buf, p_start, p - p_start);
buf[p - p_start] = 0; // Zero terminate
}
const char* ImStrSkipBlank(const char* str)
{
while (str[0] == ' ' || str[0] == '\t')
str++;
return str;
}
// A) MSVC version appears to return -1 on overflow, whereas glibc appears to return total count (which may be >= buf_size).
// Ideally we would test for only one of those limits at runtime depending on the behavior the vsnprintf(), but trying to deduct it at compile time sounds like a pandora can of worm.
// B) When buf==NULL vsnprintf() will return the output size.
#ifndef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
// We support stb_sprintf which is much faster (see: https://github.com/nothings/stb/blob/master/stb_sprintf.h)
// You may set IMGUI_USE_STB_SPRINTF to use our default wrapper, or set IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
// and setup the wrapper yourself. (FIXME-OPT: Some of our high-level operations such as ImGuiTextBuffer::appendfv() are
// designed using two-passes worst case, which probably could be improved using the stbsp_vsprintfcb() function.)
#ifdef IMGUI_USE_STB_SPRINTF
#define STB_SPRINTF_IMPLEMENTATION
#include "stb_sprintf.h"
#endif
#if defined(_MSC_VER) && !defined(vsnprintf)
#define vsnprintf _vsnprintf
#endif
int ImFormatString(char* buf, size_t buf_size, const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
#ifdef IMGUI_USE_STB_SPRINTF
int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
#else
int w = vsnprintf(buf, buf_size, fmt, args);
#endif
va_end(args);
if (buf == NULL)
return w;
if (w == -1 || w >= (int)buf_size)
w = (int)buf_size - 1;
buf[w] = 0;
return w;
}
int ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args)
{
#ifdef IMGUI_USE_STB_SPRINTF
int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
#else
int w = vsnprintf(buf, buf_size, fmt, args);
#endif
if (buf == NULL)
return w;
if (w == -1 || w >= (int)buf_size)
w = (int)buf_size - 1;
buf[w] = 0;
return w;
}
#endif // #ifdef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
// CRC32 needs a 1KB lookup table (not cache friendly)
// Although the code to generate the table is simple and shorter than the table itself, using a const table allows us to easily:
// - avoid an unnecessary branch/memory tap, - keep the ImHashXXX functions usable by static constructors, - make it thread-safe.
static const ImU32 GCrc32LookupTable[256] =
{
0x00000000,0x77073096,0xEE0E612C,0x990951BA,0x076DC419,0x706AF48F,0xE963A535,0x9E6495A3,0x0EDB8832,0x79DCB8A4,0xE0D5E91E,0x97D2D988,0x09B64C2B,0x7EB17CBD,0xE7B82D07,0x90BF1D91,
0x1DB71064,0x6AB020F2,0xF3B97148,0x84BE41DE,0x1ADAD47D,0x6DDDE4EB,0xF4D4B551,0x83D385C7,0x136C9856,0x646BA8C0,0xFD62F97A,0x8A65C9EC,0x14015C4F,0x63066CD9,0xFA0F3D63,0x8D080DF5,
0x3B6E20C8,0x4C69105E,0xD56041E4,0xA2677172,0x3C03E4D1,0x4B04D447,0xD20D85FD,0xA50AB56B,0x35B5A8FA,0x42B2986C,0xDBBBC9D6,0xACBCF940,0x32D86CE3,0x45DF5C75,0xDCD60DCF,0xABD13D59,
0x26D930AC,0x51DE003A,0xC8D75180,0xBFD06116,0x21B4F4B5,0x56B3C423,0xCFBA9599,0xB8BDA50F,0x2802B89E,0x5F058808,0xC60CD9B2,0xB10BE924,0x2F6F7C87,0x58684C11,0xC1611DAB,0xB6662D3D,
0x76DC4190,0x01DB7106,0x98D220BC,0xEFD5102A,0x71B18589,0x06B6B51F,0x9FBFE4A5,0xE8B8D433,0x7807C9A2,0x0F00F934,0x9609A88E,0xE10E9818,0x7F6A0DBB,0x086D3D2D,0x91646C97,0xE6635C01,
0x6B6B51F4,0x1C6C6162,0x856530D8,0xF262004E,0x6C0695ED,0x1B01A57B,0x8208F4C1,0xF50FC457,0x65B0D9C6,0x12B7E950,0x8BBEB8EA,0xFCB9887C,0x62DD1DDF,0x15DA2D49,0x8CD37CF3,0xFBD44C65,
0x4DB26158,0x3AB551CE,0xA3BC0074,0xD4BB30E2,0x4ADFA541,0x3DD895D7,0xA4D1C46D,0xD3D6F4FB,0x4369E96A,0x346ED9FC,0xAD678846,0xDA60B8D0,0x44042D73,0x33031DE5,0xAA0A4C5F,0xDD0D7CC9,
0x5005713C,0x270241AA,0xBE0B1010,0xC90C2086,0x5768B525,0x206F85B3,0xB966D409,0xCE61E49F,0x5EDEF90E,0x29D9C998,0xB0D09822,0xC7D7A8B4,0x59B33D17,0x2EB40D81,0xB7BD5C3B,0xC0BA6CAD,
0xEDB88320,0x9ABFB3B6,0x03B6E20C,0x74B1D29A,0xEAD54739,0x9DD277AF,0x04DB2615,0x73DC1683,0xE3630B12,0x94643B84,0x0D6D6A3E,0x7A6A5AA8,0xE40ECF0B,0x9309FF9D,0x0A00AE27,0x7D079EB1,
0xF00F9344,0x8708A3D2,0x1E01F268,0x6906C2FE,0xF762575D,0x806567CB,0x196C3671,0x6E6B06E7,0xFED41B76,0x89D32BE0,0x10DA7A5A,0x67DD4ACC,0xF9B9DF6F,0x8EBEEFF9,0x17B7BE43,0x60B08ED5,
0xD6D6A3E8,0xA1D1937E,0x38D8C2C4,0x4FDFF252,0xD1BB67F1,0xA6BC5767,0x3FB506DD,0x48B2364B,0xD80D2BDA,0xAF0A1B4C,0x36034AF6,0x41047A60,0xDF60EFC3,0xA867DF55,0x316E8EEF,0x4669BE79,
0xCB61B38C,0xBC66831A,0x256FD2A0,0x5268E236,0xCC0C7795,0xBB0B4703,0x220216B9,0x5505262F,0xC5BA3BBE,0xB2BD0B28,0x2BB45A92,0x5CB36A04,0xC2D7FFA7,0xB5D0CF31,0x2CD99E8B,0x5BDEAE1D,
0x9B64C2B0,0xEC63F226,0x756AA39C,0x026D930A,0x9C0906A9,0xEB0E363F,0x72076785,0x05005713,0x95BF4A82,0xE2B87A14,0x7BB12BAE,0x0CB61B38,0x92D28E9B,0xE5D5BE0D,0x7CDCEFB7,0x0BDBDF21,
0x86D3D2D4,0xF1D4E242,0x68DDB3F8,0x1FDA836E,0x81BE16CD,0xF6B9265B,0x6FB077E1,0x18B74777,0x88085AE6,0xFF0F6A70,0x66063BCA,0x11010B5C,0x8F659EFF,0xF862AE69,0x616BFFD3,0x166CCF45,
0xA00AE278,0xD70DD2EE,0x4E048354,0x3903B3C2,0xA7672661,0xD06016F7,0x4969474D,0x3E6E77DB,0xAED16A4A,0xD9D65ADC,0x40DF0B66,0x37D83BF0,0xA9BCAE53,0xDEBB9EC5,0x47B2CF7F,0x30B5FFE9,
0xBDBDF21C,0xCABAC28A,0x53B39330,0x24B4A3A6,0xBAD03605,0xCDD70693,0x54DE5729,0x23D967BF,0xB3667A2E,0xC4614AB8,0x5D681B02,0x2A6F2B94,0xB40BBE37,0xC30C8EA1,0x5A05DF1B,0x2D02EF8D,
};
// Known size hash
// It is ok to call ImHashData on a string with known length but the ### operator won't be supported.
// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
ImU32 ImHashData(const void* data_p, size_t data_size, ImU32 seed)
{
ImU32 crc = ~seed;
const unsigned char* data = (const unsigned char*)data_p;
const ImU32* crc32_lut = GCrc32LookupTable;
while (data_size-- != 0)
crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *data++];
return ~crc;
}
// Zero-terminated string hash, with support for ### to reset back to seed value
// We support a syntax of "label###id" where only "###id" is included in the hash, and only "label" gets displayed.
// Because this syntax is rarely used we are optimizing for the common case.
// - If we reach ### in the string we discard the hash so far and reset to the seed.
// - We don't do 'current += 2; continue;' after handling ### to keep the code smaller/faster (measured ~10% diff in Debug build)
// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
ImU32 ImHashStr(const char* data_p, size_t data_size, ImU32 seed)
{
seed = ~seed;
ImU32 crc = seed;
const unsigned char* data = (const unsigned char*)data_p;
const ImU32* crc32_lut = GCrc32LookupTable;
if (data_size != 0)
{
while (data_size-- != 0)
{
unsigned char c = *data++;
if (c == '#' && data_size >= 2 && data[0] == '#' && data[1] == '#')
crc = seed;
crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
}
}
else
{
while (unsigned char c = *data++)
{
if (c == '#' && data[0] == '#' && data[1] == '#')
crc = seed;
crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
}
}
return ~crc;
}
//-----------------------------------------------------------------------------
// [SECTION] MISC HELPERS/UTILITIES (File functions)
//-----------------------------------------------------------------------------
// Default file functions
#ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
ImFileHandle ImFileOpen(const char* filename, const char* mode)
{
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(__CYGWIN__) && !defined(__GNUC__)
// We need a fopen() wrapper because MSVC/Windows fopen doesn't handle UTF-8 filenames.
const int filename_wsize = ImTextCountCharsFromUtf8(filename, NULL) + 1;
const int mode_wsize = ImTextCountCharsFromUtf8(mode, NULL) + 1;
ImVector<ImWchar> buf;
buf.resize(filename_wsize + mode_wsize);
ImTextStrFromUtf8(&buf[0], filename_wsize, filename, NULL);
ImTextStrFromUtf8(&buf[filename_wsize], mode_wsize, mode, NULL);
return _wfopen((wchar_t*)&buf[0], (wchar_t*)&buf[filename_wsize]);
#else
return fopen(filename, mode);
#endif
}
// We should in theory be using fseeko()/ftello() with off_t and _fseeki64()/_ftelli64() with __int64, waiting for the PR that does that in a very portable pre-C++11 zero-warnings way.
bool ImFileClose(ImFileHandle f) { return fclose(f) == 0; }
ImU64 ImFileGetSize(ImFileHandle f) { long off = 0, sz = 0; return ((off = ftell(f)) != -1 && !fseek(f, 0, SEEK_END) && (sz = ftell(f)) != -1 && !fseek(f, off, SEEK_SET)) ? (ImU64)sz : (ImU64)-1; }
ImU64 ImFileRead(void* data, ImU64 sz, ImU64 count, ImFileHandle f) { return fread(data, (size_t)sz, (size_t)count, f); }
ImU64 ImFileWrite(const void* data, ImU64 sz, ImU64 count, ImFileHandle f) { return fwrite(data, (size_t)sz, (size_t)count, f); }
#endif // #ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
// Helper: Load file content into memory
// Memory allocated with IM_ALLOC(), must be freed by user using IM_FREE() == ImGui::MemFree()
void* ImFileLoadToMemory(const char* filename, const char* mode, size_t* out_file_size, int padding_bytes)
{
IM_ASSERT(filename && mode);
if (out_file_size)
*out_file_size = 0;
ImFileHandle f;
if ((f = ImFileOpen(filename, mode)) == NULL)
return NULL;
size_t file_size = (size_t)ImFileGetSize(f);
if (file_size == (size_t)-1)
{
ImFileClose(f);
return NULL;
}
void* file_data = IM_ALLOC(file_size + padding_bytes);
if (file_data == NULL)
{
ImFileClose(f);
return NULL;
}
if (ImFileRead(file_data, 1, file_size, f) != file_size)
{
ImFileClose(f);
IM_FREE(file_data);
return NULL;
}
if (padding_bytes > 0)
memset((void*)(((char*)file_data) + file_size), 0, (size_t)padding_bytes);
ImFileClose(f);
if (out_file_size)
*out_file_size = file_size;
return file_data;
}
//-----------------------------------------------------------------------------
// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
//-----------------------------------------------------------------------------
// Convert UTF-8 to 32-bit character, process single character input.
// Based on stb_from_utf8() from github.com/nothings/stb/
// We handle UTF-8 decoding error by skipping forward.
int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end)
{
unsigned int c = (unsigned int)-1;
const unsigned char* str = (const unsigned char*)in_text;
if (!(*str & 0x80))
{
c = (unsigned int)(*str++);
*out_char = c;
return 1;
}
if ((*str & 0xe0) == 0xc0)
{
*out_char = IM_UNICODE_CODEPOINT_INVALID; // will be invalid but not end of string
if (in_text_end && in_text_end - (const char*)str < 2) return 1;
if (*str < 0xc2) return 2;
c = (unsigned int)((*str++ & 0x1f) << 6);
if ((*str & 0xc0) != 0x80) return 2;
c += (*str++ & 0x3f);
*out_char = c;
return 2;
}
if ((*str & 0xf0) == 0xe0)
{
*out_char = IM_UNICODE_CODEPOINT_INVALID; // will be invalid but not end of string
if (in_text_end && in_text_end - (const char*)str < 3) return 1;
if (*str == 0xe0 && (str[1] < 0xa0 || str[1] > 0xbf)) return 3;
if (*str == 0xed && str[1] > 0x9f) return 3; // str[1] < 0x80 is checked below
c = (unsigned int)((*str++ & 0x0f) << 12);
if ((*str & 0xc0) != 0x80) return 3;
c += (unsigned int)((*str++ & 0x3f) << 6);
if ((*str & 0xc0) != 0x80) return 3;
c += (*str++ & 0x3f);
*out_char = c;
return 3;
}
if ((*str & 0xf8) == 0xf0)
{
*out_char = IM_UNICODE_CODEPOINT_INVALID; // will be invalid but not end of string
if (in_text_end && in_text_end - (const char*)str < 4) return 1;
if (*str > 0xf4) return 4;
if (*str == 0xf0 && (str[1] < 0x90 || str[1] > 0xbf)) return 4;
if (*str == 0xf4 && str[1] > 0x8f) return 4; // str[1] < 0x80 is checked below
c = (unsigned int)((*str++ & 0x07) << 18);
if ((*str & 0xc0) != 0x80) return 4;
c += (unsigned int)((*str++ & 0x3f) << 12);
if ((*str & 0xc0) != 0x80) return 4;
c += (unsigned int)((*str++ & 0x3f) << 6);
if ((*str & 0xc0) != 0x80) return 4;
c += (*str++ & 0x3f);
// utf-8 encodings of values used in surrogate pairs are invalid
if ((c & 0xFFFFF800) == 0xD800) return 4;
*out_char = c;
return 4;
}
*out_char = 0;
return 0;
}
int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining)
{
ImWchar* buf_out = buf;
ImWchar* buf_end = buf + buf_size;
while (buf_out < buf_end-1 && (!in_text_end || in_text < in_text_end) && *in_text)
{
unsigned int c;
in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
if (c == 0)
break;
if (c <= IM_UNICODE_CODEPOINT_MAX) // FIXME: Losing characters that don't fit in 2 bytes
*buf_out++ = (ImWchar)c;
}
*buf_out = 0;
if (in_text_remaining)
*in_text_remaining = in_text;
return (int)(buf_out - buf);
}
int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end)
{
int char_count = 0;
while ((!in_text_end || in_text < in_text_end) && *in_text)
{
unsigned int c;
in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
if (c == 0)
break;
if (c <= IM_UNICODE_CODEPOINT_MAX)
char_count++;
}
return char_count;
}
// Based on stb_to_utf8() from github.com/nothings/stb/
static inline int ImTextCharToUtf8(char* buf, int buf_size, unsigned int c)
{
if (c < 0x80)
{
buf[0] = (char)c;
return 1;
}
if (c < 0x800)
{
if (buf_size < 2) return 0;
buf[0] = (char)(0xc0 + (c >> 6));
buf[1] = (char)(0x80 + (c & 0x3f));
return 2;
}
if (c >= 0xdc00 && c < 0xe000)
{
return 0;
}
if (c >= 0xd800 && c < 0xdc00)
{
if (buf_size < 4) return 0;
buf[0] = (char)(0xf0 + (c >> 18));
buf[1] = (char)(0x80 + ((c >> 12) & 0x3f));
buf[2] = (char)(0x80 + ((c >> 6) & 0x3f));
buf[3] = (char)(0x80 + ((c ) & 0x3f));
return 4;
}
//else if (c < 0x10000)
{
if (buf_size < 3) return 0;
buf[0] = (char)(0xe0 + (c >> 12));
buf[1] = (char)(0x80 + ((c>> 6) & 0x3f));
buf[2] = (char)(0x80 + ((c ) & 0x3f));
return 3;
}
}
// Not optimal but we very rarely use this function.
int ImTextCountUtf8BytesFromChar(const char* in_text, const char* in_text_end)
{
unsigned int dummy = 0;
return ImTextCharFromUtf8(&dummy, in_text, in_text_end);
}
static inline int ImTextCountUtf8BytesFromChar(unsigned int c)
{
if (c < 0x80) return 1;
if (c < 0x800) return 2;
if (c >= 0xdc00 && c < 0xe000) return 0;
if (c >= 0xd800 && c < 0xdc00) return 4;
return 3;
}
int ImTextStrToUtf8(char* buf, int buf_size, const ImWchar* in_text, const ImWchar* in_text_end)
{
char* buf_out = buf;
const char* buf_end = buf + buf_size;
while (buf_out < buf_end-1 && (!in_text_end || in_text < in_text_end) && *in_text)
{
unsigned int c = (unsigned int)(*in_text++);
if (c < 0x80)
*buf_out++ = (char)c;
else
buf_out += ImTextCharToUtf8(buf_out, (int)(buf_end-buf_out-1), c);
}
*buf_out = 0;
return (int)(buf_out - buf);
}
int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end)
{
int bytes_count = 0;
while ((!in_text_end || in_text < in_text_end) && *in_text)
{
unsigned int c = (unsigned int)(*in_text++);
if (c < 0x80)
bytes_count++;
else
bytes_count += ImTextCountUtf8BytesFromChar(c);
}
return bytes_count;
}
//-----------------------------------------------------------------------------
// [SECTION] MISC HELPERS/UTILTIES (Color functions)
// Note: The Convert functions are early design which are not consistent with other API.
//-----------------------------------------------------------------------------
ImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in)
{
float s = 1.0f/255.0f;
return ImVec4(
((in >> IM_COL32_R_SHIFT) & 0xFF) * s,
((in >> IM_COL32_G_SHIFT) & 0xFF) * s,
((in >> IM_COL32_B_SHIFT) & 0xFF) * s,
((in >> IM_COL32_A_SHIFT) & 0xFF) * s);
}
ImU32 ImGui::ColorConvertFloat4ToU32(const ImVec4& in)
{
ImU32 out;
out = ((ImU32)IM_F32_TO_INT8_SAT(in.x)) << IM_COL32_R_SHIFT;
out |= ((ImU32)IM_F32_TO_INT8_SAT(in.y)) << IM_COL32_G_SHIFT;
out |= ((ImU32)IM_F32_TO_INT8_SAT(in.z)) << IM_COL32_B_SHIFT;
out |= ((ImU32)IM_F32_TO_INT8_SAT(in.w)) << IM_COL32_A_SHIFT;
return out;
}
// Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592
// Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv
void ImGui::ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v)
{
float K = 0.f;
if (g < b)
{
ImSwap(g, b);
K = -1.f;
}
if (r < g)
{
ImSwap(r, g);
K = -2.f / 6.f - K;
}
const float chroma = r - (g < b ? g : b);
out_h = ImFabs(K + (g - b) / (6.f * chroma + 1e-20f));
out_s = chroma / (r + 1e-20f);
out_v = r;
}
// Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593
// also http://en.wikipedia.org/wiki/HSL_and_HSV
void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b)
{
if (s == 0.0f)
{
// gray
out_r = out_g = out_b = v;
return;
}
h = ImFmod(h, 1.0f) / (60.0f/360.0f);
int i = (int)h;
float f = h - (float)i;
float p = v * (1.0f - s);
float q = v * (1.0f - s * f);
float t = v * (1.0f - s * (1.0f - f));
switch (i)
{
case 0: out_r = v; out_g = t; out_b = p; break;
case 1: out_r = q; out_g = v; out_b = p; break;
case 2: out_r = p; out_g = v; out_b = t; break;
case 3: out_r = p; out_g = q; out_b = v; break;
case 4: out_r = t; out_g = p; out_b = v; break;
case 5: default: out_r = v; out_g = p; out_b = q; break;
}
}
//-----------------------------------------------------------------------------
// [SECTION] ImGuiStorage
// Helper: Key->value storage
//-----------------------------------------------------------------------------
// std::lower_bound but without the bullshit
static ImGuiStorage::ImGuiStoragePair* LowerBound(ImVector<ImGuiStorage::ImGuiStoragePair>& data, ImGuiID key)
{
ImGuiStorage::ImGuiStoragePair* first = data.Data;
ImGuiStorage::ImGuiStoragePair* last = data.Data + data.Size;
size_t count = (size_t)(last - first);
while (count > 0)
{
size_t count2 = count >> 1;
ImGuiStorage::ImGuiStoragePair* mid = first + count2;
if (mid->key < key)
{
first = ++mid;
count -= count2 + 1;
}
else
{
count = count2;
}
}
return first;
}
// For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once.
void ImGuiStorage::BuildSortByKey()
{
struct StaticFunc
{
static int IMGUI_CDECL PairCompareByID(const void* lhs, const void* rhs)
{
// We can't just do a subtraction because qsort uses signed integers and subtracting our ID doesn't play well with that.
if (((const ImGuiStoragePair*)lhs)->key > ((const ImGuiStoragePair*)rhs)->key) return +1;
if (((const ImGuiStoragePair*)lhs)->key < ((const ImGuiStoragePair*)rhs)->key) return -1;
return 0;
}
};
if (Data.Size > 1)
ImQsort(Data.Data, (size_t)Data.Size, sizeof(ImGuiStoragePair), StaticFunc::PairCompareByID);
}
int ImGuiStorage::GetInt(ImGuiID key, int default_val) const
{
ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
if (it == Data.end() || it->key != key)
return default_val;
return it->val_i;
}
bool ImGuiStorage::GetBool(ImGuiID key, bool default_val) const
{
return GetInt(key, default_val ? 1 : 0) != 0;
}
float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const
{
ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
if (it == Data.end() || it->key != key)
return default_val;
return it->val_f;
}
void* ImGuiStorage::GetVoidPtr(ImGuiID key) const
{
ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
if (it == Data.end() || it->key != key)
return NULL;
return it->val_p;
}
// References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer.
int* ImGuiStorage::GetIntRef(ImGuiID key, int default_val)
{
ImGuiStoragePair* it = LowerBound(Data, key);
if (it == Data.end() || it->key != key)
it = Data.insert(it, ImGuiStoragePair(key, default_val));
return &it->val_i;
}
bool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val)
{
return (bool*)GetIntRef(key, default_val ? 1 : 0);
}
float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val)
{
ImGuiStoragePair* it = LowerBound(Data, key);
if (it == Data.end() || it->key != key)
it = Data.insert(it, ImGuiStoragePair(key, default_val));
return &it->val_f;
}
void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val)
{
ImGuiStoragePair* it = LowerBound(Data, key);
if (it == Data.end() || it->key != key)
it = Data.insert(it, ImGuiStoragePair(key, default_val));
return &it->val_p;
}
// FIXME-OPT: Need a way to reuse the result of lower_bound when doing GetInt()/SetInt() - not too bad because it only happens on explicit interaction (maximum one a frame)
void ImGuiStorage::SetInt(ImGuiID key, int val)
{
ImGuiStoragePair* it = LowerBound(Data, key);
if (it == Data.end() || it->key != key)
{
Data.insert(it, ImGuiStoragePair(key, val));
return;
}
it->val_i = val;
}
void ImGuiStorage::SetBool(ImGuiID key, bool val)
{
SetInt(key, val ? 1 : 0);
}
void ImGuiStorage::SetFloat(ImGuiID key, float val)
{
ImGuiStoragePair* it = LowerBound(Data, key);
if (it == Data.end() || it->key != key)
{
Data.insert(it, ImGuiStoragePair(key, val));
return;
}
it->val_f = val;
}
void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val)
{
ImGuiStoragePair* it = LowerBound(Data, key);
if (it == Data.end() || it->key != key)
{
Data.insert(it, ImGuiStoragePair(key, val));
return;
}
it->val_p = val;
}
void ImGuiStorage::SetAllInt(int v)
{
for (int i = 0; i < Data.Size; i++)
Data[i].val_i = v;
}
//-----------------------------------------------------------------------------
// [SECTION] ImGuiTextFilter
//-----------------------------------------------------------------------------
// Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]"
ImGuiTextFilter::ImGuiTextFilter(const char* default_filter)
{
if (default_filter)
{
ImStrncpy(InputBuf, default_filter, IM_ARRAYSIZE(InputBuf));
Build();
}
else
{
InputBuf[0] = 0;
CountGrep = 0;
}
}
bool ImGuiTextFilter::Draw(const char* label, float width)
{
if (width != 0.0f)
ImGui::SetNextItemWidth(width);
bool value_changed = ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf));
if (value_changed)
Build();
return value_changed;
}
void ImGuiTextFilter::ImGuiTextRange::split(char separator, ImVector<ImGuiTextRange>* out) const
{
out->resize(0);
const char* wb = b;
const char* we = wb;
while (we < e)
{
if (*we == separator)
{
out->push_back(ImGuiTextRange(wb, we));
wb = we + 1;
}
we++;
}
if (wb != we)
out->push_back(ImGuiTextRange(wb, we));
}
void ImGuiTextFilter::Build()
{
Filters.resize(0);
ImGuiTextRange input_range(InputBuf, InputBuf+strlen(InputBuf));
input_range.split(',', &Filters);
CountGrep = 0;
for (int i = 0; i != Filters.Size; i++)
{
ImGuiTextRange& f = Filters[i];
while (f.b < f.e && ImCharIsBlankA(f.b[0]))
f.b++;
while (f.e > f.b && ImCharIsBlankA(f.e[-1]))
f.e--;
if (f.empty())
continue;
if (Filters[i].b[0] != '-')
CountGrep += 1;
}
}
bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const
{
if (Filters.empty())
return true;
if (text == NULL)
text = "";
for (int i = 0; i != Filters.Size; i++)
{
const ImGuiTextRange& f = Filters[i];
if (f.empty())
continue;
if (f.b[0] == '-')
{
// Subtract
if (ImStristr(text, text_end, f.b + 1, f.e) != NULL)
return false;
}
else
{
// Grep
if (ImStristr(text, text_end, f.b, f.e) != NULL)
return true;
}
}
// Implicit * grep
if (CountGrep == 0)
return true;
return false;
}
//-----------------------------------------------------------------------------
// [SECTION] ImGuiTextBuffer
//-----------------------------------------------------------------------------
// On some platform vsnprintf() takes va_list by reference and modifies it.
// va_copy is the 'correct' way to copy a va_list but Visual Studio prior to 2013 doesn't have it.
#ifndef va_copy
#if defined(__GNUC__) || defined(__clang__)
#define va_copy(dest, src) __builtin_va_copy(dest, src)
#else
#define va_copy(dest, src) (dest = src)
#endif
#endif
char ImGuiTextBuffer::EmptyString[1] = { 0 };
void ImGuiTextBuffer::append(const char* str, const char* str_end)
{
int len = str_end ? (int)(str_end - str) : (int)strlen(str);
// Add zero-terminator the first time
const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
const int needed_sz = write_off + len;
if (write_off + len >= Buf.Capacity)
{
int new_capacity = Buf.Capacity * 2;
Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
}
Buf.resize(needed_sz);
memcpy(&Buf[write_off - 1], str, (size_t)len);
Buf[write_off - 1 + len] = 0;
}
void ImGuiTextBuffer::appendf(const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
appendfv(fmt, args);
va_end(args);
}
// Helper: Text buffer for logging/accumulating text
void ImGuiTextBuffer::appendfv(const char* fmt, va_list args)
{
va_list args_copy;
va_copy(args_copy, args);
int len = ImFormatStringV(NULL, 0, fmt, args); // FIXME-OPT: could do a first pass write attempt, likely successful on first pass.
if (len <= 0)
{
va_end(args_copy);
return;
}
// Add zero-terminator the first time
const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
const int needed_sz = write_off + len;
if (write_off + len >= Buf.Capacity)
{
int new_capacity = Buf.Capacity * 2;
Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
}
Buf.resize(needed_sz);
ImFormatStringV(&Buf[write_off - 1], (size_t)len + 1, fmt, args_copy);
va_end(args_copy);
}
//-----------------------------------------------------------------------------
// [SECTION] ImGuiListClipper
// This is currently not as flexible/powerful as it should be and really confusing/spaghetti, mostly because we changed
// the API mid-way through development and support two ways to using the clipper, needs some rework (see TODO)
//-----------------------------------------------------------------------------
// Helper to calculate coarse clipping of large list of evenly sized items.
// NB: Prefer using the ImGuiListClipper higher-level helper if you can! Read comments and instructions there on how those use this sort of pattern.
// NB: 'items_count' is only used to clamp the result, if you don't know your count you can use INT_MAX
void ImGui::CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (g.LogEnabled)
{
// If logging is active, do not perform any clipping
*out_items_display_start = 0;
*out_items_display_end = items_count;
return;
}
if (window->SkipItems)
{
*out_items_display_start = *out_items_display_end = 0;
return;
}
// We create the union of the ClipRect and the NavScoringRect which at worst should be 1 page away from ClipRect
ImRect unclipped_rect = window->ClipRect;
if (g.NavMoveRequest)
unclipped_rect.Add(g.NavScoringRectScreen);
const ImVec2 pos = window->DC.CursorPos;
int start = (int)((unclipped_rect.Min.y - pos.y) / items_height);
int end = (int)((unclipped_rect.Max.y - pos.y) / items_height);
// When performing a navigation request, ensure we have one item extra in the direction we are moving to
if (g.NavMoveRequest && g.NavMoveClipDir == ImGuiDir_Up)
start--;
if (g.NavMoveRequest && g.NavMoveClipDir == ImGuiDir_Down)
end++;
start = ImClamp(start, 0, items_count);
end = ImClamp(end + 1, start, items_count);
*out_items_display_start = start;
*out_items_display_end = end;
}
static void SetCursorPosYAndSetupDummyPrevLine(float pos_y, float line_height)
{
// Set cursor position and a few other things so that SetScrollHereY() and Columns() can work when seeking cursor.
// FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue.
// The clipper should probably have a 4th step to display the last item in a regular manner.
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
window->DC.CursorPos.y = pos_y;
window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, pos_y);
window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y - line_height; // Setting those fields so that SetScrollHereY() can properly function after the end of our clipper usage.
window->DC.PrevLineSize.y = (line_height - g.Style.ItemSpacing.y); // If we end up needing more accurate data (to e.g. use SameLine) we may as well make the clipper have a fourth step to let user process and display the last item in their list.
if (ImGuiColumns* columns = window->DC.CurrentColumns)
columns->LineMinY = window->DC.CursorPos.y; // Setting this so that cell Y position are set properly
}
// Use case A: Begin() called from constructor with items_height<0, then called again from Sync() in StepNo 1
// Use case B: Begin() called from constructor with items_height>0
// FIXME-LEGACY: Ideally we should remove the Begin/End functions but they are part of the legacy API we still support. This is why some of the code in Step() calling Begin() and reassign some fields, spaghetti style.
void ImGuiListClipper::Begin(int count, float items_height)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
StartPosY = window->DC.CursorPos.y;
ItemsHeight = items_height;
ItemsCount = count;
StepNo = 0;
DisplayEnd = DisplayStart = -1;
if (ItemsHeight > 0.0f)
{
ImGui::CalcListClipping(ItemsCount, ItemsHeight, &DisplayStart, &DisplayEnd); // calculate how many to clip/display
if (DisplayStart > 0)
SetCursorPosYAndSetupDummyPrevLine(StartPosY + DisplayStart * ItemsHeight, ItemsHeight); // advance cursor
StepNo = 2;
}
}
void ImGuiListClipper::End()
{
if (ItemsCount < 0)
return;
// In theory here we should assert that ImGui::GetCursorPosY() == StartPosY + DisplayEnd * ItemsHeight, but it feels saner to just seek at the end and not assert/crash the user.
if (ItemsCount < INT_MAX)
SetCursorPosYAndSetupDummyPrevLine(StartPosY + ItemsCount * ItemsHeight, ItemsHeight); // advance cursor
ItemsCount = -1;
StepNo = 3;
}
bool ImGuiListClipper::Step()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (ItemsCount == 0 || window->SkipItems)
{
ItemsCount = -1;
return false;
}
if (StepNo == 0) // Step 0: the clipper let you process the first element, regardless of it being visible or not, so we can measure the element height.
{
DisplayStart = 0;
DisplayEnd = 1;
StartPosY = window->DC.CursorPos.y;
StepNo = 1;
return true;
}
if (StepNo == 1) // Step 1: the clipper infer height from first element, calculate the actual range of elements to display, and position the cursor before the first element.
{
if (ItemsCount == 1) { ItemsCount = -1; return false; }
float items_height = window->DC.CursorPos.y - StartPosY;
IM_ASSERT(items_height > 0.0f); // If this triggers, it means Item 0 hasn't moved the cursor vertically
Begin(ItemsCount - 1, items_height);
DisplayStart++;
DisplayEnd++;
StepNo = 3;
return true;
}
if (StepNo == 2) // Step 2: dummy step only required if an explicit items_height was passed to constructor or Begin() and user still call Step(). Does nothing and switch to Step 3.
{
IM_ASSERT(DisplayStart >= 0 && DisplayEnd >= 0);
StepNo = 3;
return true;
}
if (StepNo == 3) // Step 3: the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd), advance the cursor to the end of the list and then returns 'false' to end the loop.
End();
return false;
}
//-----------------------------------------------------------------------------
// [SECTION] RENDER HELPERS
// Some of those (internal) functions are currently quite a legacy mess - their signature and behavior will change.
// Also see imgui_draw.cpp for some more which have been reworked to not rely on ImGui:: state.
//-----------------------------------------------------------------------------
ImU32 ImGui::GetColorU32(ImGuiCol idx, float alpha_mul)
{
ImGuiStyle& style = GImGui->Style;
ImVec4 c = style.Colors[idx];
c.w *= style.Alpha * alpha_mul;
return ColorConvertFloat4ToU32(c);
}
ImU32 ImGui::GetColorU32(const ImVec4& col)
{
ImGuiStyle& style = GImGui->Style;
ImVec4 c = col;
c.w *= style.Alpha;
return ColorConvertFloat4ToU32(c);
}
const ImVec4& ImGui::GetStyleColorVec4(ImGuiCol idx)
{
ImGuiStyle& style = GImGui->Style;
return style.Colors[idx];
}
ImU32 ImGui::GetColorU32(ImU32 col)
{
ImGuiStyle& style = GImGui->Style;
if (style.Alpha >= 1.0f)
return col;
ImU32 a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT;
a = (ImU32)(a * style.Alpha); // We don't need to clamp 0..255 because Style.Alpha is in 0..1 range.
return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT);
}
const char* ImGui::FindRenderedTextEnd(const char* text, const char* text_end)
{
const char* text_display_end = text;
if (!text_end)
text_end = (const char*)-1;
while (text_display_end < text_end && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#'))
text_display_end++;
return text_display_end;
}
// Internal ImGui functions to render text
// RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText()
void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash, ImU32 color)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
// Hide anything after a '##' string
const char* text_display_end;
if (hide_text_after_hash)
{
text_display_end = FindRenderedTextEnd(text, text_end);
}
else
{
if (!text_end)
text_end = text + strlen(text); // FIXME-OPT
text_display_end = text_end;
}
if (text != text_display_end)
{
window->DrawList->AddText(g.Font, g.FontSize, pos, (color == 0 ? GetColorU32(ImGuiCol_Text) : color), text, text_display_end);
if (g.LogEnabled)
LogRenderedText(&pos, text, text_display_end);
}
}
void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width, ImU32 color)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (!text_end)
text_end = text + strlen(text); // FIXME-OPT
if (text != text_end)
{
window->DrawList->AddText(g.Font, g.FontSize, pos, (color == 0 ? GetColorU32(ImGuiCol_Text) : color), text, text_end, wrap_width);
if (g.LogEnabled)
LogRenderedText(&pos, text, text_end);
}
}
// Default clip_rect uses (pos_min,pos_max)
// Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping rectangle edges)
void ImGui::RenderTextClippedEx(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_display_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect, ImU32 color)
{
// Perform CPU side clipping for single clipped element to avoid using scissor state
ImVec2 pos = pos_min;
const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_display_end, false, 0.0f);
const ImVec2* clip_min = clip_rect ? &clip_rect->Min : &pos_min;
const ImVec2* clip_max = clip_rect ? &clip_rect->Max : &pos_max;
bool need_clipping = (pos.x + text_size.x >= clip_max->x) || (pos.y + text_size.y >= clip_max->y);
if (clip_rect) // If we had no explicit clipping rectangle then pos==clip_min
need_clipping |= (pos.x < clip_min->x) || (pos.y < clip_min->y);
// Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment.
if (align.x > 0.0f) pos.x = ImMax(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x);
if (align.y > 0.0f) pos.y = ImMax(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y);
// Render
if (need_clipping)
{
ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y);
draw_list->AddText(NULL, 0.0f, pos, (color != 0 ? color : GetColorU32(ImGuiCol_Text)), text, text_display_end, 0.0f, &fine_clip_rect);
}
else
{
draw_list->AddText(NULL, 0.0f, pos, (color != 0 ? color : GetColorU32(ImGuiCol_Text)), text, text_display_end, 0.0f, NULL);
}
}
void ImGui::RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect, ImU32 color)
{
// Hide anything after a '##' string
const char* text_display_end = FindRenderedTextEnd(text, text_end);
const int text_len = (int)(text_display_end - text);
if (text_len == 0)
return;
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
RenderTextClippedEx(window->DrawList, pos_min, pos_max, text, text_display_end, text_size_if_known, align, clip_rect, color);
if (g.LogEnabled)
LogRenderedText(&pos_min, text, text_display_end);
}
// Another overly complex function until we reorganize everything into a nice all-in-one helper.
// This is made more complex because we have dissociated the layout rectangle (pos_min..pos_max) which define _where_ the ellipsis is, from actual clipping of text and limit of the ellipsis display.
// This is because in the context of tabs we selectively hide part of the text when the Close Button appears, but we don't want the ellipsis to move.
void ImGui::RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, float clip_max_x, float ellipsis_max_x, const char* text, const char* text_end_full, const ImVec2* text_size_if_known)
{
ImGuiContext& g = *GImGui;
if (text_end_full == NULL)
text_end_full = FindRenderedTextEnd(text);
const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_end_full, false, 0.0f);
//draw_list->AddLine(ImVec2(pos_max.x, pos_min.y - 4), ImVec2(pos_max.x, pos_max.y + 4), IM_COL32(0, 0, 255, 255));
//draw_list->AddLine(ImVec2(ellipsis_max_x, pos_min.y-2), ImVec2(ellipsis_max_x, pos_max.y+2), IM_COL32(0, 255, 0, 255));
//draw_list->AddLine(ImVec2(clip_max_x, pos_min.y), ImVec2(clip_max_x, pos_max.y), IM_COL32(255, 0, 0, 255));
// FIXME: We could technically remove (last_glyph->AdvanceX - last_glyph->X1) from text_size.x here and save a few pixels.
if (text_size.x > pos_max.x - pos_min.x)
{
// Hello wo...
// | | |
// min max ellipsis_max
// <-> this is generally some padding value
const ImFont* font = draw_list->_Data->Font;
const float font_size = draw_list->_Data->FontSize;
const char* text_end_ellipsis = NULL;
ImWchar ellipsis_char = font->EllipsisChar;
int ellipsis_char_count = 1;
if (ellipsis_char == (ImWchar)-1)
{
ellipsis_char = (ImWchar)'.';
ellipsis_char_count = 3;
}
const ImFontGlyph* glyph = font->FindGlyph(ellipsis_char);
float ellipsis_glyph_width = glyph->X1; // Width of the glyph with no padding on either side
float ellipsis_total_width = ellipsis_glyph_width; // Full width of entire ellipsis
if (ellipsis_char_count > 1)
{
// Full ellipsis size without free spacing after it.
const float spacing_between_dots = 1.0f * (draw_list->_Data->FontSize / font->FontSize);
ellipsis_glyph_width = glyph->X1 - glyph->X0 + spacing_between_dots;
ellipsis_total_width = ellipsis_glyph_width * (float)ellipsis_char_count - spacing_between_dots;
}
// We can now claim the space between pos_max.x and ellipsis_max.x
const float text_avail_width = ImMax((ImMax(pos_max.x, ellipsis_max_x) - ellipsis_total_width) - pos_min.x, 1.0f);
float text_size_clipped_x = font->CalcTextSizeA(font_size, text_avail_width, 0.0f, text, text_end_full, &text_end_ellipsis).x;
if (text == text_end_ellipsis && text_end_ellipsis < text_end_full)
{
// Always display at least 1 character if there's no room for character + ellipsis
text_end_ellipsis = text + ImTextCountUtf8BytesFromChar(text, text_end_full);
text_size_clipped_x = font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text, text_end_ellipsis).x;
}
while (text_end_ellipsis > text && ImCharIsBlankA(text_end_ellipsis[-1]))
{
// Trim trailing space before ellipsis (FIXME: Supporting non-ascii blanks would be nice, for this we need a function to backtrack in UTF-8 text)
text_end_ellipsis--;
text_size_clipped_x -= font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text_end_ellipsis, text_end_ellipsis + 1).x; // Ascii blanks are always 1 byte
}
// Render text, render ellipsis
RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_ellipsis, &text_size, ImVec2(0.0f, 0.0f));
float ellipsis_x = pos_min.x + text_size_clipped_x;
if (ellipsis_x + ellipsis_total_width <= ellipsis_max_x)
for (int i = 0; i < ellipsis_char_count; i++)
{
font->RenderChar(draw_list, font_size, ImVec2(ellipsis_x, pos_min.y), GetColorU32(ImGuiCol_Text), ellipsis_char);
ellipsis_x += ellipsis_glyph_width;
}
}
else
{
RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_full, &text_size, ImVec2(0.0f, 0.0f));
}
if (g.LogEnabled)
LogRenderedText(&pos_min, text, text_end_full);
}
// Render a rectangle shaped with optional rounding and borders
void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, float rounding)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding);
const float border_size = g.Style.FrameBorderSize;
if (border && border_size > 0.0f)
{
window->DrawList->AddRect(p_min+ImVec2(1,1), p_max+ImVec2(1,1), GetColorU32(ImGuiCol_BorderShadow), rounding, ImDrawCornerFlags_All, border_size);
window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, ImDrawCornerFlags_All, border_size);
}
}
void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, ImU32 border_col, float rounding) {
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding);
const float border_size = g.Style.FrameBorderSize;
if (border_size > 0.0f) {
window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, ImDrawCornerFlags_All, border_size);
window->DrawList->AddRect(p_min, p_max, border_col, rounding, ImDrawCornerFlags_All, border_size);
}
}
void ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
const float border_size = g.Style.FrameBorderSize;
if (border_size > 0.0f)
{
window->DrawList->AddRect(p_min+ImVec2(1,1), p_max+ImVec2(1,1), GetColorU32(ImGuiCol_BorderShadow), rounding, ImDrawCornerFlags_All, border_size);
window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, ImDrawCornerFlags_All, border_size);
}
}
void ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, ImU32 border_col, float border_size, float rounding)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (border_size > 0.0f) {
window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, ImDrawCornerFlags_All, border_size);
window->DrawList->AddRect(p_min, p_max, border_col, rounding, ImDrawCornerFlags_All, border_size);
}
}
// Render an arrow aimed to be aligned with text (p_min is a position in the same space text would be positioned). To e.g. denote expanded/collapsed state
void ImGui::RenderArrow(ImDrawList* draw_list, ImVec2 pos, ImU32 col, ImGuiDir dir, float scale)
{
const float h = draw_list->_Data->FontSize * 1.00f;
float r = h * 0.40f * scale;
ImVec2 center = pos + ImVec2(h * 0.50f, h * 0.50f * scale);
ImVec2 a, b, c;
switch (dir)
{
case ImGuiDir_Up:
case ImGuiDir_Down:
if (dir == ImGuiDir_Up) r = -r;
a = ImVec2(+0.000f,+0.750f) * r;
b = ImVec2(-0.866f,-0.750f) * r;
c = ImVec2(+0.866f,-0.750f) * r;
break;
case ImGuiDir_Left:
case ImGuiDir_Right:
if (dir == ImGuiDir_Left) r = -r;
a = ImVec2(+0.750f,+0.000f) * r;
b = ImVec2(-0.750f,+0.866f) * r;
c = ImVec2(-0.750f,-0.866f) * r;
break;
case ImGuiDir_None:
case ImGuiDir_COUNT:
IM_ASSERT(0);
break;
}
draw_list->AddTriangleFilled(center + a, center + b, center + c, col);
}
void ImGui::RenderBullet(ImDrawList* draw_list, ImVec2 pos, ImU32 col)
{
draw_list->AddCircleFilled(pos, draw_list->_Data->FontSize * 0.20f, col, 8);
}
void ImGui::RenderCheckMark(ImVec2 pos, ImU32 col, float sz)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
float thickness = ImMax(sz / 5.0f, 1.0f);
sz -= thickness*0.5f;
pos += ImVec2(thickness*0.25f, thickness*0.25f);
float third = sz / 3.0f;
float bx = pos.x + third;
float by = pos.y + sz - third*0.5f;
window->DrawList->PathLineTo(ImVec2(bx - third, by - third));
window->DrawList->PathLineTo(ImVec2(bx, by));
window->DrawList->PathLineTo(ImVec2(bx + third*2, by - third*2));
window->DrawList->PathStroke(col, false, thickness);
}
void ImGui::RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFlags flags)
{
ImGuiContext& g = *GImGui;
if (id != g.NavId)
return;
if (g.NavDisableHighlight && !(flags & ImGuiNavHighlightFlags_AlwaysDraw))
return;
ImGuiWindow* window = g.CurrentWindow;
if (window->DC.NavHideHighlightOneFrame)
return;
float rounding = (flags & ImGuiNavHighlightFlags_NoRounding) ? 0.0f : g.Style.FrameRounding;
ImRect display_rect = bb;
display_rect.ClipWith(window->ClipRect);
if (flags & ImGuiNavHighlightFlags_TypeDefault)
{
const float THICKNESS = 2.0f;
const float DISTANCE = 3.0f + THICKNESS * 0.5f;
display_rect.Expand(ImVec2(DISTANCE,DISTANCE));
bool fully_visible = window->ClipRect.Contains(display_rect);
if (!fully_visible)
window->DrawList->PushClipRect(display_rect.Min, display_rect.Max);
window->DrawList->AddRect(display_rect.Min + ImVec2(THICKNESS*0.5f,THICKNESS*0.5f), display_rect.Max - ImVec2(THICKNESS*0.5f,THICKNESS*0.5f), GetColorU32(ImGuiCol_NavHighlight), rounding, ImDrawCornerFlags_All, THICKNESS);
if (!fully_visible)
window->DrawList->PopClipRect();
}
if (flags & ImGuiNavHighlightFlags_TypeThin)
{
window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavHighlight), rounding, ~0, 1.0f);
}
}
//-----------------------------------------------------------------------------
// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
//-----------------------------------------------------------------------------
// ImGuiWindow is mostly a dumb struct. It merely has a constructor and a few helper methods
ImGuiWindow::ImGuiWindow(ImGuiContext* context, const char* name)
: DrawListInst(&context->DrawListSharedData)
{
Name = ImStrdup(name);
ID = ImHashStr(name);
IDStack.push_back(ID);
Flags = ImGuiWindowFlags_None;
Pos = ImVec2(0.0f, 0.0f);
Size = SizeFull = ImVec2(0.0f, 0.0f);
ContentSize = ContentSizeExplicit = ImVec2(0.0f, 0.0f);
WindowPadding = ImVec2(0.0f, 0.0f);
WindowRounding = 0.0f;
WindowBorderSize = 0.0f;
NameBufLen = (int)strlen(name) + 1;
MoveId = GetID("#MOVE");
ChildId = 0;
Scroll = ImVec2(0.0f, 0.0f);
ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f);
ScrollbarSizes = ImVec2(0.0f, 0.0f);
ScrollbarX = ScrollbarY = false;
Active = WasActive = false;
WriteAccessed = false;
Collapsed = false;
WantCollapseToggle = false;
SkipItems = false;
Appearing = false;
Hidden = false;
IsFallbackWindow = false;
HasCloseButton = false;
ResizeBorderHeld = -1;
BeginCount = 0;
BeginOrderWithinParent = -1;
BeginOrderWithinContext = -1;
PopupId = 0;
AutoFitFramesX = AutoFitFramesY = -1;
AutoFitChildAxises = 0x00;
AutoFitOnlyGrows = false;
AutoPosLastDirection = ImGuiDir_None;
HiddenFramesCanSkipItems = HiddenFramesCannotSkipItems = 0;
SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = ImGuiCond_Always | ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing;
SetWindowPosVal = SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX);
InnerRect = ImRect(0.0f, 0.0f, 0.0f, 0.0f); // Clear so the InnerRect.GetSize() code in Begin() doesn't lead to overflow even if the result isn't used.
LastFrameActive = -1;
LastTimeActive = -1.0f;
ItemWidthDefault = 0.0f;
FontWindowScale = 1.0f;
SettingsOffset = -1;
DrawList = &DrawListInst;
DrawList->_OwnerName = Name;
ParentWindow = NULL;
RootWindow = NULL;
RootWindowForTitleBarHighlight = NULL;
RootWindowForNav = NULL;
NavLastIds[0] = NavLastIds[1] = 0;
NavRectRel[0] = NavRectRel[1] = ImRect();
NavLastChildNavWindow = NULL;
MemoryCompacted = false;
MemoryDrawListIdxCapacity = MemoryDrawListVtxCapacity = 0;
}
ImGuiWindow::~ImGuiWindow()
{
IM_ASSERT(DrawList == &DrawListInst);
IM_DELETE(Name);
for (int i = 0; i != ColumnsStorage.Size; i++)
ColumnsStorage[i].~ImGuiColumns();
}
ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end)
{
ImGuiID seed = IDStack.back();
ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
ImGui::KeepAliveID(id);
return id;
}
ImGuiID ImGuiWindow::GetID(const void* ptr)
{
ImGuiID seed = IDStack.back();
ImGuiID id = ImHashData(&ptr, sizeof(void*), seed);
ImGui::KeepAliveID(id);
return id;
}
ImGuiID ImGuiWindow::GetID(int n)
{
ImGuiID seed = IDStack.back();
ImGuiID id = ImHashData(&n, sizeof(n), seed);
ImGui::KeepAliveID(id);
return id;
}
ImGuiID ImGuiWindow::GetIDNoKeepAlive(const char* str, const char* str_end)
{
ImGuiID seed = IDStack.back();
return ImHashStr(str, str_end ? (str_end - str) : 0, seed);
}
ImGuiID ImGuiWindow::GetIDNoKeepAlive(const void* ptr)
{
ImGuiID seed = IDStack.back();
return ImHashData(&ptr, sizeof(void*), seed);
}
ImGuiID ImGuiWindow::GetIDNoKeepAlive(int n)
{
ImGuiID seed = IDStack.back();
return ImHashData(&n, sizeof(n), seed);
}
// This is only used in rare/specific situations to manufacture an ID out of nowhere.
ImGuiID ImGuiWindow::GetIDFromRectangle(const ImRect& r_abs)
{
ImGuiID seed = IDStack.back();
const int r_rel[4] = { (int)(r_abs.Min.x - Pos.x), (int)(r_abs.Min.y - Pos.y), (int)(r_abs.Max.x - Pos.x), (int)(r_abs.Max.y - Pos.y) };
ImGuiID id = ImHashData(&r_rel, sizeof(r_rel), seed);
ImGui::KeepAliveID(id);
return id;
}
static void SetCurrentWindow(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
g.CurrentWindow = window;
if (window)
g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
}
// Free up/compact internal window buffers, we can use this when a window becomes unused.
// This is currently unused by the library, but you may call this yourself for easy GC.
// Not freed:
// - ImGuiWindow, ImGuiWindowSettings, Name
// - StateStorage, ColumnsStorage (may hold useful data)
// This should have no noticeable visual effect. When the window reappear however, expect new allocation/buffer growth/copy cost.
void ImGui::GcCompactTransientWindowBuffers(ImGuiWindow* window)
{
window->MemoryCompacted = true;
window->MemoryDrawListIdxCapacity = window->DrawList->IdxBuffer.Capacity;
window->MemoryDrawListVtxCapacity = window->DrawList->VtxBuffer.Capacity;
window->IDStack.clear();
window->DrawList->ClearFreeMemory();
window->DC.ChildWindows.clear();
window->DC.ItemFlagsStack.clear();
window->DC.ItemWidthStack.clear();
window->DC.TextWrapPosStack.clear();
window->DC.GroupStack.clear();
}
void ImGui::GcAwakeTransientWindowBuffers(ImGuiWindow* window)
{
// We stored capacity of the ImDrawList buffer to reduce growth-caused allocation/copy when awakening.
// The other buffers tends to amortize much faster.
window->MemoryCompacted = false;
window->DrawList->IdxBuffer.reserve(window->MemoryDrawListIdxCapacity);
window->DrawList->VtxBuffer.reserve(window->MemoryDrawListVtxCapacity);
window->MemoryDrawListIdxCapacity = window->MemoryDrawListVtxCapacity = 0;
}
void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
g.ActiveIdIsJustActivated = (g.ActiveId != id);
if (g.ActiveIdIsJustActivated)
{
g.ActiveIdTimer = 0.0f;
g.ActiveIdHasBeenPressedBefore = false;
g.ActiveIdHasBeenEditedBefore = false;
if (id != 0)
{
g.LastActiveId = id;
g.LastActiveIdTimer = 0.0f;
}
}
g.ActiveId = id;
g.ActiveIdAllowOverlap = false;
g.ActiveIdWindow = window;
g.ActiveIdHasBeenEditedThisFrame = false;
if (id)
{
g.ActiveIdIsAlive = id;
g.ActiveIdSource = (g.NavActivateId == id || g.NavInputId == id || g.NavJustTabbedId == id || g.NavJustMovedToId == id) ? ImGuiInputSource_Nav : ImGuiInputSource_Mouse;
}
// Clear declaration of inputs claimed by the widget
// (Please note that this is WIP and not all keys/inputs are thoroughly declared by all widgets yet)
g.ActiveIdUsingNavDirMask = 0x00;
g.ActiveIdUsingNavInputMask = 0x00;
g.ActiveIdUsingKeyInputMask = 0x00;
}
void ImGui::ClearActiveID()
{
SetActiveID(0, NULL);
}
void ImGui::SetHoveredID(ImGuiID id)
{
ImGuiContext& g = *GImGui;
g.HoveredId = id;
g.HoveredIdAllowOverlap = false;
if (id != 0 && g.HoveredIdPreviousFrame != id)
g.HoveredIdTimer = g.HoveredIdNotActiveTimer = 0.0f;
}
ImGuiID ImGui::GetHoveredID()
{
ImGuiContext& g = *GImGui;
return g.HoveredId ? g.HoveredId : g.HoveredIdPreviousFrame;
}
void ImGui::KeepAliveID(ImGuiID id)
{
ImGuiContext& g = *GImGui;
if (g.ActiveId == id)
g.ActiveIdIsAlive = id;
if (g.ActiveIdPreviousFrame == id)
g.ActiveIdPreviousFrameIsAlive = true;
}
void ImGui::MarkItemEdited(ImGuiID id)
{
// This marking is solely to be able to provide info for IsItemDeactivatedAfterEdit().
// ActiveId might have been released by the time we call this (as in the typical press/release button behavior) but still need need to fill the data.
ImGuiContext& g = *GImGui;
IM_ASSERT(g.ActiveId == id || g.ActiveId == 0 || g.DragDropActive);
IM_UNUSED(id); // Avoid unused variable warnings when asserts are compiled out.
//IM_ASSERT(g.CurrentWindow->DC.LastItemId == id);
g.ActiveIdHasBeenEditedThisFrame = true;
g.ActiveIdHasBeenEditedBefore = true;
g.CurrentWindow->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_Edited;
}
static inline bool IsWindowContentHoverable(ImGuiWindow* window, ImGuiHoveredFlags flags)
{
// An active popup disable hovering on other windows (apart from its own children)
// FIXME-OPT: This could be cached/stored within the window.
ImGuiContext& g = *GImGui;
if (g.NavWindow)
if (ImGuiWindow* focused_root_window = g.NavWindow->RootWindow)
if (focused_root_window->WasActive && focused_root_window != window->RootWindow)
{
// For the purpose of those flags we differentiate "standard popup" from "modal popup"
// NB: The order of those two tests is important because Modal windows are also Popups.
if (focused_root_window->Flags & ImGuiWindowFlags_Modal)
return false;
if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiHoveredFlags_AllowWhenBlockedByPopup))
return false;
}
return true;
}
// Advance cursor given item size for layout.
void ImGui::ItemSize(const ImVec2& size, float text_baseline_y)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (window->SkipItems)
return;
// We increase the height in this function to accommodate for baseline offset.
// In theory we should be offsetting the starting position (window->DC.CursorPos), that will be the topic of a larger refactor,
// but since ItemSize() is not yet an API that moves the cursor (to handle e.g. wrapping) enlarging the height has the same effect.
const float offset_to_match_baseline_y = (text_baseline_y >= 0) ? ImMax(0.0f, window->DC.CurrLineTextBaseOffset - text_baseline_y) : 0.0f;
const float line_height = ImMax(window->DC.CurrLineSize.y, size.y + offset_to_match_baseline_y);
// Always align ourselves on pixel boundaries
//if (g.IO.KeyAlt) window->DrawList->AddRect(window->DC.CursorPos, window->DC.CursorPos + ImVec2(size.x, line_height), IM_COL32(255,0,0,200)); // [DEBUG]
window->DC.CursorPosPrevLine.x = window->DC.CursorPos.x + size.x;
window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y;
window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); // Next line
window->DC.CursorPos.y = IM_FLOOR(window->DC.CursorPos.y + line_height + g.Style.ItemSpacing.y); // Next line
window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPosPrevLine.x);
window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y - g.Style.ItemSpacing.y);
//if (g.IO.KeyAlt) window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, IM_COL32(255,0,0,255), 4); // [DEBUG]
window->DC.PrevLineSize.y = line_height;
window->DC.CurrLineSize.y = 0.0f;
window->DC.PrevLineTextBaseOffset = ImMax(window->DC.CurrLineTextBaseOffset, text_baseline_y);
window->DC.CurrLineTextBaseOffset = 0.0f;
// Horizontal layout mode
if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
SameLine();
}
void ImGui::ItemSize(const ImRect& bb, float text_baseline_y)
{
ItemSize(bb.GetSize(), text_baseline_y);
}
// Declare item bounding box for clipping and interaction.
// Note that the size can be different than the one provided to ItemSize(). Typically, widgets that spread over available surface
// declare their minimum size requirement to ItemSize() and then use a larger region for drawing/interaction, which is passed to ItemAdd().
bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (id != 0)
{
// Navigation processing runs prior to clipping early-out
// (a) So that NavInitRequest can be honored, for newly opened windows to select a default widget
// (b) So that we can scroll up/down past clipped items. This adds a small O(N) cost to regular navigation requests
// unfortunately, but it is still limited to one window. It may not scale very well for windows with ten of
// thousands of item, but at least NavMoveRequest is only set on user interaction, aka maximum once a frame.
// We could early out with "if (is_clipped && !g.NavInitRequest) return false;" but when we wouldn't be able
// to reach unclipped widgets. This would work if user had explicit scrolling control (e.g. mapped on a stick).
// We intentionally don't check if g.NavWindow != NULL because g.NavAnyRequest should only be set when it is non null.
// If we crash on a NULL g.NavWindow we need to fix the bug elsewhere.
window->DC.NavLayerActiveMaskNext |= window->DC.NavLayerCurrentMask;
if (g.NavId == id || g.NavAnyRequest)
if (g.NavWindow->RootWindowForNav == window->RootWindowForNav)
if (window == g.NavWindow || ((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened))
NavProcessItem(window, nav_bb_arg ? *nav_bb_arg : bb, id);
// [DEBUG] Item Picker tool, when enabling the "extended" version we perform the check in ItemAdd()
#ifdef IMGUI_DEBUG_TOOL_ITEM_PICKER_EX
if (id == g.DebugItemPickerBreakId)
{
IM_DEBUG_BREAK();
g.DebugItemPickerBreakId = 0;
}
#endif
}
window->DC.LastItemId = id;
window->DC.LastItemRect = bb;
window->DC.LastItemStatusFlags = ImGuiItemStatusFlags_None;
g.NextItemData.Flags = ImGuiNextItemDataFlags_None;
#ifdef IMGUI_ENABLE_TEST_ENGINE
if (id != 0)
IMGUI_TEST_ENGINE_ITEM_ADD(nav_bb_arg ? *nav_bb_arg : bb, id);
#endif
// Clipping test
const bool is_clipped = IsClippedEx(bb, id, false);
if (is_clipped)
return false;
//if (g.IO.KeyAlt) window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255,255,0,120)); // [DEBUG]
// We need to calculate this now to take account of the current clipping rectangle (as items like Selectable may change them)
if (IsMouseHoveringRect(bb.Min, bb.Max))
window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_HoveredRect;
return true;
}
// This is roughly matching the behavior of internal-facing ItemHoverable()
// - we allow hovering to be true when ActiveId==window->MoveID, so that clicking on non-interactive items such as a Text() item still returns true with IsItemHovered()
// - this should work even for non-interactive items that have no ID, so we cannot use LastItemId
bool ImGui::IsItemHovered(ImGuiHoveredFlags flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (g.NavDisableMouseHover && !g.NavDisableHighlight)
return IsItemFocused();
// Test for bounding box overlap, as updated as ItemAdd()
if (!(window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect))
return false;
IM_ASSERT((flags & (ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows)) == 0); // Flags not supported by this function
// Test if we are hovering the right window (our window could be behind another window)
// [2017/10/16] Reverted commit 344d48be3 and testing RootWindow instead. I believe it is correct to NOT test for RootWindow but this leaves us unable to use IsItemHovered() after EndChild() itself.
// Until a solution is found I believe reverting to the test from 2017/09/27 is safe since this was the test that has been running for a long while.
//if (g.HoveredWindow != window)
// return false;
if (g.HoveredRootWindow != window->RootWindow && !(flags & ImGuiHoveredFlags_AllowWhenOverlapped))
return false;
// Test if another item is active (e.g. being dragged)
if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
if (g.ActiveId != 0 && g.ActiveId != window->DC.LastItemId && !g.ActiveIdAllowOverlap && g.ActiveId != window->MoveId)
return false;
// Test if interactions on this window are blocked by an active popup or modal.
// The ImGuiHoveredFlags_AllowWhenBlockedByPopup flag will be tested here.
if (!IsWindowContentHoverable(window, flags))
return false;
// Test if the item is disabled
if ((window->DC.ItemFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
return false;
// Special handling for the dummy item after Begin() which represent the title bar or tab.
// When the window is collapsed (SkipItems==true) that last item will never be overwritten so we need to detect the case.
if (window->DC.LastItemId == window->MoveId && window->WriteAccessed)
return false;
return true;
}
// Internal facing ItemHoverable() used when submitting widgets. Differs slightly from IsItemHovered().
bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id)
{
ImGuiContext& g = *GImGui;
if (g.HoveredId != 0 && g.HoveredId != id && !g.HoveredIdAllowOverlap)
return false;
ImGuiWindow* window = g.CurrentWindow;
if (g.HoveredWindow != window)
return false;
if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
return false;
if (!IsMouseHoveringRect(bb.Min, bb.Max))
return false;
if (g.NavDisableMouseHover || !IsWindowContentHoverable(window, ImGuiHoveredFlags_None))
return false;
if (window->DC.ItemFlags & ImGuiItemFlags_Disabled)
return false;
SetHoveredID(id);
// [DEBUG] Item Picker tool!
// We perform the check here because SetHoveredID() is not frequently called (1~ time a frame), making
// the cost of this tool near-zero. We can get slightly better call-stack and support picking non-hovered
// items if we perform the test in ItemAdd(), but that would incur a small runtime cost.
// #define IMGUI_DEBUG_TOOL_ITEM_PICKER_EX in imconfig.h if you want this check to also be performed in ItemAdd().
if (g.DebugItemPickerActive && g.HoveredIdPreviousFrame == id)
GetForegroundDrawList()->AddRect(bb.Min, bb.Max, IM_COL32(255, 255, 0, 255));
if (g.DebugItemPickerBreakId == id)
IM_DEBUG_BREAK();
return true;
}
bool ImGui::IsClippedEx(const ImRect& bb, ImGuiID id, bool clip_even_when_logged)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (!bb.Overlaps(window->ClipRect))
if (id == 0 || id != g.ActiveId)
if (clip_even_when_logged || !g.LogEnabled)
return true;
return false;
}
// Process TAB/Shift+TAB. Be mindful that this function may _clear_ the ActiveID when tabbing out.
bool ImGui::FocusableItemRegister(ImGuiWindow* window, ImGuiID id)
{
ImGuiContext& g = *GImGui;
// Increment counters
const bool is_tab_stop = (window->DC.ItemFlags & (ImGuiItemFlags_NoTabStop | ImGuiItemFlags_Disabled)) == 0;
window->DC.FocusCounterRegular++;
if (is_tab_stop)
window->DC.FocusCounterTabStop++;
// Process TAB/Shift-TAB to tab *OUT* of the currently focused item.
// (Note that we can always TAB out of a widget that doesn't allow tabbing in)
if (g.ActiveId == id && g.FocusTabPressed && !IsActiveIdUsingKey(ImGuiKey_Tab) && g.FocusRequestNextWindow == NULL)
{
g.FocusRequestNextWindow = window;
g.FocusRequestNextCounterTabStop = window->DC.FocusCounterTabStop + (g.IO.KeyShift ? (is_tab_stop ? -1 : 0) : +1); // Modulo on index will be applied at the end of frame once we've got the total counter of items.
}
// Handle focus requests
if (g.FocusRequestCurrWindow == window)
{
if (window->DC.FocusCounterRegular == g.FocusRequestCurrCounterRegular)
return true;
if (is_tab_stop && window->DC.FocusCounterTabStop == g.FocusRequestCurrCounterTabStop)
{
g.NavJustTabbedId = id;
return true;
}
// If another item is about to be focused, we clear our own active id
if (g.ActiveId == id)
ClearActiveID();
}
return false;
}
void ImGui::FocusableItemUnregister(ImGuiWindow* window)
{
window->DC.FocusCounterRegular--;
window->DC.FocusCounterTabStop--;
}
float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x)
{
if (wrap_pos_x < 0.0f)
return 0.0f;
ImGuiWindow* window = GImGui->CurrentWindow;
if (wrap_pos_x == 0.0f)
wrap_pos_x = window->WorkRect.Max.x;
else if (wrap_pos_x > 0.0f)
wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space
return ImMax(wrap_pos_x - pos.x, 1.0f);
}
// IM_ALLOC() == ImGui::MemAlloc()
void* ImGui::MemAlloc(size_t size)
{
if (ImGuiContext* ctx = GImGui)
ctx->IO.MetricsActiveAllocations++;
return GImAllocatorAllocFunc(size, GImAllocatorUserData);
}
// IM_FREE() == ImGui::MemFree()
void ImGui::MemFree(void* ptr)
{
if (ptr)
if (ImGuiContext* ctx = GImGui)
ctx->IO.MetricsActiveAllocations--;
return GImAllocatorFreeFunc(ptr, GImAllocatorUserData);
}
const char* ImGui::GetClipboardText()
{
ImGuiContext& g = *GImGui;
return g.IO.GetClipboardTextFn ? g.IO.GetClipboardTextFn(g.IO.ClipboardUserData) : "";
}
void ImGui::SetClipboardText(const char* text)
{
ImGuiContext& g = *GImGui;
if (g.IO.SetClipboardTextFn)
g.IO.SetClipboardTextFn(g.IO.ClipboardUserData, text);
}
const char* ImGui::GetVersion()
{
return IMGUI_VERSION;
}
// Internal state access - if you want to share Dear ImGui state between modules (e.g. DLL) or allocate it yourself
// Note that we still point to some static data and members (such as GFontAtlas), so the state instance you end up using will point to the static data within its module
ImGuiContext* ImGui::GetCurrentContext()
{
return GImGui;
}
void ImGui::SetCurrentContext(ImGuiContext* ctx)
{
#ifdef IMGUI_SET_CURRENT_CONTEXT_FUNC
IMGUI_SET_CURRENT_CONTEXT_FUNC(ctx); // For custom thread-based hackery you may want to have control over this.
#else
GImGui = ctx;
#endif
}
// Helper function to verify ABI compatibility between caller code and compiled version of Dear ImGui.
// Verify that the type sizes are matching between the calling file's compilation unit and imgui.cpp's compilation unit
// If the user has inconsistent compilation settings, imgui configuration #define, packing pragma, etc. your user code
// may see different structures than what imgui.cpp sees, which is problematic.
// We usually require settings to be in imconfig.h to make sure that they are accessible to all compilation units involved with Dear ImGui.
bool ImGui::DebugCheckVersionAndDataLayout(const char* version, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_vert, size_t sz_idx)
{
bool error = false;
if (strcmp(version, IMGUI_VERSION)!=0) { error = true; IM_ASSERT(strcmp(version,IMGUI_VERSION)==0 && "Mismatched version string!"); }
if (sz_io != sizeof(ImGuiIO)) { error = true; IM_ASSERT(sz_io == sizeof(ImGuiIO) && "Mismatched struct layout!"); }
if (sz_style != sizeof(ImGuiStyle)) { error = true; IM_ASSERT(sz_style == sizeof(ImGuiStyle) && "Mismatched struct layout!"); }
if (sz_vec2 != sizeof(ImVec2)) { error = true; IM_ASSERT(sz_vec2 == sizeof(ImVec2) && "Mismatched struct layout!"); }
if (sz_vec4 != sizeof(ImVec4)) { error = true; IM_ASSERT(sz_vec4 == sizeof(ImVec4) && "Mismatched struct layout!"); }
if (sz_vert != sizeof(ImDrawVert)) { error = true; IM_ASSERT(sz_vert == sizeof(ImDrawVert) && "Mismatched struct layout!"); }
if (sz_idx != sizeof(ImDrawIdx)) { error = true; IM_ASSERT(sz_idx == sizeof(ImDrawIdx) && "Mismatched struct layout!"); }
return !error;
}
void ImGui::SetAllocatorFunctions(void* (*alloc_func)(size_t sz, void* user_data), void (*free_func)(void* ptr, void* user_data), void* user_data)
{
GImAllocatorAllocFunc = alloc_func;
GImAllocatorFreeFunc = free_func;
GImAllocatorUserData = user_data;
}
ImGuiContext* ImGui::CreateContext(ImFontAtlas* shared_font_atlas)
{
ImGuiContext* ctx = IM_NEW(ImGuiContext)(shared_font_atlas);
if (GImGui == NULL)
SetCurrentContext(ctx);
Initialize(ctx);
return ctx;
}
void ImGui::DestroyContext(ImGuiContext* ctx)
{
if (ctx == NULL)
ctx = GImGui;
Shutdown(ctx);
if (GImGui == ctx)
SetCurrentContext(NULL);
IM_DELETE(ctx);
}
ImGuiIO& ImGui::GetIO()
{
IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
return GImGui->IO;
}
ImGuiStyle& ImGui::GetStyle()
{
IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
return GImGui->Style;
}
// Same value as passed to the old io.RenderDrawListsFn function. Valid after Render() and until the next call to NewFrame()
ImDrawData* ImGui::GetDrawData()
{
ImGuiContext& g = *GImGui;
return g.DrawData.Valid ? &g.DrawData : NULL;
}
double ImGui::GetTime()
{
return GImGui->Time;
}
int ImGui::GetFrameCount()
{
return GImGui->FrameCount;
}
ImDrawList* ImGui::GetBackgroundDrawList()
{
return &GImGui->BackgroundDrawList;
}
ImDrawList* ImGui::GetForegroundDrawList()
{
return &GImGui->ForegroundDrawList;
}
ImDrawListSharedData* ImGui::GetDrawListSharedData()
{
return &GImGui->DrawListSharedData;
}
void ImGui::StartMouseMovingWindow(ImGuiWindow* window)
{
// Set ActiveId even if the _NoMove flag is set. Without it, dragging away from a window with _NoMove would activate hover on other windows.
// We _also_ call this when clicking in a window empty space when io.ConfigWindowsMoveFromTitleBarOnly is set, but clear g.MovingWindow afterward.
// This is because we want ActiveId to be set even when the window is not permitted to move.
ImGuiContext& g = *GImGui;
FocusWindow(window);
SetActiveID(window->MoveId, window);
g.NavDisableHighlight = true;
g.ActiveIdClickOffset = g.IO.MousePos - window->RootWindow->Pos;
bool can_move_window = true;
if ((window->Flags & ImGuiWindowFlags_NoMove) || (window->RootWindow->Flags & ImGuiWindowFlags_NoMove))
can_move_window = false;
if (can_move_window)
g.MovingWindow = window;
}
// Handle mouse moving window
// Note: moving window with the navigation keys (Square + d-pad / CTRL+TAB + Arrows) are processed in NavUpdateWindowing()
void ImGui::UpdateMouseMovingWindowNewFrame()
{
ImGuiContext& g = *GImGui;
if (g.MovingWindow != NULL)
{
// We actually want to move the root window. g.MovingWindow == window we clicked on (could be a child window).
// We track it to preserve Focus and so that generally ActiveIdWindow == MovingWindow and ActiveId == MovingWindow->MoveId for consistency.
KeepAliveID(g.ActiveId);
IM_ASSERT(g.MovingWindow && g.MovingWindow->RootWindow);
ImGuiWindow* moving_window = g.MovingWindow->RootWindow;
if (g.IO.MouseDown[0] && IsMousePosValid(&g.IO.MousePos))
{
ImVec2 pos = g.IO.MousePos - g.ActiveIdClickOffset;
if (moving_window->Pos.x != pos.x || moving_window->Pos.y != pos.y)
{
MarkIniSettingsDirty(moving_window);
SetWindowPos(moving_window, pos, ImGuiCond_Always);
}
FocusWindow(g.MovingWindow);
}
else
{
ClearActiveID();
g.MovingWindow = NULL;
}
}
else
{
// When clicking/dragging from a window that has the _NoMove flag, we still set the ActiveId in order to prevent hovering others.
if (g.ActiveIdWindow && g.ActiveIdWindow->MoveId == g.ActiveId)
{
KeepAliveID(g.ActiveId);
if (!g.IO.MouseDown[0])
ClearActiveID();
}
}
}
// Initiate moving window when clicking on empty space or title bar.
// Handle left-click and right-click focus.
void ImGui::UpdateMouseMovingWindowEndFrame()
{
ImGuiContext& g = *GImGui;
if (g.ActiveId != 0 || g.HoveredId != 0)
return;
// Unless we just made a window/popup appear
if (g.NavWindow && g.NavWindow->Appearing)
return;
// Click to focus window and start moving (after we're done with all our widgets)
if (g.IO.MouseClicked[0])
{
if (g.HoveredRootWindow != NULL)
{
StartMouseMovingWindow(g.HoveredWindow);
if (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(g.HoveredRootWindow->Flags & ImGuiWindowFlags_NoTitleBar))
if (!g.HoveredRootWindow->TitleBarRect().Contains(g.IO.MouseClickedPos[0]))
g.MovingWindow = NULL;
}
else if (g.NavWindow != NULL && GetTopMostPopupModal() == NULL)
{
// Clicking on void disable focus
FocusWindow(NULL);
}
}
// With right mouse button we close popups without changing focus based on where the mouse is aimed
// Instead, focus will be restored to the window under the bottom-most closed popup.
// (The left mouse button path calls FocusWindow on the hovered window, which will lead NewFrame->ClosePopupsOverWindow to trigger)
if (g.IO.MouseClicked[1])
{
// Find the top-most window between HoveredWindow and the top-most Modal Window.
// This is where we can trim the popup stack.
ImGuiWindow* modal = GetTopMostPopupModal();
bool hovered_window_above_modal = false;
if (modal == NULL)
hovered_window_above_modal = true;
for (int i = g.Windows.Size - 1; i >= 0 && hovered_window_above_modal == false; i--)
{
ImGuiWindow* window = g.Windows[i];
if (window == modal)
break;
if (window == g.HoveredWindow)
hovered_window_above_modal = true;
}
ClosePopupsOverWindow(hovered_window_above_modal ? g.HoveredWindow : modal, true);
}
}
static bool IsWindowActiveAndVisible(ImGuiWindow* window)
{
return (window->Active) && (!window->Hidden);
}
static void ImGui::UpdateMouseInputs()
{
ImGuiContext& g = *GImGui;
// Round mouse position to avoid spreading non-rounded position (e.g. UpdateManualResize doesn't support them well)
if (IsMousePosValid(&g.IO.MousePos))
g.IO.MousePos = g.LastValidMousePos = ImFloor(g.IO.MousePos);
// If mouse just appeared or disappeared (usually denoted by -FLT_MAX components) we cancel out movement in MouseDelta
if (IsMousePosValid(&g.IO.MousePos) && IsMousePosValid(&g.IO.MousePosPrev))
g.IO.MouseDelta = g.IO.MousePos - g.IO.MousePosPrev;
else
g.IO.MouseDelta = ImVec2(0.0f, 0.0f);
if (g.IO.MouseDelta.x != 0.0f || g.IO.MouseDelta.y != 0.0f)
g.NavDisableMouseHover = false;
g.IO.MousePosPrev = g.IO.MousePos;
for (int i = 0; i < IM_ARRAYSIZE(g.IO.MouseDown); i++)
{
g.IO.MouseClicked[i] = g.IO.MouseDown[i] && g.IO.MouseDownDuration[i] < 0.0f;
g.IO.MouseReleased[i] = !g.IO.MouseDown[i] && g.IO.MouseDownDuration[i] >= 0.0f;
g.IO.MouseDownDurationPrev[i] = g.IO.MouseDownDuration[i];
g.IO.MouseDownDuration[i] = g.IO.MouseDown[i] ? (g.IO.MouseDownDuration[i] < 0.0f ? 0.0f : g.IO.MouseDownDuration[i] + g.IO.DeltaTime) : -1.0f;
g.IO.MouseDoubleClicked[i] = false;
if (g.IO.MouseClicked[i])
{
if ((float)(g.Time - g.IO.MouseClickedTime[i]) < g.IO.MouseDoubleClickTime)
{
ImVec2 delta_from_click_pos = IsMousePosValid(&g.IO.MousePos) ? (g.IO.MousePos - g.IO.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
if (ImLengthSqr(delta_from_click_pos) < g.IO.MouseDoubleClickMaxDist * g.IO.MouseDoubleClickMaxDist)
g.IO.MouseDoubleClicked[i] = true;
g.IO.MouseClickedTime[i] = -FLT_MAX; // so the third click isn't turned into a double-click
}
else
{
g.IO.MouseClickedTime[i] = g.Time;
}
g.IO.MouseClickedPos[i] = g.IO.MousePos;
g.IO.MouseDownWasDoubleClick[i] = g.IO.MouseDoubleClicked[i];
g.IO.MouseDragMaxDistanceAbs[i] = ImVec2(0.0f, 0.0f);
g.IO.MouseDragMaxDistanceSqr[i] = 0.0f;
}
else if (g.IO.MouseDown[i])
{
// Maintain the maximum distance we reaching from the initial click position, which is used with dragging threshold
ImVec2 delta_from_click_pos = IsMousePosValid(&g.IO.MousePos) ? (g.IO.MousePos - g.IO.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
g.IO.MouseDragMaxDistanceSqr[i] = ImMax(g.IO.MouseDragMaxDistanceSqr[i], ImLengthSqr(delta_from_click_pos));
g.IO.MouseDragMaxDistanceAbs[i].x = ImMax(g.IO.MouseDragMaxDistanceAbs[i].x, delta_from_click_pos.x < 0.0f ? -delta_from_click_pos.x : delta_from_click_pos.x);
g.IO.MouseDragMaxDistanceAbs[i].y = ImMax(g.IO.MouseDragMaxDistanceAbs[i].y, delta_from_click_pos.y < 0.0f ? -delta_from_click_pos.y : delta_from_click_pos.y);
}
if (!g.IO.MouseDown[i] && !g.IO.MouseReleased[i])
g.IO.MouseDownWasDoubleClick[i] = false;
if (g.IO.MouseClicked[i]) // Clicking any mouse button reactivate mouse hovering which may have been deactivated by gamepad/keyboard navigation
g.NavDisableMouseHover = false;
}
}
static void StartLockWheelingWindow(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
if (g.WheelingWindow == window)
return;
g.WheelingWindow = window;
g.WheelingWindowRefMousePos = g.IO.MousePos;
g.WheelingWindowTimer = WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER;
}
void ImGui::UpdateMouseWheel()
{
ImGuiContext& g = *GImGui;
// Reset the locked window if we move the mouse or after the timer elapses
if (g.WheelingWindow != NULL)
{
g.WheelingWindowTimer -= g.IO.DeltaTime;
if (IsMousePosValid() && ImLengthSqr(g.IO.MousePos - g.WheelingWindowRefMousePos) > g.IO.MouseDragThreshold * g.IO.MouseDragThreshold)
g.WheelingWindowTimer = 0.0f;
if (g.WheelingWindowTimer <= 0.0f)
{
g.WheelingWindow = NULL;
g.WheelingWindowTimer = 0.0f;
}
}
if (g.IO.MouseWheel == 0.0f && g.IO.MouseWheelH == 0.0f)
return;
ImGuiWindow* window = g.WheelingWindow ? g.WheelingWindow : g.HoveredWindow;
if (!window || window->Collapsed)
return;
// Zoom / Scale window
// FIXME-OBSOLETE: This is an old feature, it still works but pretty much nobody is using it and may be best redesigned.
if (g.IO.MouseWheel != 0.0f && g.IO.KeyCtrl && g.IO.FontAllowUserScaling)
{
StartLockWheelingWindow(window);
const float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f);
const float scale = new_font_scale / window->FontWindowScale;
window->FontWindowScale = new_font_scale;
if (!(window->Flags & ImGuiWindowFlags_ChildWindow))
{
const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size;
SetWindowPos(window, window->Pos + offset, 0);
window->Size = ImFloor(window->Size * scale);
window->SizeFull = ImFloor(window->SizeFull * scale);
}
return;
}
// Mouse wheel scrolling
// If a child window has the ImGuiWindowFlags_NoScrollWithMouse flag, we give a chance to scroll its parent
// Vertical Mouse Wheel scrolling
const float wheel_y = (g.IO.MouseWheel != 0.0f && !g.IO.KeyShift) ? g.IO.MouseWheel : 0.0f;
if (wheel_y != 0.0f && !g.IO.KeyCtrl)
{
StartLockWheelingWindow(window);
while ((window->Flags & ImGuiWindowFlags_ChildWindow) && ((window->ScrollMax.y == 0.0f) || ((window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))))
window = window->ParentWindow;
if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))
{
float max_step = window->InnerRect.GetHeight() * 0.67f;
float scroll_step = ImFloor(ImMin(5 * window->CalcFontSize(), max_step));
SetScrollY(window, window->Scroll.y - wheel_y * scroll_step);
}
}
// Horizontal Mouse Wheel scrolling, or Vertical Mouse Wheel w/ Shift held
const float wheel_x = (g.IO.MouseWheelH != 0.0f && !g.IO.KeyShift) ? g.IO.MouseWheelH : (g.IO.MouseWheel != 0.0f && g.IO.KeyShift) ? g.IO.MouseWheel : 0.0f;
if (wheel_x != 0.0f && !g.IO.KeyCtrl)
{
StartLockWheelingWindow(window);
while ((window->Flags & ImGuiWindowFlags_ChildWindow) && ((window->ScrollMax.x == 0.0f) || ((window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))))
window = window->ParentWindow;
if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))
{
float max_step = window->InnerRect.GetWidth() * 0.67f;
float scroll_step = ImFloor(ImMin(2 * window->CalcFontSize(), max_step));
SetScrollX(window, window->Scroll.x - wheel_x * scroll_step);
}
}
}
// The reason this is exposed in imgui_internal.h is: on touch-based system that don't have hovering, we want to dispatch inputs to the right target (imgui vs imgui+app)
void ImGui::UpdateHoveredWindowAndCaptureFlags()
{
ImGuiContext& g = *GImGui;
// Find the window hovered by mouse:
// - Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow.
// - When moving a window we can skip the search, which also conveniently bypasses the fact that window->WindowRectClipped is lagging as this point of the frame.
// - We also support the moved window toggling the NoInputs flag after moving has started in order to be able to detect windows below it, which is useful for e.g. docking mechanisms.
FindHoveredWindow();
// Modal windows prevents cursor from hovering behind them.
ImGuiWindow* modal_window = GetTopMostPopupModal();
if (modal_window)
if (g.HoveredRootWindow && !IsWindowChildOf(g.HoveredRootWindow, modal_window))
g.HoveredRootWindow = g.HoveredWindow = NULL;
// Disabled mouse?
if (g.IO.ConfigFlags & ImGuiConfigFlags_NoMouse)
g.HoveredWindow = g.HoveredRootWindow = NULL;
// We track click ownership. When clicked outside of a window the click is owned by the application and won't report hovering nor request capture even while dragging over our windows afterward.
int mouse_earliest_button_down = -1;
bool mouse_any_down = false;
for (int i = 0; i < IM_ARRAYSIZE(g.IO.MouseDown); i++)
{
if (g.IO.MouseClicked[i])
g.IO.MouseDownOwned[i] = (g.HoveredWindow != NULL) || (!g.OpenPopupStack.empty());
mouse_any_down |= g.IO.MouseDown[i];
if (g.IO.MouseDown[i])
if (mouse_earliest_button_down == -1 || g.IO.MouseClickedTime[i] < g.IO.MouseClickedTime[mouse_earliest_button_down])
mouse_earliest_button_down = i;
}
const bool mouse_avail_to_imgui = (mouse_earliest_button_down == -1) || g.IO.MouseDownOwned[mouse_earliest_button_down];
// If mouse was first clicked outside of ImGui bounds we also cancel out hovering.
// FIXME: For patterns of drag and drop across OS windows, we may need to rework/remove this test (first committed 311c0ca9 on 2015/02)
const bool mouse_dragging_extern_payload = g.DragDropActive && (g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) != 0;
if (!mouse_avail_to_imgui && !mouse_dragging_extern_payload)
g.HoveredWindow = g.HoveredRootWindow = NULL;
// Update io.WantCaptureMouse for the user application (true = dispatch mouse info to imgui, false = dispatch mouse info to Dear ImGui + app)
if (g.WantCaptureMouseNextFrame != -1)
g.IO.WantCaptureMouse = (g.WantCaptureMouseNextFrame != 0);
else
g.IO.WantCaptureMouse = (mouse_avail_to_imgui && (g.HoveredWindow != NULL || mouse_any_down)) || (!g.OpenPopupStack.empty());
// Update io.WantCaptureKeyboard for the user application (true = dispatch keyboard info to imgui, false = dispatch keyboard info to Dear ImGui + app)
if (g.WantCaptureKeyboardNextFrame != -1)
g.IO.WantCaptureKeyboard = (g.WantCaptureKeyboardNextFrame != 0);
else
g.IO.WantCaptureKeyboard = (g.ActiveId != 0) || (modal_window != NULL);
if (g.IO.NavActive && (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && !(g.IO.ConfigFlags & ImGuiConfigFlags_NavNoCaptureKeyboard))
g.IO.WantCaptureKeyboard = true;
// Update io.WantTextInput flag, this is to allow systems without a keyboard (e.g. mobile, hand-held) to show a software keyboard if possible
g.IO.WantTextInput = (g.WantTextInputNextFrame != -1) ? (g.WantTextInputNextFrame != 0) : false;
}
static void NewFrameSanityChecks()
{
ImGuiContext& g = *GImGui;
// Check user data
// (We pass an error message in the assert expression to make it visible to programmers who are not using a debugger, as most assert handlers display their argument)
IM_ASSERT(g.Initialized);
IM_ASSERT((g.IO.DeltaTime > 0.0f || g.FrameCount == 0) && "Need a positive DeltaTime!");
IM_ASSERT((g.FrameCount == 0 || g.FrameCountEnded == g.FrameCount) && "Forgot to call Render() or EndFrame() at the end of the previous frame?");
IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f && "Invalid DisplaySize value!");
IM_ASSERT(g.IO.Fonts->Fonts.Size > 0 && "Font Atlas not built. Did you call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8() ?");
IM_ASSERT(g.IO.Fonts->Fonts[0]->IsLoaded() && "Font Atlas not built. Did you call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8() ?");
IM_ASSERT(g.Style.CurveTessellationTol > 0.0f && "Invalid style setting!");
IM_ASSERT(g.Style.CircleSegmentMaxError > 0.0f && "Invalid style setting!");
IM_ASSERT(g.Style.Alpha >= 0.0f && g.Style.Alpha <= 1.0f && "Invalid style setting. Alpha cannot be negative (allows us to avoid a few clamps in color computations)!");
IM_ASSERT(g.Style.WindowMinSize.x >= 1.0f && g.Style.WindowMinSize.y >= 1.0f && "Invalid style setting.");
IM_ASSERT(g.Style.WindowMenuButtonPosition == ImGuiDir_None || g.Style.WindowMenuButtonPosition == ImGuiDir_Left || g.Style.WindowMenuButtonPosition == ImGuiDir_Right);
for (int n = 0; n < ImGuiKey_COUNT; n++)
IM_ASSERT(g.IO.KeyMap[n] >= -1 && g.IO.KeyMap[n] < IM_ARRAYSIZE(g.IO.KeysDown) && "io.KeyMap[] contains an out of bound value (need to be 0..512, or -1 for unmapped key)");
// Perform simple check: required key mapping (we intentionally do NOT check all keys to not pressure user into setting up everything, but Space is required and was only recently added in 1.60 WIP)
if (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard)
IM_ASSERT(g.IO.KeyMap[ImGuiKey_Space] != -1 && "ImGuiKey_Space is not mapped, required for keyboard navigation.");
// Perform simple check: the beta io.ConfigWindowsResizeFromEdges option requires back-end to honor mouse cursor changes and set the ImGuiBackendFlags_HasMouseCursors flag accordingly.
if (g.IO.ConfigWindowsResizeFromEdges && !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseCursors))
g.IO.ConfigWindowsResizeFromEdges = false;
}
void ImGui::NewFrame()
{
IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
ImGuiContext& g = *GImGui;
#ifdef IMGUI_ENABLE_TEST_ENGINE
ImGuiTestEngineHook_PreNewFrame(&g);
#endif
// Check and assert for various common IO and Configuration mistakes
NewFrameSanityChecks();
// Load settings on first frame (if not explicitly loaded manually before)
if (!g.SettingsLoaded)
{
IM_ASSERT(g.SettingsWindows.empty());
if (g.IO.IniFilename)
LoadIniSettingsFromDisk(g.IO.IniFilename);
g.SettingsLoaded = true;
}
// Save settings (with a delay after the last modification, so we don't spam disk too much)
if (g.SettingsDirtyTimer > 0.0f)
{
g.SettingsDirtyTimer -= g.IO.DeltaTime;
if (g.SettingsDirtyTimer <= 0.0f)
{
if (g.IO.IniFilename != NULL)
SaveIniSettingsToDisk(g.IO.IniFilename);
else
g.IO.WantSaveIniSettings = true; // Let user know they can call SaveIniSettingsToMemory(). user will need to clear io.WantSaveIniSettings themselves.
g.SettingsDirtyTimer = 0.0f;
}
}
g.Time += g.IO.DeltaTime;
g.WithinFrameScope = true;
g.FrameCount += 1;
g.TooltipOverrideCount = 0;
g.WindowsActiveCount = 0;
// Setup current font and draw list shared data
g.IO.Fonts->Locked = true;
SetCurrentFont(GetDefaultFont());
IM_ASSERT(g.Font->IsLoaded());
g.DrawListSharedData.ClipRectFullscreen = ImVec4(0.0f, 0.0f, g.IO.DisplaySize.x, g.IO.DisplaySize.y);
g.DrawListSharedData.CurveTessellationTol = g.Style.CurveTessellationTol;
g.DrawListSharedData.SetCircleSegmentMaxError(g.Style.CircleSegmentMaxError);
g.DrawListSharedData.InitialFlags = ImDrawListFlags_None;
if (g.Style.AntiAliasedLines)
g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLines;
if (g.Style.AntiAliasedFill)
g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedFill;
if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset)
g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AllowVtxOffset;
g.BackgroundDrawList.Clear();
g.BackgroundDrawList.PushTextureID(g.IO.Fonts->TexID);
g.BackgroundDrawList.PushClipRectFullScreen();
g.ForegroundDrawList.Clear();
g.ForegroundDrawList.PushTextureID(g.IO.Fonts->TexID);
g.ForegroundDrawList.PushClipRectFullScreen();
// Mark rendering data as invalid to prevent user who may have a handle on it to use it.
g.DrawData.Clear();
// Drag and drop keep the source ID alive so even if the source disappear our state is consistent
if (g.DragDropActive && g.DragDropPayload.SourceId == g.ActiveId)
KeepAliveID(g.DragDropPayload.SourceId);
// Clear reference to active widget if the widget isn't alive anymore
if (!g.HoveredIdPreviousFrame)
g.HoveredIdTimer = 0.0f;
if (!g.HoveredIdPreviousFrame || (g.HoveredId && g.ActiveId == g.HoveredId))
g.HoveredIdNotActiveTimer = 0.0f;
if (g.HoveredId)
g.HoveredIdTimer += g.IO.DeltaTime;
if (g.HoveredId && g.ActiveId != g.HoveredId)
g.HoveredIdNotActiveTimer += g.IO.DeltaTime;
g.HoveredIdPreviousFrame = g.HoveredId;
g.HoveredId = 0;
g.HoveredIdAllowOverlap = false;
if (g.ActiveIdIsAlive != g.ActiveId && g.ActiveIdPreviousFrame == g.ActiveId && g.ActiveId != 0)
ClearActiveID();
if (g.ActiveId)
g.ActiveIdTimer += g.IO.DeltaTime;
g.LastActiveIdTimer += g.IO.DeltaTime;
g.ActiveIdPreviousFrame = g.ActiveId;
g.ActiveIdPreviousFrameWindow = g.ActiveIdWindow;
g.ActiveIdPreviousFrameHasBeenEditedBefore = g.ActiveIdHasBeenEditedBefore;
g.ActiveIdIsAlive = 0;
g.ActiveIdHasBeenEditedThisFrame = false;
g.ActiveIdPreviousFrameIsAlive = false;
g.ActiveIdIsJustActivated = false;
if (g.TempInputTextId != 0 && g.ActiveId != g.TempInputTextId)
g.TempInputTextId = 0;
if (g.ActiveId == 0)
{
g.ActiveIdUsingNavDirMask = g.ActiveIdUsingNavInputMask = 0;
g.ActiveIdUsingKeyInputMask = 0;
}
// Drag and drop
g.DragDropAcceptIdPrev = g.DragDropAcceptIdCurr;
g.DragDropAcceptIdCurr = 0;
g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
g.DragDropWithinSourceOrTarget = false;
// Update keyboard input state
memcpy(g.IO.KeysDownDurationPrev, g.IO.KeysDownDuration, sizeof(g.IO.KeysDownDuration));
for (int i = 0; i < IM_ARRAYSIZE(g.IO.KeysDown); i++)
g.IO.KeysDownDuration[i] = g.IO.KeysDown[i] ? (g.IO.KeysDownDuration[i] < 0.0f ? 0.0f : g.IO.KeysDownDuration[i] + g.IO.DeltaTime) : -1.0f;
// Update gamepad/keyboard directional navigation
NavUpdate();
// Update mouse input state
UpdateMouseInputs();
// Calculate frame-rate for the user, as a purely luxurious feature
g.FramerateSecPerFrameAccum += g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx];
g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime;
g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % IM_ARRAYSIZE(g.FramerateSecPerFrame);
g.IO.Framerate = (g.FramerateSecPerFrameAccum > 0.0f) ? (1.0f / (g.FramerateSecPerFrameAccum / (float)IM_ARRAYSIZE(g.FramerateSecPerFrame))) : FLT_MAX;
// Find hovered window
// (needs to be before UpdateMouseMovingWindowNewFrame so we fill g.HoveredWindowUnderMovingWindow on the mouse release frame)
UpdateHoveredWindowAndCaptureFlags();
// Handle user moving window with mouse (at the beginning of the frame to avoid input lag or sheering)
UpdateMouseMovingWindowNewFrame();
// Background darkening/whitening
if (GetTopMostPopupModal() != NULL || (g.NavWindowingTarget != NULL && g.NavWindowingHighlightAlpha > 0.0f))
g.DimBgRatio = ImMin(g.DimBgRatio + g.IO.DeltaTime * 6.0f, 1.0f);
else
g.DimBgRatio = ImMax(g.DimBgRatio - g.IO.DeltaTime * 10.0f, 0.0f);
g.MouseCursor = ImGuiMouseCursor_Arrow;
g.WantCaptureMouseNextFrame = g.WantCaptureKeyboardNextFrame = g.WantTextInputNextFrame = -1;
g.PlatformImePos = ImVec2(1.0f, 1.0f); // OS Input Method Editor showing on top-left of our window by default
// Mouse wheel scrolling, scale
UpdateMouseWheel();
// Pressing TAB activate widget focus
g.FocusTabPressed = (g.NavWindow && g.NavWindow->Active && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_Tab));
if (g.ActiveId == 0 && g.FocusTabPressed)
{
// Note that SetKeyboardFocusHere() sets the Next fields mid-frame. To be consistent we also
// manipulate the Next fields even, even though they will be turned into Curr fields by the code below.
g.FocusRequestNextWindow = g.NavWindow;
g.FocusRequestNextCounterRegular = INT_MAX;
if (g.NavId != 0 && g.NavIdTabCounter != INT_MAX)
g.FocusRequestNextCounterTabStop = g.NavIdTabCounter + 1 + (g.IO.KeyShift ? -1 : 1);
else
g.FocusRequestNextCounterTabStop = g.IO.KeyShift ? -1 : 0;
}
// Turn queued focus request into current one
g.FocusRequestCurrWindow = NULL;
g.FocusRequestCurrCounterRegular = g.FocusRequestCurrCounterTabStop = INT_MAX;
if (g.FocusRequestNextWindow != NULL)
{
ImGuiWindow* window = g.FocusRequestNextWindow;
g.FocusRequestCurrWindow = window;
if (g.FocusRequestNextCounterRegular != INT_MAX && window->DC.FocusCounterRegular != -1)
g.FocusRequestCurrCounterRegular = ImModPositive(g.FocusRequestNextCounterRegular, window->DC.FocusCounterRegular + 1);
if (g.FocusRequestNextCounterTabStop != INT_MAX && window->DC.FocusCounterTabStop != -1)
g.FocusRequestCurrCounterTabStop = ImModPositive(g.FocusRequestNextCounterTabStop, window->DC.FocusCounterTabStop + 1);
g.FocusRequestNextWindow = NULL;
g.FocusRequestNextCounterRegular = g.FocusRequestNextCounterTabStop = INT_MAX;
}
g.NavIdTabCounter = INT_MAX;
// Mark all windows as not visible and compact unused memory.
IM_ASSERT(g.WindowsFocusOrder.Size == g.Windows.Size);
const float memory_compact_start_time = (g.IO.ConfigWindowsMemoryCompactTimer >= 0.0f) ? (float)g.Time - g.IO.ConfigWindowsMemoryCompactTimer : FLT_MAX;
for (int i = 0; i != g.Windows.Size; i++)
{
ImGuiWindow* window = g.Windows[i];
window->WasActive = window->Active;
window->BeginCount = 0;
window->Active = false;
window->WriteAccessed = false;
// Garbage collect transient buffers of recently unused windows
if (!window->WasActive && !window->MemoryCompacted && window->LastTimeActive < memory_compact_start_time)
GcCompactTransientWindowBuffers(window);
}
// Closing the focused window restore focus to the first active root window in descending z-order
if (g.NavWindow && !g.NavWindow->WasActive)
FocusTopMostWindowUnderOne(NULL, NULL);
// No window should be open at the beginning of the frame.
// But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear.
g.CurrentWindowStack.resize(0);
g.BeginPopupStack.resize(0);
ClosePopupsOverWindow(g.NavWindow, false);
// [DEBUG] Item picker tool - start with DebugStartItemPicker() - useful to visually select an item and break into its call-stack.
UpdateDebugToolItemPicker();
// Create implicit/fallback window - which we will only render it if the user has added something to it.
// We don't use "Debug" to avoid colliding with user trying to create a "Debug" window with custom flags.
// This fallback is particularly important as it avoid ImGui:: calls from crashing.
g.WithinFrameScopeWithImplicitWindow = true;
SetNextWindowSize(ImVec2(400,400), ImGuiCond_FirstUseEver);
Begin("Debug##Default");
IM_ASSERT(g.CurrentWindow->IsFallbackWindow == true);
#ifdef IMGUI_ENABLE_TEST_ENGINE
ImGuiTestEngineHook_PostNewFrame(&g);
#endif
}
// [DEBUG] Item picker tool - start with DebugStartItemPicker() - useful to visually select an item and break into its call-stack.
void ImGui::UpdateDebugToolItemPicker()
{
ImGuiContext& g = *GImGui;
g.DebugItemPickerBreakId = 0;
if (g.DebugItemPickerActive)
{
const ImGuiID hovered_id = g.HoveredIdPreviousFrame;
ImGui::SetMouseCursor(ImGuiMouseCursor_Hand);
if (ImGui::IsKeyPressedMap(ImGuiKey_Escape))
g.DebugItemPickerActive = false;
if (ImGui::IsMouseClicked(0) && hovered_id)
{
g.DebugItemPickerBreakId = hovered_id;
g.DebugItemPickerActive = false;
}
ImGui::SetNextWindowBgAlpha(0.60f);
ImGui::BeginTooltip();
ImGui::Text("HoveredId: 0x%08X", hovered_id);
ImGui::Text("Press ESC to abort picking.");
ImGui::TextColored(GetStyleColorVec4(hovered_id ? ImGuiCol_Text : ImGuiCol_TextDisabled), "Click to break in debugger!");
ImGui::EndTooltip();
}
}
void ImGui::Initialize(ImGuiContext* context)
{
ImGuiContext& g = *context;
IM_ASSERT(!g.Initialized && !g.SettingsLoaded);
// Add .ini handle for ImGuiWindow type
{
ImGuiSettingsHandler ini_handler;
ini_handler.TypeName = "Window";
ini_handler.TypeHash = ImHashStr("Window");
ini_handler.ReadOpenFn = WindowSettingsHandler_ReadOpen;
ini_handler.ReadLineFn = WindowSettingsHandler_ReadLine;
ini_handler.WriteAllFn = WindowSettingsHandler_WriteAll;
g.SettingsHandlers.push_back(ini_handler);
}
#ifdef IMGUI_HAS_TABLE
// Add .ini handle for ImGuiTable type
{
ImGuiSettingsHandler ini_handler;
ini_handler.TypeName = "Table";
ini_handler.TypeHash = ImHashStr("Table");
ini_handler.ReadOpenFn = TableSettingsHandler_ReadOpen;
ini_handler.ReadLineFn = TableSettingsHandler_ReadLine;
ini_handler.WriteAllFn = TableSettingsHandler_WriteAll;
g.SettingsHandlers.push_back(ini_handler);
}
#endif // #ifdef IMGUI_HAS_TABLE
#ifdef IMGUI_HAS_DOCK
#endif // #ifdef IMGUI_HAS_DOCK
g.Initialized = true;
}
// This function is merely here to free heap allocations.
void ImGui::Shutdown(ImGuiContext* context)
{
// The fonts atlas can be used prior to calling NewFrame(), so we clear it even if g.Initialized is FALSE (which would happen if we never called NewFrame)
ImGuiContext& g = *context;
if (g.IO.Fonts && g.FontAtlasOwnedByContext)
{
g.IO.Fonts->Locked = false;
IM_DELETE(g.IO.Fonts);
}
g.IO.Fonts = NULL;
// Cleanup of other data are conditional on actually having initialized Dear ImGui.
if (!g.Initialized)
return;
// Save settings (unless we haven't attempted to load them: CreateContext/DestroyContext without a call to NewFrame shouldn't save an empty file)
if (g.SettingsLoaded && g.IO.IniFilename != NULL)
{
ImGuiContext* backup_context = GImGui;
SetCurrentContext(context);
SaveIniSettingsToDisk(g.IO.IniFilename);
SetCurrentContext(backup_context);
}
// Clear everything else
for (int i = 0; i < g.Windows.Size; i++)
IM_DELETE(g.Windows[i]);
g.Windows.clear();
g.WindowsFocusOrder.clear();
g.WindowsTempSortBuffer.clear();
g.CurrentWindow = NULL;
g.CurrentWindowStack.clear();
g.WindowsById.Clear();
g.NavWindow = NULL;
g.HoveredWindow = g.HoveredRootWindow = NULL;
g.ActiveIdWindow = g.ActiveIdPreviousFrameWindow = NULL;
g.MovingWindow = NULL;
g.ColorModifiers.clear();
g.StyleModifiers.clear();
g.FontStack.clear();
g.OpenPopupStack.clear();
g.BeginPopupStack.clear();
g.DrawDataBuilder.ClearFreeMemory();
g.BackgroundDrawList.ClearFreeMemory();
g.ForegroundDrawList.ClearFreeMemory();
g.TabBars.Clear();
g.CurrentTabBarStack.clear();
g.ShrinkWidthBuffer.clear();
g.PrivateClipboard.clear();
g.InputTextState.ClearFreeMemory();
g.SettingsWindows.clear();
g.SettingsHandlers.clear();
if (g.LogFile)
{
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
if (g.LogFile != stdout)
#endif
ImFileClose(g.LogFile);
g.LogFile = NULL;
}
g.LogBuffer.clear();
g.Initialized = false;
}
// FIXME: Add a more explicit sort order in the window structure.
static int IMGUI_CDECL ChildWindowComparer(const void* lhs, const void* rhs)
{
const ImGuiWindow* const a = *(const ImGuiWindow* const *)lhs;
const ImGuiWindow* const b = *(const ImGuiWindow* const *)rhs;
if (int d = (a->Flags & ImGuiWindowFlags_Popup) - (b->Flags & ImGuiWindowFlags_Popup))
return d;
if (int d = (a->Flags & ImGuiWindowFlags_Tooltip) - (b->Flags & ImGuiWindowFlags_Tooltip))
return d;
return (a->BeginOrderWithinParent - b->BeginOrderWithinParent);
}
static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window)
{
out_sorted_windows->push_back(window);
if (window->Active)
{
int count = window->DC.ChildWindows.Size;
if (count > 1)
ImQsort(window->DC.ChildWindows.Data, (size_t)count, sizeof(ImGuiWindow*), ChildWindowComparer);
for (int i = 0; i < count; i++)
{
ImGuiWindow* child = window->DC.ChildWindows[i];
if (child->Active)
AddWindowToSortBuffer(out_sorted_windows, child);
}
}
}
static void AddDrawListToDrawData(ImVector<ImDrawList*>* out_list, ImDrawList* draw_list)
{
if (draw_list->CmdBuffer.empty())
return;
// Remove trailing command if unused
ImDrawCmd& last_cmd = draw_list->CmdBuffer.back();
if (last_cmd.ElemCount == 0 && last_cmd.UserCallback == NULL)
{
draw_list->CmdBuffer.pop_back();
if (draw_list->CmdBuffer.empty())
return;
}
// Draw list sanity check. Detect mismatch between PrimReserve() calls and incrementing _VtxCurrentIdx, _VtxWritePtr etc.
// May trigger for you if you are using PrimXXX functions incorrectly.
IM_ASSERT(draw_list->VtxBuffer.Size == 0 || draw_list->_VtxWritePtr == draw_list->VtxBuffer.Data + draw_list->VtxBuffer.Size);
IM_ASSERT(draw_list->IdxBuffer.Size == 0 || draw_list->_IdxWritePtr == draw_list->IdxBuffer.Data + draw_list->IdxBuffer.Size);
if (!(draw_list->Flags & ImDrawListFlags_AllowVtxOffset))
IM_ASSERT((int)draw_list->_VtxCurrentIdx == draw_list->VtxBuffer.Size);
// Check that draw_list doesn't use more vertices than indexable (default ImDrawIdx = unsigned short = 2 bytes = 64K vertices per ImDrawList = per window)
// If this assert triggers because you are drawing lots of stuff manually:
// - First, make sure you are coarse clipping yourself and not trying to draw many things outside visible bounds.
// Be mindful that the ImDrawList API doesn't filter vertices. Use the Metrics window to inspect draw list contents.
// - If you want large meshes with more than 64K vertices, you can either:
// (A) Handle the ImDrawCmd::VtxOffset value in your renderer back-end, and set 'io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset'.
// Most example back-ends already support this from 1.71. Pre-1.71 back-ends won't.
// Some graphics API such as GL ES 1/2 don't have a way to offset the starting vertex so it is not supported for them.
// (B) Or handle 32-bit indices in your renderer back-end, and uncomment '#define ImDrawIdx unsigned int' line in imconfig.h.
// Most example back-ends already support this. For example, the OpenGL example code detect index size at compile-time:
// glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer_offset);
// Your own engine or render API may use different parameters or function calls to specify index sizes.
// 2 and 4 bytes indices are generally supported by most graphics API.
// - If for some reason neither of those solutions works for you, a workaround is to call BeginChild()/EndChild() before reaching
// the 64K limit to split your draw commands in multiple draw lists.
if (sizeof(ImDrawIdx) == 2)
IM_ASSERT(draw_list->_VtxCurrentIdx < (1 << 16) && "Too many vertices in ImDrawList using 16-bit indices. Read comment above");
out_list->push_back(draw_list);
}
static void AddWindowToDrawData(ImVector<ImDrawList*>* out_render_list, ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
g.IO.MetricsRenderWindows++;
AddDrawListToDrawData(out_render_list, window->DrawList);
for (int i = 0; i < window->DC.ChildWindows.Size; i++)
{
ImGuiWindow* child = window->DC.ChildWindows[i];
if (IsWindowActiveAndVisible(child)) // clipped children may have been marked not active
AddWindowToDrawData(out_render_list, child);
}
}
// Layer is locked for the root window, however child windows may use a different viewport (e.g. extruding menu)
static void AddRootWindowToDrawData(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
int layer = (window->Flags & ImGuiWindowFlags_Tooltip) ? 1 : 0;
AddWindowToDrawData(&g.DrawDataBuilder.Layers[layer], window);
}
void ImDrawDataBuilder::FlattenIntoSingleLayer()
{
int n = Layers[0].Size;
int size = n;
for (int i = 1; i < IM_ARRAYSIZE(Layers); i++)
size += Layers[i].Size;
Layers[0].resize(size);
for (int layer_n = 1; layer_n < IM_ARRAYSIZE(Layers); layer_n++)
{
ImVector<ImDrawList*>& layer = Layers[layer_n];
if (layer.empty())
continue;
memcpy(&Layers[0][n], &layer[0], layer.Size * sizeof(ImDrawList*));
n += layer.Size;
layer.resize(0);
}
}
static void SetupDrawData(ImVector<ImDrawList*>* draw_lists, ImDrawData* draw_data)
{
ImGuiIO& io = ImGui::GetIO();
draw_data->Valid = true;
draw_data->CmdLists = (draw_lists->Size > 0) ? draw_lists->Data : NULL;
draw_data->CmdListsCount = draw_lists->Size;
draw_data->TotalVtxCount = draw_data->TotalIdxCount = 0;
draw_data->DisplayPos = ImVec2(0.0f, 0.0f);
draw_data->DisplaySize = io.DisplaySize;
draw_data->FramebufferScale = io.DisplayFramebufferScale;
for (int n = 0; n < draw_lists->Size; n++)
{
draw_data->TotalVtxCount += draw_lists->Data[n]->VtxBuffer.Size;
draw_data->TotalIdxCount += draw_lists->Data[n]->IdxBuffer.Size;
}
}
// When using this function it is sane to ensure that float are perfectly rounded to integer values, to that e.g. (int)(max.x-min.x) in user's render produce correct result.
void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect)
{
ImGuiWindow* window = GetCurrentWindow();
window->DrawList->PushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect);
window->ClipRect = window->DrawList->_ClipRectStack.back();
}
void ImGui::PopClipRect()
{
ImGuiWindow* window = GetCurrentWindow();
window->DrawList->PopClipRect();
window->ClipRect = window->DrawList->_ClipRectStack.back();
}
// This is normally called by Render(). You may want to call it directly if you want to avoid calling Render() but the gain will be very minimal.
void ImGui::EndFrame()
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.Initialized);
if (g.FrameCountEnded == g.FrameCount) // Don't process EndFrame() multiple times.
return;
IM_ASSERT(g.WithinFrameScope && "Forgot to call ImGui::NewFrame()?");
// Notify OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME)
if (g.IO.ImeSetInputScreenPosFn && (g.PlatformImeLastPos.x == FLT_MAX || ImLengthSqr(g.PlatformImeLastPos - g.PlatformImePos) > 0.0001f))
{
g.IO.ImeSetInputScreenPosFn((int)g.PlatformImePos.x, (int)g.PlatformImePos.y);
g.PlatformImeLastPos = g.PlatformImePos;
}
ErrorCheckEndFrame();
// Hide implicit/fallback "Debug" window if it hasn't been used
g.WithinFrameScopeWithImplicitWindow = false;
if (g.CurrentWindow && !g.CurrentWindow->WriteAccessed)
g.CurrentWindow->Active = false;
End();
// Show CTRL+TAB list window
if (g.NavWindowingTarget != NULL)
NavUpdateWindowingOverlay();
// Drag and Drop: Elapse payload (if delivered, or if source stops being submitted)
if (g.DragDropActive)
{
bool is_delivered = g.DragDropPayload.Delivery;
bool is_elapsed = (g.DragDropPayload.DataFrameCount + 1 < g.FrameCount) && ((g.DragDropSourceFlags & ImGuiDragDropFlags_SourceAutoExpirePayload) || !IsMouseDown(g.DragDropMouseButton));
if (is_delivered || is_elapsed)
ClearDragDrop();
}
// Drag and Drop: Fallback for source tooltip. This is not ideal but better than nothing.
if (g.DragDropActive && g.DragDropSourceFrameCount < g.FrameCount)
{
g.DragDropWithinSourceOrTarget = true;
SetTooltip("...");
g.DragDropWithinSourceOrTarget = false;
}
// End frame
g.WithinFrameScope = false;
g.FrameCountEnded = g.FrameCount;
// Initiate moving window + handle left-click and right-click focus
UpdateMouseMovingWindowEndFrame();
// Sort the window list so that all child windows are after their parent
// We cannot do that on FocusWindow() because childs may not exist yet
g.WindowsTempSortBuffer.resize(0);
g.WindowsTempSortBuffer.reserve(g.Windows.Size);
for (int i = 0; i != g.Windows.Size; i++)
{
ImGuiWindow* window = g.Windows[i];
if (window->Active && (window->Flags & ImGuiWindowFlags_ChildWindow)) // if a child is active its parent will add it
continue;
AddWindowToSortBuffer(&g.WindowsTempSortBuffer, window);
}
// This usually assert if there is a mismatch between the ImGuiWindowFlags_ChildWindow / ParentWindow values and DC.ChildWindows[] in parents, aka we've done something wrong.
IM_ASSERT(g.Windows.Size == g.WindowsTempSortBuffer.Size);
g.Windows.swap(g.WindowsTempSortBuffer);
g.IO.MetricsActiveWindows = g.WindowsActiveCount;
// Unlock font atlas
g.IO.Fonts->Locked = false;
// Clear Input data for next frame
g.IO.MouseWheel = g.IO.MouseWheelH = 0.0f;
g.IO.InputQueueCharacters.resize(0);
memset(g.IO.NavInputs, 0, sizeof(g.IO.NavInputs));
}
void ImGui::Render()
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.Initialized);
if (g.FrameCountEnded != g.FrameCount)
EndFrame();
g.FrameCountRendered = g.FrameCount;
g.IO.MetricsRenderWindows = 0;
g.DrawDataBuilder.Clear();
// Add background ImDrawList
if (!g.BackgroundDrawList.VtxBuffer.empty())
AddDrawListToDrawData(&g.DrawDataBuilder.Layers[0], &g.BackgroundDrawList);
// Add ImDrawList to render
ImGuiWindow* windows_to_render_top_most[2];
windows_to_render_top_most[0] = (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) ? g.NavWindowingTarget->RootWindow : NULL;
windows_to_render_top_most[1] = (g.NavWindowingTarget ? g.NavWindowingList : NULL);
for (int n = 0; n != g.Windows.Size; n++)
{
ImGuiWindow* window = g.Windows[n];
if (IsWindowActiveAndVisible(window) && (window->Flags & ImGuiWindowFlags_ChildWindow) == 0 && window != windows_to_render_top_most[0] && window != windows_to_render_top_most[1])
AddRootWindowToDrawData(window);
}
for (int n = 0; n < IM_ARRAYSIZE(windows_to_render_top_most); n++)
if (windows_to_render_top_most[n] && IsWindowActiveAndVisible(windows_to_render_top_most[n])) // NavWindowingTarget is always temporarily displayed as the top-most window
AddRootWindowToDrawData(windows_to_render_top_most[n]);
g.DrawDataBuilder.FlattenIntoSingleLayer();
// Draw software mouse cursor if requested
if (g.IO.MouseDrawCursor)
RenderMouseCursor(&g.ForegroundDrawList, g.IO.MousePos, g.Style.MouseCursorScale, g.MouseCursor, IM_COL32_WHITE, IM_COL32_BLACK, IM_COL32(0, 0, 0, 48));
// Add foreground ImDrawList
if (!g.ForegroundDrawList.VtxBuffer.empty())
AddDrawListToDrawData(&g.DrawDataBuilder.Layers[0], &g.ForegroundDrawList);
// Setup ImDrawData structure for end-user
SetupDrawData(&g.DrawDataBuilder.Layers[0], &g.DrawData);
g.IO.MetricsRenderVertices = g.DrawData.TotalVtxCount;
g.IO.MetricsRenderIndices = g.DrawData.TotalIdxCount;
// (Legacy) Call the Render callback function. The current prefer way is to let the user retrieve GetDrawData() and call the render function themselves.
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
if (g.DrawData.CmdListsCount > 0 && g.IO.RenderDrawListsFn != NULL)
g.IO.RenderDrawListsFn(&g.DrawData);
#endif
}
// Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker.
// CalcTextSize("") should return ImVec2(0.0f, g.FontSize)
ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width)
{
ImGuiContext& g = *GImGui;
const char* text_display_end;
if (hide_text_after_double_hash)
text_display_end = FindRenderedTextEnd(text, text_end); // Hide anything after a '##' string
else
text_display_end = text_end;
ImFont* font = g.Font;
const float font_size = g.FontSize;
if (text == text_display_end)
return ImVec2(0.0f, font_size);
ImVec2 text_size = font->CalcTextSizeA(font_size, FLT_MAX, wrap_width, text, text_display_end, NULL);
// Round
text_size.x = IM_FLOOR(text_size.x + 0.95f);
return text_size;
}
// Find window given position, search front-to-back
// FIXME: Note that we have an inconsequential lag here: OuterRectClipped is updated in Begin(), so windows moved programatically
// with SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is
// called, aka before the next Begin(). Moving window isn't affected.
static void FindHoveredWindow()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* hovered_window = NULL;
if (g.MovingWindow && !(g.MovingWindow->Flags & ImGuiWindowFlags_NoMouseInputs))
hovered_window = g.MovingWindow;
ImVec2 padding_regular = g.Style.TouchExtraPadding;
ImVec2 padding_for_resize_from_edges = g.IO.ConfigWindowsResizeFromEdges ? ImMax(g.Style.TouchExtraPadding, ImVec2(WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS, WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS)) : padding_regular;
for (int i = g.Windows.Size - 1; i >= 0; i--)
{
ImGuiWindow* window = g.Windows[i];
if (!window->Active || window->Hidden)
continue;
if (window->Flags & ImGuiWindowFlags_NoMouseInputs)
continue;
// Using the clipped AABB, a child window will typically be clipped by its parent (not always)
ImRect bb(window->OuterRectClipped);
if (window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize))
bb.Expand(padding_regular);
else
bb.Expand(padding_for_resize_from_edges);
if (!bb.Contains(g.IO.MousePos))
continue;
// Those seemingly unnecessary extra tests are because the code here is a little different in viewport/docking branches.
if (hovered_window == NULL)
hovered_window = window;
if (hovered_window)
break;
}
g.HoveredWindow = hovered_window;
g.HoveredRootWindow = g.HoveredWindow ? g.HoveredWindow->RootWindow : NULL;
}
// Test if mouse cursor is hovering given rectangle
// NB- Rectangle is clipped by our current clip setting
// NB- Expand the rectangle to be generous on imprecise inputs systems (g.Style.TouchExtraPadding)
bool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip)
{
ImGuiContext& g = *GImGui;
// Clip
ImRect rect_clipped(r_min, r_max);
if (clip)
rect_clipped.ClipWith(g.CurrentWindow->ClipRect);
// Expand for touch input
const ImRect rect_for_touch(rect_clipped.Min - g.Style.TouchExtraPadding, rect_clipped.Max + g.Style.TouchExtraPadding);
if (!rect_for_touch.Contains(g.IO.MousePos))
return false;
return true;
}
int ImGui::GetKeyIndex(ImGuiKey imgui_key)
{
IM_ASSERT(imgui_key >= 0 && imgui_key < ImGuiKey_COUNT);
ImGuiContext& g = *GImGui;
return g.IO.KeyMap[imgui_key];
}
// Note that dear imgui doesn't know the semantic of each entry of io.KeysDown[]!
// Use your own indices/enums according to how your back-end/engine stored them into io.KeysDown[]!
bool ImGui::IsKeyDown(int user_key_index)
{
if (user_key_index < 0)
return false;
ImGuiContext& g = *GImGui;
IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(g.IO.KeysDown));
return g.IO.KeysDown[user_key_index];
}
// t0 = previous time (e.g.: g.Time - g.IO.DeltaTime)
// t1 = current time (e.g.: g.Time)
// An event is triggered at:
// t = 0.0f t = repeat_delay, t = repeat_delay + repeat_rate*N
int ImGui::CalcTypematicRepeatAmount(float t0, float t1, float repeat_delay, float repeat_rate)
{
if (t1 == 0.0f)
return 1;
if (t0 >= t1)
return 0;
if (repeat_rate <= 0.0f)
return (t0 < repeat_delay) && (t1 >= repeat_delay);
const int count_t0 = (t0 < repeat_delay) ? -1 : (int)((t0 - repeat_delay) / repeat_rate);
const int count_t1 = (t1 < repeat_delay) ? -1 : (int)((t1 - repeat_delay) / repeat_rate);
const int count = count_t1 - count_t0;
return count;
}
int ImGui::GetKeyPressedAmount(int key_index, float repeat_delay, float repeat_rate)
{
ImGuiContext& g = *GImGui;
if (key_index < 0)
return 0;
IM_ASSERT(key_index >= 0 && key_index < IM_ARRAYSIZE(g.IO.KeysDown));
const float t = g.IO.KeysDownDuration[key_index];
return CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, repeat_delay, repeat_rate);
}
bool ImGui::IsKeyPressed(int user_key_index, bool repeat)
{
ImGuiContext& g = *GImGui;
if (user_key_index < 0)
return false;
IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(g.IO.KeysDown));
const float t = g.IO.KeysDownDuration[user_key_index];
if (t == 0.0f)
return true;
if (repeat && t > g.IO.KeyRepeatDelay)
return GetKeyPressedAmount(user_key_index, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate) > 0;
return false;
}
bool ImGui::IsKeyReleased(int user_key_index)
{
ImGuiContext& g = *GImGui;
if (user_key_index < 0) return false;
IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(g.IO.KeysDown));
return g.IO.KeysDownDurationPrev[user_key_index] >= 0.0f && !g.IO.KeysDown[user_key_index];
}
bool ImGui::IsMouseDown(ImGuiMouseButton button)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
return g.IO.MouseDown[button];
}
bool ImGui::IsMouseClicked(ImGuiMouseButton button, bool repeat)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
const float t = g.IO.MouseDownDuration[button];
if (t == 0.0f)
return true;
if (repeat && t > g.IO.KeyRepeatDelay)
{
// FIXME: 2019/05/03: Our old repeat code was wrong here and led to doubling the repeat rate, which made it an ok rate for repeat on mouse hold.
int amount = CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate * 0.50f);
if (amount > 0)
return true;
}
return false;
}
bool ImGui::IsMouseReleased(ImGuiMouseButton button)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
return g.IO.MouseReleased[button];
}
bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
return g.IO.MouseDoubleClicked[button];
}
// [Internal] This doesn't test if the button is pressed
bool ImGui::IsMouseDragPastThreshold(ImGuiMouseButton button, float lock_threshold)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
if (lock_threshold < 0.0f)
lock_threshold = g.IO.MouseDragThreshold;
return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold;
}
bool ImGui::IsMouseDragging(ImGuiMouseButton button, float lock_threshold)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
if (!g.IO.MouseDown[button])
return false;
return IsMouseDragPastThreshold(button, lock_threshold);
}
ImVec2 ImGui::GetMousePos()
{
ImGuiContext& g = *GImGui;
return g.IO.MousePos;
}
// NB: prefer to call right after BeginPopup(). At the time Selectable/MenuItem is activated, the popup is already closed!
ImVec2 ImGui::GetMousePosOnOpeningCurrentPopup()
{
ImGuiContext& g = *GImGui;
if (g.BeginPopupStack.Size > 0)
return g.OpenPopupStack[g.BeginPopupStack.Size-1].OpenMousePos;
return g.IO.MousePos;
}
// We typically use ImVec2(-FLT_MAX,-FLT_MAX) to denote an invalid mouse position.
bool ImGui::IsMousePosValid(const ImVec2* mouse_pos)
{
// The assert is only to silence a false-positive in XCode Static Analysis.
// Because GImGui is not dereferenced in every code path, the static analyzer assume that it may be NULL (which it doesn't for other functions).
IM_ASSERT(GImGui != NULL);
const float MOUSE_INVALID = -256000.0f;
ImVec2 p = mouse_pos ? *mouse_pos : GImGui->IO.MousePos;
return p.x >= MOUSE_INVALID && p.y >= MOUSE_INVALID;
}
bool ImGui::IsAnyMouseDown()
{
ImGuiContext& g = *GImGui;
for (int n = 0; n < IM_ARRAYSIZE(g.IO.MouseDown); n++)
if (g.IO.MouseDown[n])
return true;
return false;
}
// Return the delta from the initial clicking position while the mouse button is clicked or was just released.
// This is locked and return 0.0f until the mouse moves past a distance threshold at least once.
// NB: This is only valid if IsMousePosValid(). Back-ends in theory should always keep mouse position valid when dragging even outside the client window.
ImVec2 ImGui::GetMouseDragDelta(ImGuiMouseButton button, float lock_threshold)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
if (lock_threshold < 0.0f)
lock_threshold = g.IO.MouseDragThreshold;
if (g.IO.MouseDown[button] || g.IO.MouseReleased[button])
if (g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold)
if (IsMousePosValid(&g.IO.MousePos) && IsMousePosValid(&g.IO.MouseClickedPos[button]))
return g.IO.MousePos - g.IO.MouseClickedPos[button];
return ImVec2(0.0f, 0.0f);
}
void ImGui::ResetMouseDragDelta(ImGuiMouseButton button)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
// NB: We don't need to reset g.IO.MouseDragMaxDistanceSqr
g.IO.MouseClickedPos[button] = g.IO.MousePos;
}
ImGuiMouseCursor ImGui::GetMouseCursor()
{
return GImGui->MouseCursor;
}
void ImGui::SetMouseCursor(ImGuiMouseCursor cursor_type)
{
GImGui->MouseCursor = cursor_type;
}
void ImGui::CaptureKeyboardFromApp(bool capture)
{
GImGui->WantCaptureKeyboardNextFrame = capture ? 1 : 0;
}
void ImGui::CaptureMouseFromApp(bool capture)
{
GImGui->WantCaptureMouseNextFrame = capture ? 1 : 0;
}
bool ImGui::IsItemActive()
{
ImGuiContext& g = *GImGui;
if (g.ActiveId)
{
ImGuiWindow* window = g.CurrentWindow;
return g.ActiveId == window->DC.LastItemId;
}
return false;
}
bool ImGui::IsItemActivated()
{
ImGuiContext& g = *GImGui;
if (g.ActiveId)
{
ImGuiWindow* window = g.CurrentWindow;
if (g.ActiveId == window->DC.LastItemId && g.ActiveIdPreviousFrame != window->DC.LastItemId)
return true;
}
return false;
}
bool ImGui::IsItemDeactivated()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HasDeactivated)
return (window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_Deactivated) != 0;
return (g.ActiveIdPreviousFrame == window->DC.LastItemId && g.ActiveIdPreviousFrame != 0 && g.ActiveId != window->DC.LastItemId);
}
bool ImGui::IsItemDeactivatedAfterEdit()
{
ImGuiContext& g = *GImGui;
return IsItemDeactivated() && (g.ActiveIdPreviousFrameHasBeenEditedBefore || (g.ActiveId == 0 && g.ActiveIdHasBeenEditedBefore));
}
bool ImGui::IsItemFocused()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (g.NavId == 0 || g.NavDisableHighlight || g.NavId != window->DC.LastItemId)
return false;
return true;
}
bool ImGui::IsItemClicked(ImGuiMouseButton mouse_button)
{
return IsMouseClicked(mouse_button) && IsItemHovered(ImGuiHoveredFlags_None);
}
bool ImGui::IsItemToggledOpen()
{
ImGuiContext& g = *GImGui;
return (g.CurrentWindow->DC.LastItemStatusFlags & ImGuiItemStatusFlags_ToggledOpen) ? true : false;
}
bool ImGui::IsItemToggledSelection()
{
ImGuiContext& g = *GImGui;
return (g.CurrentWindow->DC.LastItemStatusFlags & ImGuiItemStatusFlags_ToggledSelection) ? true : false;
}
bool ImGui::IsAnyItemHovered()
{
ImGuiContext& g = *GImGui;
return g.HoveredId != 0 || g.HoveredIdPreviousFrame != 0;
}
bool ImGui::IsAnyItemActive()
{
ImGuiContext& g = *GImGui;
return g.ActiveId != 0;
}
bool ImGui::IsAnyItemFocused()
{
ImGuiContext& g = *GImGui;
return g.NavId != 0 && !g.NavDisableHighlight;
}
bool ImGui::IsItemVisible()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->ClipRect.Overlaps(window->DC.LastItemRect);
}
bool ImGui::IsItemEdited()
{
ImGuiWindow* window = GetCurrentWindowRead();
return (window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_Edited) != 0;
}
// Allow last item to be overlapped by a subsequent item. Both may be activated during the same frame before the later one takes priority.
void ImGui::SetItemAllowOverlap()
{
ImGuiContext& g = *GImGui;
if (g.HoveredId == g.CurrentWindow->DC.LastItemId)
g.HoveredIdAllowOverlap = true;
if (g.ActiveId == g.CurrentWindow->DC.LastItemId)
g.ActiveIdAllowOverlap = true;
}
ImVec2 ImGui::GetItemRectMin()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.LastItemRect.Min;
}
ImVec2 ImGui::GetItemRectMax()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.LastItemRect.Max;
}
ImVec2 ImGui::GetItemRectSize()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.LastItemRect.GetSize();
}
static ImRect GetViewportRect()
{
ImGuiContext& g = *GImGui;
return ImRect(0.0f, 0.0f, g.IO.DisplaySize.x, g.IO.DisplaySize.y);
}
bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* parent_window = g.CurrentWindow;
flags |= ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_ChildWindow;
flags |= (parent_window->Flags & ImGuiWindowFlags_NoMove); // Inherit the NoMove flag
// Size
const ImVec2 content_avail = GetContentRegionAvail();
ImVec2 size = ImFloor(size_arg);
const int auto_fit_axises = ((size.x == 0.0f) ? (1 << ImGuiAxis_X) : 0x00) | ((size.y == 0.0f) ? (1 << ImGuiAxis_Y) : 0x00);
if (size.x <= 0.0f)
size.x = ImMax(content_avail.x + size.x, 4.0f); // Arbitrary minimum child size (0.0f causing too much issues)
if (size.y <= 0.0f)
size.y = ImMax(content_avail.y + size.y, 4.0f);
SetNextWindowSize(size);
// Build up name. If you need to append to a same child from multiple location in the ID stack, use BeginChild(ImGuiID id) with a stable value.
char title[256];
if (name)
ImFormatString(title, IM_ARRAYSIZE(title), "%s/%s_%08X", parent_window->Name, name, id);
else
ImFormatString(title, IM_ARRAYSIZE(title), "%s/%08X", parent_window->Name, id);
const float backup_border_size = g.Style.ChildBorderSize;
if (!border)
g.Style.ChildBorderSize = 0.0f;
bool ret = Begin(title, NULL, flags);
g.Style.ChildBorderSize = backup_border_size;
ImGuiWindow* child_window = g.CurrentWindow;
child_window->ChildId = id;
child_window->AutoFitChildAxises = (ImS8)auto_fit_axises;
// Set the cursor to handle case where the user called SetNextWindowPos()+BeginChild() manually.
// While this is not really documented/defined, it seems that the expected thing to do.
if (child_window->BeginCount == 1)
parent_window->DC.CursorPos = child_window->Pos;
// Process navigation-in immediately so NavInit can run on first frame
if (g.NavActivateId == id && !(flags & ImGuiWindowFlags_NavFlattened) && (child_window->DC.NavLayerActiveMask != 0 || child_window->DC.NavHasScroll))
{
FocusWindow(child_window);
NavInitWindow(child_window, false);
SetActiveID(id+1, child_window); // Steal ActiveId with a dummy id so that key-press won't activate child item
g.ActiveIdSource = ImGuiInputSource_Nav;
}
return ret;
}
bool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags)
{
ImGuiWindow* window = GetCurrentWindow();
return BeginChildEx(str_id, window->GetID(str_id), size_arg, border, extra_flags);
}
bool ImGui::BeginChild(ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags)
{
IM_ASSERT(id != 0);
return BeginChildEx(NULL, id, size_arg, border, extra_flags);
}
void ImGui::EndChild()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
IM_ASSERT(g.WithinEndChild == false);
IM_ASSERT(window->Flags & ImGuiWindowFlags_ChildWindow); // Mismatched BeginChild()/EndChild() calls
g.WithinEndChild = true;
if (window->BeginCount > 1)
{
End();
}
else
{
ImVec2 sz = window->Size;
if (window->AutoFitChildAxises & (1 << ImGuiAxis_X)) // Arbitrary minimum zero-ish child size of 4.0f causes less trouble than a 0.0f
sz.x = ImMax(4.0f, sz.x);
if (window->AutoFitChildAxises & (1 << ImGuiAxis_Y))
sz.y = ImMax(4.0f, sz.y);
End();
ImGuiWindow* parent_window = g.CurrentWindow;
ImRect bb(parent_window->DC.CursorPos, parent_window->DC.CursorPos + sz);
ItemSize(sz);
if ((window->DC.NavLayerActiveMask != 0 || window->DC.NavHasScroll) && !(window->Flags & ImGuiWindowFlags_NavFlattened))
{
ItemAdd(bb, window->ChildId);
RenderNavHighlight(bb, window->ChildId);
// When browsing a window that has no activable items (scroll only) we keep a highlight on the child
if (window->DC.NavLayerActiveMask == 0 && window == g.NavWindow)
RenderNavHighlight(ImRect(bb.Min - ImVec2(2,2), bb.Max + ImVec2(2,2)), g.NavId, ImGuiNavHighlightFlags_TypeThin);
}
else
{
// Not navigable into
ItemAdd(bb, 0);
}
}
g.WithinEndChild = false;
}
// Helper to create a child window / scrolling region that looks like a normal widget frame.
bool ImGui::BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags extra_flags)
{
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
PushStyleColor(ImGuiCol_ChildBg, style.Colors[ImGuiCol_FrameBg]);
PushStyleVar(ImGuiStyleVar_ChildRounding, style.FrameRounding);
PushStyleVar(ImGuiStyleVar_ChildBorderSize, style.FrameBorderSize);
PushStyleVar(ImGuiStyleVar_WindowPadding, style.FramePadding);
bool ret = BeginChild(id, size, true, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_AlwaysUseWindowPadding | extra_flags);
PopStyleVar(3);
PopStyleColor();
return ret;
}
void ImGui::EndChildFrame()
{
EndChild();
}
static void SetWindowConditionAllowFlags(ImGuiWindow* window, ImGuiCond flags, bool enabled)
{
window->SetWindowPosAllowFlags = enabled ? (window->SetWindowPosAllowFlags | flags) : (window->SetWindowPosAllowFlags & ~flags);
window->SetWindowSizeAllowFlags = enabled ? (window->SetWindowSizeAllowFlags | flags) : (window->SetWindowSizeAllowFlags & ~flags);
window->SetWindowCollapsedAllowFlags = enabled ? (window->SetWindowCollapsedAllowFlags | flags) : (window->SetWindowCollapsedAllowFlags & ~flags);
}
ImGuiWindow* ImGui::FindWindowByID(ImGuiID id)
{
ImGuiContext& g = *GImGui;
return (ImGuiWindow*)g.WindowsById.GetVoidPtr(id);
}
ImGuiWindow* ImGui::FindWindowByName(const char* name)
{
ImGuiID id = ImHashStr(name);
return FindWindowByID(id);
}
static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags)
{
ImGuiContext& g = *GImGui;
//IMGUI_DEBUG_LOG("CreateNewWindow '%s', flags = 0x%08X\n", name, flags);
// Create window the first time
ImGuiWindow* window = IM_NEW(ImGuiWindow)(&g, name);
window->Flags = flags;
g.WindowsById.SetVoidPtr(window->ID, window);
// Default/arbitrary window position. Use SetNextWindowPos() with the appropriate condition flag to change the initial position of a window.
window->Pos = ImVec2(60, 60);
// User can disable loading and saving of settings. Tooltip and child windows also don't store settings.
if (!(flags & ImGuiWindowFlags_NoSavedSettings))
if (ImGuiWindowSettings* settings = ImGui::FindWindowSettings(window->ID))
{
// Retrieve settings from .ini file
window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
SetWindowConditionAllowFlags(window, ImGuiCond_FirstUseEver, false);
window->Pos = ImVec2(settings->Pos.x, settings->Pos.y);
window->Collapsed = settings->Collapsed;
if (settings->Size.x > 0 && settings->Size.y > 0)
size = ImVec2(settings->Size.x, settings->Size.y);
}
window->Size = window->SizeFull = ImFloor(size);
window->DC.CursorStartPos = window->DC.CursorMaxPos = window->Pos; // So first call to CalcContentSize() doesn't return crazy values
if ((flags & ImGuiWindowFlags_AlwaysAutoResize) != 0)
{
window->AutoFitFramesX = window->AutoFitFramesY = 2;
window->AutoFitOnlyGrows = false;
}
else
{
if (window->Size.x <= 0.0f)
window->AutoFitFramesX = 2;
if (window->Size.y <= 0.0f)
window->AutoFitFramesY = 2;
window->AutoFitOnlyGrows = (window->AutoFitFramesX > 0) || (window->AutoFitFramesY > 0);
}
g.WindowsFocusOrder.push_back(window);
if (flags & ImGuiWindowFlags_NoBringToFrontOnFocus)
g.Windows.push_front(window); // Quite slow but rare and only once
else
g.Windows.push_back(window);
return window;
}
static ImVec2 CalcWindowSizeAfterConstraint(ImGuiWindow* window, ImVec2 new_size)
{
ImGuiContext& g = *GImGui;
if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSizeConstraint)
{
// Using -1,-1 on either X/Y axis to preserve the current size.
ImRect cr = g.NextWindowData.SizeConstraintRect;
new_size.x = (cr.Min.x >= 0 && cr.Max.x >= 0) ? ImClamp(new_size.x, cr.Min.x, cr.Max.x) : window->SizeFull.x;
new_size.y = (cr.Min.y >= 0 && cr.Max.y >= 0) ? ImClamp(new_size.y, cr.Min.y, cr.Max.y) : window->SizeFull.y;
if (g.NextWindowData.SizeCallback)
{
ImGuiSizeCallbackData data;
data.UserData = g.NextWindowData.SizeCallbackUserData;
data.Pos = window->Pos;
data.CurrentSize = window->SizeFull;
data.DesiredSize = new_size;
g.NextWindowData.SizeCallback(&data);
new_size = data.DesiredSize;
}
new_size.x = IM_FLOOR(new_size.x);
new_size.y = IM_FLOOR(new_size.y);
}
// Minimum size
if (!(window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_AlwaysAutoResize)))
{
ImGuiWindow* window_for_height = window;
new_size = ImMax(new_size, g.Style.WindowMinSize);
new_size.y = ImMax(new_size.y, window_for_height->TitleBarHeight() + window_for_height->MenuBarHeight() + ImMax(0.0f, g.Style.WindowRounding - 1.0f)); // Reduce artifacts with very small windows
}
return new_size;
}
static ImVec2 CalcWindowContentSize(ImGuiWindow* window)
{
if (window->Collapsed)
if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
return window->ContentSize;
if (window->Hidden && window->HiddenFramesCannotSkipItems == 0 && window->HiddenFramesCanSkipItems > 0)
return window->ContentSize;
ImVec2 sz;
sz.x = IM_FLOOR((window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : window->DC.CursorMaxPos.x - window->DC.CursorStartPos.x);
sz.y = IM_FLOOR((window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : window->DC.CursorMaxPos.y - window->DC.CursorStartPos.y);
return sz;
}
static ImVec2 CalcWindowAutoFitSize(ImGuiWindow* window, const ImVec2& size_contents)
{
ImGuiContext& g = *GImGui;
ImGuiStyle& style = g.Style;
ImVec2 size_decorations = ImVec2(0.0f, window->TitleBarHeight() + window->MenuBarHeight());
ImVec2 size_pad = window->WindowPadding * 2.0f;
ImVec2 size_desired = size_contents + size_pad + size_decorations;
if (window->Flags & ImGuiWindowFlags_Tooltip)
{
// Tooltip always resize
return size_desired;
}
else
{
// Maximum window size is determined by the viewport size or monitor size
const bool is_popup = (window->Flags & ImGuiWindowFlags_Popup) != 0;
const bool is_menu = (window->Flags & ImGuiWindowFlags_ChildMenu) != 0;
ImVec2 size_min = style.WindowMinSize;
if (is_popup || is_menu) // Popups and menus bypass style.WindowMinSize by default, but we give then a non-zero minimum size to facilitate understanding problematic cases (e.g. empty popups)
size_min = ImMin(size_min, ImVec2(4.0f, 4.0f));
ImVec2 size_auto_fit = ImClamp(size_desired, size_min, ImMax(size_min, g.IO.DisplaySize - style.DisplaySafeAreaPadding * 2.0f));
// When the window cannot fit all contents (either because of constraints, either because screen is too small),
// we are growing the size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than ViewportSize-WindowPadding.
ImVec2 size_auto_fit_after_constraint = CalcWindowSizeAfterConstraint(window, size_auto_fit);
bool will_have_scrollbar_x = (size_auto_fit_after_constraint.x - size_pad.x - size_decorations.x < size_contents.x && !(window->Flags & ImGuiWindowFlags_NoScrollbar) && (window->Flags & ImGuiWindowFlags_HorizontalScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar);
bool will_have_scrollbar_y = (size_auto_fit_after_constraint.y - size_pad.y - size_decorations.y < size_contents.y && !(window->Flags & ImGuiWindowFlags_NoScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysVerticalScrollbar);
if (will_have_scrollbar_x)
size_auto_fit.y += style.ScrollbarSize;
if (will_have_scrollbar_y)
size_auto_fit.x += style.ScrollbarSize;
return size_auto_fit;
}
}
ImVec2 ImGui::CalcWindowExpectedSize(ImGuiWindow* window)
{
ImVec2 size_contents = CalcWindowContentSize(window);
ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, size_contents);
ImVec2 size_final = CalcWindowSizeAfterConstraint(window, size_auto_fit);
return size_final;
}
static ImGuiCol GetWindowBgColorIdxFromFlags(ImGuiWindowFlags flags)
{
if (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
return ImGuiCol_PopupBg;
if (flags & ImGuiWindowFlags_ChildWindow)
return ImGuiCol_ChildBg;
return ImGuiCol_WindowBg;
}
static void CalcResizePosSizeFromAnyCorner(ImGuiWindow* window, const ImVec2& corner_target, const ImVec2& corner_norm, ImVec2* out_pos, ImVec2* out_size)
{
ImVec2 pos_min = ImLerp(corner_target, window->Pos, corner_norm); // Expected window upper-left
ImVec2 pos_max = ImLerp(window->Pos + window->Size, corner_target, corner_norm); // Expected window lower-right
ImVec2 size_expected = pos_max - pos_min;
ImVec2 size_constrained = CalcWindowSizeAfterConstraint(window, size_expected);
*out_pos = pos_min;
if (corner_norm.x == 0.0f)
out_pos->x -= (size_constrained.x - size_expected.x);
if (corner_norm.y == 0.0f)
out_pos->y -= (size_constrained.y - size_expected.y);
*out_size = size_constrained;
}
struct ImGuiResizeGripDef
{
ImVec2 CornerPosN;
ImVec2 InnerDir;
int AngleMin12, AngleMax12;
};
static const ImGuiResizeGripDef resize_grip_def[4] =
{
{ ImVec2(1,1), ImVec2(-1,-1), 0, 3 }, // Lower-right
{ ImVec2(0,1), ImVec2(+1,-1), 3, 6 }, // Lower-left
{ ImVec2(0,0), ImVec2(+1,+1), 6, 9 }, // Upper-left (Unused)
{ ImVec2(1,0), ImVec2(-1,+1), 9,12 }, // Upper-right (Unused)
};
static ImRect GetResizeBorderRect(ImGuiWindow* window, int border_n, float perp_padding, float thickness)
{
ImRect rect = window->Rect();
if (thickness == 0.0f) rect.Max -= ImVec2(1,1);
if (border_n == 0) return ImRect(rect.Min.x + perp_padding, rect.Min.y - thickness, rect.Max.x - perp_padding, rect.Min.y + thickness); // Top
if (border_n == 1) return ImRect(rect.Max.x - thickness, rect.Min.y + perp_padding, rect.Max.x + thickness, rect.Max.y - perp_padding); // Right
if (border_n == 2) return ImRect(rect.Min.x + perp_padding, rect.Max.y - thickness, rect.Max.x - perp_padding, rect.Max.y + thickness); // Bottom
if (border_n == 3) return ImRect(rect.Min.x - thickness, rect.Min.y + perp_padding, rect.Min.x + thickness, rect.Max.y - perp_padding); // Left
IM_ASSERT(0);
return ImRect();
}
// 0..3: corners (Lower-right, Lower-left, Unused, Unused)
// 4..7: borders (Top, Right, Bottom, Left)
ImGuiID ImGui::GetWindowResizeID(ImGuiWindow* window, int n)
{
IM_ASSERT(n >= 0 && n <= 7);
ImGuiID id = window->ID;
id = ImHashStr("#RESIZE", 0, id);
id = ImHashData(&n, sizeof(int), id);
return id;
}
// Handle resize for: Resize Grips, Borders, Gamepad
// Return true when using auto-fit (double click on resize grip)
static bool ImGui::UpdateManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4])
{
ImGuiContext& g = *GImGui;
ImGuiWindowFlags flags = window->Flags;
if ((flags & ImGuiWindowFlags_NoResize) || (flags & ImGuiWindowFlags_AlwaysAutoResize) || window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
return false;
if (window->WasActive == false) // Early out to avoid running this code for e.g. an hidden implicit/fallback Debug window.
return false;
bool ret_auto_fit = false;
const int resize_border_count = g.IO.ConfigWindowsResizeFromEdges ? 4 : 0;
const float grip_draw_size = IM_FLOOR(ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
const float grip_hover_inner_size = IM_FLOOR(grip_draw_size * 0.75f);
const float grip_hover_outer_size = g.IO.ConfigWindowsResizeFromEdges ? WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS : 0.0f;
ImVec2 pos_target(FLT_MAX, FLT_MAX);
ImVec2 size_target(FLT_MAX, FLT_MAX);
// Resize grips and borders are on layer 1
window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Menu);
// Manual resize grips
PushID("#RESIZE");
for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
{
const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n];
const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPosN);
// Using the FlattenChilds button flag we make the resize button accessible even if we are hovering over a child window
ImRect resize_rect(corner - grip.InnerDir * grip_hover_outer_size, corner + grip.InnerDir * grip_hover_inner_size);
if (resize_rect.Min.x > resize_rect.Max.x) ImSwap(resize_rect.Min.x, resize_rect.Max.x);
if (resize_rect.Min.y > resize_rect.Max.y) ImSwap(resize_rect.Min.y, resize_rect.Max.y);
bool hovered, held;
ButtonBehavior(resize_rect, window->GetID(resize_grip_n), &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
//GetForegroundDrawList(window)->AddRect(resize_rect.Min, resize_rect.Max, IM_COL32(255, 255, 0, 255));
if (hovered || held)
g.MouseCursor = (resize_grip_n & 1) ? ImGuiMouseCursor_ResizeNESW : ImGuiMouseCursor_ResizeNWSE;
if (held && g.IO.MouseDoubleClicked[0] && resize_grip_n == 0)
{
// Manual auto-fit when double-clicking
size_target = CalcWindowSizeAfterConstraint(window, size_auto_fit);
ret_auto_fit = true;
ClearActiveID();
}
else if (held)
{
// Resize from any of the four corners
// We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position
ImVec2 corner_target = g.IO.MousePos - g.ActiveIdClickOffset + ImLerp(grip.InnerDir * grip_hover_outer_size, grip.InnerDir * -grip_hover_inner_size, grip.CornerPosN); // Corner of the window corresponding to our corner grip
CalcResizePosSizeFromAnyCorner(window, corner_target, grip.CornerPosN, &pos_target, &size_target);
}
if (resize_grip_n == 0 || held || hovered)
resize_grip_col[resize_grip_n] = GetColorU32(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip);
}
for (int border_n = 0; border_n < resize_border_count; border_n++)
{
bool hovered, held;
ImRect border_rect = GetResizeBorderRect(window, border_n, grip_hover_inner_size, WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS);
ButtonBehavior(border_rect, window->GetID(border_n + 4), &hovered, &held, ImGuiButtonFlags_FlattenChildren);
//GetForegroundDrawLists(window)->AddRect(border_rect.Min, border_rect.Max, IM_COL32(255, 255, 0, 255));
if ((hovered && g.HoveredIdTimer > WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER) || held)
{
g.MouseCursor = (border_n & 1) ? ImGuiMouseCursor_ResizeEW : ImGuiMouseCursor_ResizeNS;
if (held)
*border_held = border_n;
}
if (held)
{
ImVec2 border_target = window->Pos;
ImVec2 border_posn;
if (border_n == 0) { border_posn = ImVec2(0, 0); border_target.y = (g.IO.MousePos.y - g.ActiveIdClickOffset.y + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Top
if (border_n == 1) { border_posn = ImVec2(1, 0); border_target.x = (g.IO.MousePos.x - g.ActiveIdClickOffset.x + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Right
if (border_n == 2) { border_posn = ImVec2(0, 1); border_target.y = (g.IO.MousePos.y - g.ActiveIdClickOffset.y + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Bottom
if (border_n == 3) { border_posn = ImVec2(0, 0); border_target.x = (g.IO.MousePos.x - g.ActiveIdClickOffset.x + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Left
CalcResizePosSizeFromAnyCorner(window, border_target, border_posn, &pos_target, &size_target);
}
}
PopID();
// Restore nav layer
window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Main);
// Navigation resize (keyboard/gamepad)
if (g.NavWindowingTarget && g.NavWindowingTarget->RootWindow == window)
{
ImVec2 nav_resize_delta;
if (g.NavInputSource == ImGuiInputSource_NavKeyboard && g.IO.KeyShift)
nav_resize_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard, ImGuiInputReadMode_Down);
if (g.NavInputSource == ImGuiInputSource_NavGamepad)
nav_resize_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadDPad, ImGuiInputReadMode_Down);
if (nav_resize_delta.x != 0.0f || nav_resize_delta.y != 0.0f)
{
const float NAV_RESIZE_SPEED = 600.0f;
nav_resize_delta *= ImFloor(NAV_RESIZE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y));
g.NavWindowingToggleLayer = false;
g.NavDisableMouseHover = true;
resize_grip_col[0] = GetColorU32(ImGuiCol_ResizeGripActive);
// FIXME-NAV: Should store and accumulate into a separate size buffer to handle sizing constraints properly, right now a constraint will make us stuck.
size_target = CalcWindowSizeAfterConstraint(window, window->SizeFull + nav_resize_delta);
}
}
// Apply back modified position/size to window
if (size_target.x != FLT_MAX)
{
window->SizeFull = size_target;
MarkIniSettingsDirty(window);
}
if (pos_target.x != FLT_MAX)
{
window->Pos = ImFloor(pos_target);
MarkIniSettingsDirty(window);
}
window->Size = window->SizeFull;
return ret_auto_fit;
}
static inline void ClampWindowRect(ImGuiWindow* window, const ImRect& rect, const ImVec2& padding)
{
ImGuiContext& g = *GImGui;
ImVec2 size_for_clamping = (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar)) ? ImVec2(window->Size.x, window->TitleBarHeight()) : window->Size;
window->Pos = ImMin(rect.Max - padding, ImMax(window->Pos + size_for_clamping, rect.Min + padding) - size_for_clamping);
}
static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
float rounding = window->WindowRounding;
float border_size = window->WindowBorderSize;
if (border_size > 0.0f && !(window->Flags & ImGuiWindowFlags_NoBackground))
window->DrawList->AddRect(window->Pos, window->Pos + window->Size, GetColorU32(ImGuiCol_Border), rounding, ImDrawCornerFlags_All, border_size);
int border_held = window->ResizeBorderHeld;
if (border_held != -1)
{
struct ImGuiResizeBorderDef
{
ImVec2 InnerDir;
ImVec2 CornerPosN1, CornerPosN2;
float OuterAngle;
};
static const ImGuiResizeBorderDef resize_border_def[4] =
{
{ ImVec2(0,+1), ImVec2(0,0), ImVec2(1,0), IM_PI*1.50f }, // Top
{ ImVec2(-1,0), ImVec2(1,0), ImVec2(1,1), IM_PI*0.00f }, // Right
{ ImVec2(0,-1), ImVec2(1,1), ImVec2(0,1), IM_PI*0.50f }, // Bottom
{ ImVec2(+1,0), ImVec2(0,1), ImVec2(0,0), IM_PI*1.00f } // Left
};
const ImGuiResizeBorderDef& def = resize_border_def[border_held];
ImRect border_r = GetResizeBorderRect(window, border_held, rounding, 0.0f);
window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.CornerPosN1) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle - IM_PI*0.25f, def.OuterAngle);
window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.CornerPosN2) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle, def.OuterAngle + IM_PI*0.25f);
window->DrawList->PathStroke(GetColorU32(ImGuiCol_SeparatorActive), false, ImMax(2.0f, border_size)); // Thicker than usual
}
if (g.Style.FrameBorderSize > 0 && !(window->Flags & ImGuiWindowFlags_NoTitleBar))
{
float y = window->Pos.y + window->TitleBarHeight() - 1;
window->DrawList->AddLine(ImVec2(window->Pos.x + border_size, y), ImVec2(window->Pos.x + window->Size.x - border_size, y), GetColorU32(ImGuiCol_Border), g.Style.FrameBorderSize);
}
}
// Draw background and borders
// Draw and handle scrollbars
void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size)
{
ImGuiContext& g = *GImGui;
ImGuiStyle& style = g.Style;
ImGuiWindowFlags flags = window->Flags;
// Ensure that ScrollBar doesn't read last frame's SkipItems
window->SkipItems = false;
// Draw window + handle manual resize
// As we highlight the title bar when want_focus is set, multiple reappearing windows will have have their title bar highlighted on their reappearing frame.
const float window_rounding = window->WindowRounding;
const float window_border_size = window->WindowBorderSize;
if (window->Collapsed)
{
// Title bar only
float backup_border_size = style.FrameBorderSize;
g.Style.FrameBorderSize = window->WindowBorderSize;
ImU32 title_bar_col = GetColorU32((title_bar_is_highlight && !g.NavDisableHighlight) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBgCollapsed);
RenderFrame(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, true, window_rounding);
g.Style.FrameBorderSize = backup_border_size;
}
else
{
// Window background
if (!(flags & ImGuiWindowFlags_NoBackground))
{
ImU32 bg_col = GetColorU32(GetWindowBgColorIdxFromFlags(flags));
bool override_alpha = false;
float alpha = 1.0f;
if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasBgAlpha)
{
alpha = g.NextWindowData.BgAlphaVal;
override_alpha = true;
}
if (override_alpha)
bg_col = (bg_col & ~IM_COL32_A_MASK) | (IM_F32_TO_INT8_SAT(alpha) << IM_COL32_A_SHIFT);
window->DrawList->AddRectFilled(window->Pos + ImVec2(0, window->TitleBarHeight()), window->Pos + window->Size, bg_col, window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? ImDrawCornerFlags_All : ImDrawCornerFlags_Bot);
}
// Title bar
if (!(flags & ImGuiWindowFlags_NoTitleBar))
{
ImU32 title_bar_col = GetColorU32(title_bar_is_highlight ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, window_rounding, ImDrawCornerFlags_Top);
}
// Menu bar
if (flags & ImGuiWindowFlags_MenuBar)
{
ImRect menu_bar_rect = window->MenuBarRect();
menu_bar_rect.ClipWith(window->Rect()); // Soft clipping, in particular child window don't have minimum size covering the menu bar so this is useful for them.
window->DrawList->AddRectFilled(menu_bar_rect.Min + ImVec2(window_border_size, 0), menu_bar_rect.Max - ImVec2(window_border_size, 0), GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, ImDrawCornerFlags_Top);
if (style.FrameBorderSize > 0.0f && menu_bar_rect.Max.y < window->Pos.y + window->Size.y)
window->DrawList->AddLine(menu_bar_rect.GetBL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_Border), style.FrameBorderSize);
}
// Scrollbars
if (window->ScrollbarX)
Scrollbar(ImGuiAxis_X);
if (window->ScrollbarY)
Scrollbar(ImGuiAxis_Y);
// Render resize grips (after their input handling so we don't have a frame of latency)
if (!(flags & ImGuiWindowFlags_NoResize))
{
for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
{
const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n];
const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPosN);
window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(window_border_size, resize_grip_draw_size) : ImVec2(resize_grip_draw_size, window_border_size)));
window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(resize_grip_draw_size, window_border_size) : ImVec2(window_border_size, resize_grip_draw_size)));
window->DrawList->PathArcToFast(ImVec2(corner.x + grip.InnerDir.x * (window_rounding + window_border_size), corner.y + grip.InnerDir.y * (window_rounding + window_border_size)), window_rounding, grip.AngleMin12, grip.AngleMax12);
window->DrawList->PathFillConvex(resize_grip_col[resize_grip_n]);
}
}
// Borders
RenderWindowOuterBorders(window);
}
}
// Render title text, collapse button, close button
void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open)
{
ImGuiContext& g = *GImGui;
ImGuiStyle& style = g.Style;
ImGuiWindowFlags flags = window->Flags;
const bool has_close_button = (p_open != NULL);
const bool has_collapse_button = !(flags & ImGuiWindowFlags_NoCollapse) && (style.WindowMenuButtonPosition != ImGuiDir_None);
// Close & Collapse button are on the Menu NavLayer and don't default focus (unless there's nothing else on that layer)
const ImGuiItemFlags item_flags_backup = window->DC.ItemFlags;
window->DC.ItemFlags |= ImGuiItemFlags_NoNavDefaultFocus;
window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Menu);
// Layout buttons
// FIXME: Would be nice to generalize the subtleties expressed here into reusable code.
float pad_l = style.FramePadding.x;
float pad_r = style.FramePadding.x;
float button_sz = g.FontSize;
ImVec2 close_button_pos;
ImVec2 collapse_button_pos;
if (has_close_button)
{
pad_r += button_sz;
close_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - style.FramePadding.x, title_bar_rect.Min.y);
}
if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Right)
{
pad_r += button_sz;
collapse_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - style.FramePadding.x, title_bar_rect.Min.y);
}
if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Left)
{
collapse_button_pos = ImVec2(title_bar_rect.Min.x + pad_l - style.FramePadding.x, title_bar_rect.Min.y);
pad_l += button_sz;
}
// Collapse button (submitting first so it gets priority when choosing a navigation init fallback)
if (has_collapse_button)
if (CollapseButton(window->GetID("#COLLAPSE"), collapse_button_pos))
window->WantCollapseToggle = true; // Defer actual collapsing to next frame as we are too far in the Begin() function
// Close button
if (has_close_button)
if (CloseButton(window->GetID("#CLOSE"), close_button_pos))
*p_open = false;
window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Main);
window->DC.ItemFlags = item_flags_backup;
// Title bar text (with: horizontal alignment, avoiding collapse/close button, optional "unsaved document" marker)
// FIXME: Refactor text alignment facilities along with RenderText helpers, this is WAY too much messy code..
const char* UNSAVED_DOCUMENT_MARKER = "*";
const float marker_size_x = (flags & ImGuiWindowFlags_UnsavedDocument) ? CalcTextSize(UNSAVED_DOCUMENT_MARKER, NULL, false).x : 0.0f;
const ImVec2 text_size = CalcTextSize(name, NULL, true) + ImVec2(marker_size_x, 0.0f);
// As a nice touch we try to ensure that centered title text doesn't get affected by visibility of Close/Collapse button,
// while uncentered title text will still reach edges correct.
if (pad_l > style.FramePadding.x)
pad_l += g.Style.ItemInnerSpacing.x;
if (pad_r > style.FramePadding.x)
pad_r += g.Style.ItemInnerSpacing.x;
if (style.WindowTitleAlign.x > 0.0f && style.WindowTitleAlign.x < 1.0f)
{
float centerness = ImSaturate(1.0f - ImFabs(style.WindowTitleAlign.x - 0.5f) * 2.0f); // 0.0f on either edges, 1.0f on center
float pad_extend = ImMin(ImMax(pad_l, pad_r), title_bar_rect.GetWidth() - pad_l - pad_r - text_size.x);
pad_l = ImMax(pad_l, pad_extend * centerness);
pad_r = ImMax(pad_r, pad_extend * centerness);
}
ImRect layout_r(title_bar_rect.Min.x + pad_l, title_bar_rect.Min.y, title_bar_rect.Max.x - pad_r, title_bar_rect.Max.y);
ImRect clip_r(layout_r.Min.x, layout_r.Min.y, layout_r.Max.x + g.Style.ItemInnerSpacing.x, layout_r.Max.y);
//if (g.IO.KeyCtrl) window->DrawList->AddRect(layout_r.Min, layout_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
RenderTextClipped(layout_r.Min, layout_r.Max, name, NULL, &text_size, style.WindowTitleAlign, &clip_r);
if (flags & ImGuiWindowFlags_UnsavedDocument)
{
ImVec2 marker_pos = ImVec2(ImMax(layout_r.Min.x, layout_r.Min.x + (layout_r.GetWidth() - text_size.x) * style.WindowTitleAlign.x) + text_size.x, layout_r.Min.y) + ImVec2(2 - marker_size_x, 0.0f);
ImVec2 off = ImVec2(0.0f, IM_FLOOR(-g.FontSize * 0.25f));
RenderTextClipped(marker_pos + off, layout_r.Max + off, UNSAVED_DOCUMENT_MARKER, NULL, NULL, ImVec2(0, style.WindowTitleAlign.y), &clip_r);
}
}
void ImGui::UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags flags, ImGuiWindow* parent_window)
{
window->ParentWindow = parent_window;
window->RootWindow = window->RootWindowForTitleBarHighlight = window->RootWindowForNav = window;
if (parent_window && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip))
window->RootWindow = parent_window->RootWindow;
if (parent_window && !(flags & ImGuiWindowFlags_Modal) && (flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)))
window->RootWindowForTitleBarHighlight = parent_window->RootWindowForTitleBarHighlight;
while (window->RootWindowForNav->Flags & ImGuiWindowFlags_NavFlattened)
{
IM_ASSERT(window->RootWindowForNav->ParentWindow != NULL);
window->RootWindowForNav = window->RootWindowForNav->ParentWindow;
}
}
// Push a new Dear ImGui window to add widgets to.
// - A default window called "Debug" is automatically stacked at the beginning of every frame so you can use widgets without explicitly calling a Begin/End pair.
// - Begin/End can be called multiple times during the frame with the same window name to append content.
// - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file).
// You can use the "##" or "###" markers to use the same label with different id, or same id with different label. See documentation at the top of this file.
// - Return false when window is collapsed, so you can early out in your code. You always need to call ImGui::End() even if false is returned.
// - Passing 'bool* p_open' displays a Close button on the upper-right corner of the window, the pointed value will be set to false when the button is pressed.
bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
{
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
IM_ASSERT(name != NULL && name[0] != '\0'); // Window name required
IM_ASSERT(g.WithinFrameScope); // Forgot to call ImGui::NewFrame()
IM_ASSERT(g.FrameCountEnded != g.FrameCount); // Called ImGui::Render() or ImGui::EndFrame() and haven't called ImGui::NewFrame() again yet
// Find or create
ImGuiWindow* window = FindWindowByName(name);
const bool window_just_created = (window == NULL);
if (window_just_created)
{
ImVec2 size_on_first_use = (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize) ? g.NextWindowData.SizeVal : ImVec2(0.0f, 0.0f); // Any condition flag will do since we are creating a new window here.
window = CreateNewWindow(name, size_on_first_use, flags);
}
// Automatically disable manual moving/resizing when NoInputs is set
if ((flags & ImGuiWindowFlags_NoInputs) == ImGuiWindowFlags_NoInputs)
flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize;
if (flags & ImGuiWindowFlags_NavFlattened)
IM_ASSERT(flags & ImGuiWindowFlags_ChildWindow);
const int current_frame = g.FrameCount;
const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame);
window->IsFallbackWindow = (g.CurrentWindowStack.Size == 0 && g.WithinFrameScopeWithImplicitWindow);
// Update the Appearing flag
bool window_just_activated_by_user = (window->LastFrameActive < current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on
const bool window_just_appearing_after_hidden_for_resize = (window->HiddenFramesCannotSkipItems > 0);
if (flags & ImGuiWindowFlags_Popup)
{
ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
window_just_activated_by_user |= (window->PopupId != popup_ref.PopupId); // We recycle popups so treat window as activated if popup id changed
window_just_activated_by_user |= (window != popup_ref.Window);
}
window->Appearing = (window_just_activated_by_user || window_just_appearing_after_hidden_for_resize);
if (window->Appearing)
SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true);
// Update Flags, LastFrameActive, BeginOrderXXX fields
if (first_begin_of_the_frame)
{
window->Flags = (ImGuiWindowFlags)flags;
window->LastFrameActive = current_frame;
window->LastTimeActive = (float)g.Time;
window->BeginOrderWithinParent = 0;
window->BeginOrderWithinContext = (short)(g.WindowsActiveCount++);
}
else
{
flags = window->Flags;
}
// Parent window is latched only on the first call to Begin() of the frame, so further append-calls can be done from a different window stack
ImGuiWindow* parent_window_in_stack = g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back();
ImGuiWindow* parent_window = first_begin_of_the_frame ? ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)) ? parent_window_in_stack : NULL) : window->ParentWindow;
IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow));
// We allow window memory to be compacted so recreate the base stack when needed.
if (window->IDStack.Size == 0)
window->IDStack.push_back(window->ID);
// Add to stack
// We intentionally set g.CurrentWindow to NULL to prevent usage until when the viewport is set, then will call SetCurrentWindow()
g.CurrentWindowStack.push_back(window);
g.CurrentWindow = NULL;
ErrorCheckBeginEndCompareStacksSize(window, true);
if (flags & ImGuiWindowFlags_Popup)
{
ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
popup_ref.Window = window;
g.BeginPopupStack.push_back(popup_ref);
window->PopupId = popup_ref.PopupId;
}
if (window_just_appearing_after_hidden_for_resize && !(flags & ImGuiWindowFlags_ChildWindow))
window->NavLastIds[0] = 0;
// Update ->RootWindow and others pointers (before any possible call to FocusWindow)
if (first_begin_of_the_frame)
UpdateWindowParentAndRootLinks(window, flags, parent_window);
// Process SetNextWindow***() calls
bool window_pos_set_by_api = false;
bool window_size_x_set_by_api = false, window_size_y_set_by_api = false;
if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos)
{
window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) != 0;
if (window_pos_set_by_api && ImLengthSqr(g.NextWindowData.PosPivotVal) > 0.00001f)
{
// May be processed on the next frame if this is our first frame and we are measuring size
// FIXME: Look into removing the branch so everything can go through this same code path for consistency.
window->SetWindowPosVal = g.NextWindowData.PosVal;
window->SetWindowPosPivot = g.NextWindowData.PosPivotVal;
window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
}
else
{
SetWindowPos(window, g.NextWindowData.PosVal, g.NextWindowData.PosCond);
}
}
if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize)
{
window_size_x_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.x > 0.0f);
window_size_y_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.y > 0.0f);
SetWindowSize(window, g.NextWindowData.SizeVal, g.NextWindowData.SizeCond);
}
if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasContentSize)
window->ContentSizeExplicit = g.NextWindowData.ContentSizeVal;
else if (first_begin_of_the_frame)
window->ContentSizeExplicit = ImVec2(0.0f, 0.0f);
if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasCollapsed)
SetWindowCollapsed(window, g.NextWindowData.CollapsedVal, g.NextWindowData.CollapsedCond);
if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasFocus)
FocusWindow(window);
if (window->Appearing)
SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, false);
// When reusing window again multiple times a frame, just append content (don't need to setup again)
if (first_begin_of_the_frame)
{
// Initialize
const bool window_is_child_tooltip = (flags & ImGuiWindowFlags_ChildWindow) && (flags & ImGuiWindowFlags_Tooltip); // FIXME-WIP: Undocumented behavior of Child+Tooltip for pinned tooltip (#1345)
window->Active = true;
window->HasCloseButton = (p_open != NULL);
window->ClipRect = ImVec4(-FLT_MAX,-FLT_MAX,+FLT_MAX,+FLT_MAX);
window->IDStack.resize(1);
// Restore buffer capacity when woken from a compacted state, to avoid
if (window->MemoryCompacted)
GcAwakeTransientWindowBuffers(window);
// Update stored window name when it changes (which can _only_ happen with the "###" operator, so the ID would stay unchanged).
// The title bar always display the 'name' parameter, so we only update the string storage if it needs to be visible to the end-user elsewhere.
bool window_title_visible_elsewhere = false;
if (g.NavWindowingList != NULL && (window->Flags & ImGuiWindowFlags_NoNavFocus) == 0) // Window titles visible when using CTRL+TAB
window_title_visible_elsewhere = true;
if (window_title_visible_elsewhere && !window_just_created && strcmp(name, window->Name) != 0)
{
size_t buf_len = (size_t)window->NameBufLen;
window->Name = ImStrdupcpy(window->Name, &buf_len, name);
window->NameBufLen = (int)buf_len;
}
// UPDATE CONTENTS SIZE, UPDATE HIDDEN STATUS
// Update contents size from last frame for auto-fitting (or use explicit size)
window->ContentSize = CalcWindowContentSize(window);
if (window->HiddenFramesCanSkipItems > 0)
window->HiddenFramesCanSkipItems--;
if (window->HiddenFramesCannotSkipItems > 0)
window->HiddenFramesCannotSkipItems--;
// Hide new windows for one frame until they calculate their size
if (window_just_created && (!window_size_x_set_by_api || !window_size_y_set_by_api))
window->HiddenFramesCannotSkipItems = 1;
// Hide popup/tooltip window when re-opening while we measure size (because we recycle the windows)
// We reset Size/ContentSize for reappearing popups/tooltips early in this function, so further code won't be tempted to use the old size.
if (window_just_activated_by_user && (flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0)
{
window->HiddenFramesCannotSkipItems = 1;
if (flags & ImGuiWindowFlags_AlwaysAutoResize)
{
if (!window_size_x_set_by_api)
window->Size.x = window->SizeFull.x = 0.f;
if (!window_size_y_set_by_api)
window->Size.y = window->SizeFull.y = 0.f;
window->ContentSize = ImVec2(0.f, 0.f);
}
}
// SELECT VIEWPORT
// FIXME-VIEWPORT: In the docking/viewport branch, this is the point where we select the current viewport (which may affect the style)
SetCurrentWindow(window);
// LOCK BORDER SIZE AND PADDING FOR THE FRAME (so that altering them doesn't cause inconsistencies)
if (flags & ImGuiWindowFlags_ChildWindow)
window->WindowBorderSize = style.ChildBorderSize;
else
window->WindowBorderSize = ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupBorderSize : style.WindowBorderSize;
window->WindowPadding = style.WindowPadding;
if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & (ImGuiWindowFlags_AlwaysUseWindowPadding | ImGuiWindowFlags_Popup)) && window->WindowBorderSize == 0.0f)
window->WindowPadding = ImVec2(0.0f, (flags & ImGuiWindowFlags_MenuBar) ? style.WindowPadding.y : 0.0f);
// Collapse window by double-clicking on title bar
// At this point we don't have a clipping rectangle setup yet, so we can use the title bar area for hit detection and drawing
if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse))
{
// We don't use a regular button+id to test for double-click on title bar (mostly due to legacy reason, could be fixed), so verify that we don't have items over the title bar.
ImRect title_bar_rect = window->TitleBarRect();
if (g.HoveredWindow == window && g.HoveredId == 0 && g.HoveredIdPreviousFrame == 0 && IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max) && g.IO.MouseDoubleClicked[0])
window->WantCollapseToggle = true;
if (window->WantCollapseToggle)
{
window->Collapsed = !window->Collapsed;
MarkIniSettingsDirty(window);
FocusWindow(window);
}
}
else
{
window->Collapsed = false;
}
window->WantCollapseToggle = false;
// SIZE
// Calculate auto-fit size, handle automatic resize
const ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, window->ContentSize);
bool use_current_size_for_scrollbar_x = window_just_created;
bool use_current_size_for_scrollbar_y = window_just_created;
if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed)
{
// Using SetNextWindowSize() overrides ImGuiWindowFlags_AlwaysAutoResize, so it can be used on tooltips/popups, etc.
if (!window_size_x_set_by_api)
{
window->SizeFull.x = size_auto_fit.x;
use_current_size_for_scrollbar_x = true;
}
if (!window_size_y_set_by_api)
{
window->SizeFull.y = size_auto_fit.y;
use_current_size_for_scrollbar_y = true;
}
}
else if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
{
// Auto-fit may only grow window during the first few frames
// We still process initial auto-fit on collapsed windows to get a window width, but otherwise don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed.
if (!window_size_x_set_by_api && window->AutoFitFramesX > 0)
{
window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x;
use_current_size_for_scrollbar_x = true;
}
if (!window_size_y_set_by_api && window->AutoFitFramesY > 0)
{
window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y;
use_current_size_for_scrollbar_y = true;
}
if (!window->Collapsed)
MarkIniSettingsDirty(window);
}
// Apply minimum/maximum window size constraints and final size
window->SizeFull = CalcWindowSizeAfterConstraint(window, window->SizeFull);
window->Size = window->Collapsed && !(flags & ImGuiWindowFlags_ChildWindow) ? window->TitleBarRect().GetSize() : window->SizeFull;
// Decoration size
const float decoration_up_height = window->TitleBarHeight() + window->MenuBarHeight();
// POSITION
// Popup latch its initial position, will position itself when it appears next frame
if (window_just_activated_by_user)
{
window->AutoPosLastDirection = ImGuiDir_None;
if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api)
window->Pos = g.BeginPopupStack.back().OpenPopupPos;
}
// Position child window
if (flags & ImGuiWindowFlags_ChildWindow)
{
IM_ASSERT(parent_window && parent_window->Active);
window->BeginOrderWithinParent = (short)parent_window->DC.ChildWindows.Size;
parent_window->DC.ChildWindows.push_back(window);
if (!(flags & ImGuiWindowFlags_Popup) && !window_pos_set_by_api && !window_is_child_tooltip)
window->Pos = parent_window->DC.CursorPos;
}
const bool window_pos_with_pivot = (window->SetWindowPosVal.x != FLT_MAX && window->HiddenFramesCannotSkipItems == 0);
if (window_pos_with_pivot)
SetWindowPos(window, window->SetWindowPosVal - window->SizeFull * window->SetWindowPosPivot, 0); // Position given a pivot (e.g. for centering)
else if ((flags & ImGuiWindowFlags_ChildMenu) != 0)
window->Pos = FindBestWindowPosForPopup(window);
else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_just_appearing_after_hidden_for_resize)
window->Pos = FindBestWindowPosForPopup(window);
else if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api && !window_is_child_tooltip)
window->Pos = FindBestWindowPosForPopup(window);
// Clamp position/size so window stays visible within its viewport or monitor
// Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing.
ImRect viewport_rect(GetViewportRect());
if (!window_pos_set_by_api && !(flags & ImGuiWindowFlags_ChildWindow) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
{
ImVec2 clamp_padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding);
if (viewport_rect.GetWidth() > 0 && viewport_rect.GetHeight() > 0.0f)
{
ClampWindowRect(window, viewport_rect, clamp_padding);
}
}
window->Pos = ImFloor(window->Pos);
// Lock window rounding for the frame (so that altering them doesn't cause inconsistencies)
window->WindowRounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildRounding : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupRounding : style.WindowRounding;
// Apply window focus (new and reactivated windows are moved to front)
bool want_focus = false;
if (window_just_activated_by_user && !(flags & ImGuiWindowFlags_NoFocusOnAppearing))
{
if (flags & ImGuiWindowFlags_Popup)
want_focus = true;
else if ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Tooltip)) == 0)
want_focus = true;
}
// Handle manual resize: Resize Grips, Borders, Gamepad
int border_held = -1;
ImU32 resize_grip_col[4] = {};
const int resize_grip_count = g.IO.ConfigWindowsResizeFromEdges ? 2 : 1; // Allow resize from lower-left if we have the mouse cursor feedback for it.
const float resize_grip_draw_size = IM_FLOOR(ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
if (!window->Collapsed)
if (UpdateManualResize(window, size_auto_fit, &border_held, resize_grip_count, &resize_grip_col[0]))
use_current_size_for_scrollbar_x = use_current_size_for_scrollbar_y = true;
window->ResizeBorderHeld = (signed char)border_held;
// SCROLLBAR VISIBILITY
// Update scrollbar visibility (based on the Size that was effective during last frame or the auto-resized Size).
if (!window->Collapsed)
{
// When reading the current size we need to read it after size constraints have been applied.
// When we use InnerRect here we are intentionally reading last frame size, same for ScrollbarSizes values before we set them again.
ImVec2 avail_size_from_current_frame = ImVec2(window->SizeFull.x, window->SizeFull.y - decoration_up_height);
ImVec2 avail_size_from_last_frame = window->InnerRect.GetSize() + window->ScrollbarSizes;
ImVec2 needed_size_from_last_frame = window_just_created ? ImVec2(0, 0) : window->ContentSize + window->WindowPadding * 2.0f;
float size_x_for_scrollbars = use_current_size_for_scrollbar_x ? avail_size_from_current_frame.x : avail_size_from_last_frame.x;
float size_y_for_scrollbars = use_current_size_for_scrollbar_y ? avail_size_from_current_frame.y : avail_size_from_last_frame.y;
//bool scrollbar_y_from_last_frame = window->ScrollbarY; // FIXME: May want to use that in the ScrollbarX expression? How many pros vs cons?
window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar));
window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((needed_size_from_last_frame.x > size_x_for_scrollbars - (window->ScrollbarY ? style.ScrollbarSize : 0.0f)) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar));
if (window->ScrollbarX && !window->ScrollbarY)
window->ScrollbarY = (needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar);
window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f);
}
// UPDATE RECTANGLES (1- THOSE NOT AFFECTED BY SCROLLING)
// Update various regions. Variables they depends on should be set above in this function.
// We set this up after processing the resize grip so that our rectangles doesn't lag by a frame.
// Outer rectangle
// Not affected by window border size. Used by:
// - FindHoveredWindow() (w/ extra padding when border resize is enabled)
// - Begin() initial clipping rect for drawing window background and borders.
// - Begin() clipping whole child
const ImRect host_rect = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip) ? parent_window->ClipRect : viewport_rect;
const ImRect outer_rect = window->Rect();
const ImRect title_bar_rect = window->TitleBarRect();
window->OuterRectClipped = outer_rect;
window->OuterRectClipped.ClipWith(host_rect);
// Inner rectangle
// Not affected by window border size. Used by:
// - InnerClipRect
// - ScrollToBringRectIntoView()
// - NavUpdatePageUpPageDown()
// - Scrollbar()
window->InnerRect.Min.x = window->Pos.x;
window->InnerRect.Min.y = window->Pos.y + decoration_up_height;
window->InnerRect.Max.x = window->Pos.x + window->Size.x - window->ScrollbarSizes.x;
window->InnerRect.Max.y = window->Pos.y + window->Size.y - window->ScrollbarSizes.y;
// Inner clipping rectangle.
// Will extend a little bit outside the normal work region.
// This is to allow e.g. Selectable or CollapsingHeader or some separators to cover that space.
// Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result.
// Note that if our window is collapsed we will end up with an inverted (~null) clipping rectangle which is the correct behavior.
// Affected by window/frame border size. Used by:
// - Begin() initial clip rect
float top_border_size = (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize);
window->InnerClipRect.Min.x = ImFloor(0.5f + window->InnerRect.Min.x + ImMax(ImFloor(window->WindowPadding.x * 0.5f), window->WindowBorderSize));
window->InnerClipRect.Min.y = ImFloor(0.5f + window->InnerRect.Min.y + top_border_size);
window->InnerClipRect.Max.x = ImFloor(0.5f + window->InnerRect.Max.x - ImMax(ImFloor(window->WindowPadding.x * 0.5f), window->WindowBorderSize));
window->InnerClipRect.Max.y = ImFloor(0.5f + window->InnerRect.Max.y - window->WindowBorderSize);
window->InnerClipRect.ClipWithFull(host_rect);
// Default item width. Make it proportional to window size if window manually resizes
if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize))
window->ItemWidthDefault = ImFloor(window->Size.x * 0.65f);
else
window->ItemWidthDefault = ImFloor(g.FontSize * 16.0f);
// SCROLLING
// Lock down maximum scrolling
// The value of ScrollMax are ahead from ScrollbarX/ScrollbarY which is intentionally using InnerRect from previous rect in order to accommodate
// for right/bottom aligned items without creating a scrollbar.
window->ScrollMax.x = ImMax(0.0f, window->ContentSize.x + window->WindowPadding.x * 2.0f - window->InnerRect.GetWidth());
window->ScrollMax.y = ImMax(0.0f, window->ContentSize.y + window->WindowPadding.y * 2.0f - window->InnerRect.GetHeight());
// Apply scrolling
window->Scroll = CalcNextScrollFromScrollTargetAndClamp(window, true);
window->ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
// DRAWING
// Setup draw list and outer clipping rectangle
window->DrawList->Clear();
window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID);
PushClipRect(host_rect.Min, host_rect.Max, false);
// Draw modal window background (darkens what is behind them, all viewports)
const bool dim_bg_for_modal = (flags & ImGuiWindowFlags_Modal) && window == GetTopMostPopupModal() && window->HiddenFramesCannotSkipItems <= 0;
const bool dim_bg_for_window_list = g.NavWindowingTargetAnim && (window == g.NavWindowingTargetAnim->RootWindow);
if (dim_bg_for_modal || dim_bg_for_window_list)
{
const ImU32 dim_bg_col = GetColorU32(dim_bg_for_modal ? ImGuiCol_ModalWindowDimBg : ImGuiCol_NavWindowingDimBg, g.DimBgRatio);
window->DrawList->AddRectFilled(viewport_rect.Min, viewport_rect.Max, dim_bg_col);
}
// Draw navigation selection/windowing rectangle background
if (dim_bg_for_window_list && window == g.NavWindowingTargetAnim)
{
ImRect bb = window->Rect();
bb.Expand(g.FontSize);
if (!bb.Contains(viewport_rect)) // Avoid drawing if the window covers all the viewport anyway
window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha * 0.25f), g.Style.WindowRounding);
}
// Since 1.71, child window can render their decoration (bg color, border, scrollbars, etc.) within their parent to save a draw call.
// When using overlapping child windows, this will break the assumption that child z-order is mapped to submission order.
// We disable this when the parent window has zero vertices, which is a common pattern leading to laying out multiple overlapping child.
// We also disabled this when we have dimming overlay behind this specific one child.
// FIXME: More code may rely on explicit sorting of overlapping child window and would need to disable this somehow. Please get in contact if you are affected.
{
bool render_decorations_in_parent = false;
if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip)
if (window->DrawList->CmdBuffer.back().ElemCount == 0 && parent_window->DrawList->VtxBuffer.Size > 0)
render_decorations_in_parent = true;
if (render_decorations_in_parent)
window->DrawList = parent_window->DrawList;
// Handle title bar, scrollbar, resize grips and resize borders
const ImGuiWindow* window_to_highlight = g.NavWindowingTarget ? g.NavWindowingTarget : g.NavWindow;
const bool title_bar_is_highlight = want_focus || (window_to_highlight && window->RootWindowForTitleBarHighlight == window_to_highlight->RootWindowForTitleBarHighlight);
RenderWindowDecorations(window, title_bar_rect, title_bar_is_highlight, resize_grip_count, resize_grip_col, resize_grip_draw_size);
if (render_decorations_in_parent)
window->DrawList = &window->DrawListInst;
}
// Draw navigation selection/windowing rectangle border
if (g.NavWindowingTargetAnim == window)
{
float rounding = ImMax(window->WindowRounding, g.Style.WindowRounding);
ImRect bb = window->Rect();
bb.Expand(g.FontSize);
if (bb.Contains(viewport_rect)) // If a window fits the entire viewport, adjust its highlight inward
{
bb.Expand(-g.FontSize - 1.0f);
rounding = window->WindowRounding;
}
window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha), rounding, ~0, 3.0f);
}
// UPDATE RECTANGLES (2- THOSE AFFECTED BY SCROLLING)
// Work rectangle.
// Affected by window padding and border size. Used by:
// - Columns() for right-most edge
// - TreeNode(), CollapsingHeader() for right-most edge
// - BeginTabBar() for right-most edge
const bool allow_scrollbar_x = !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar);
const bool allow_scrollbar_y = !(flags & ImGuiWindowFlags_NoScrollbar);
const float work_rect_size_x = (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : ImMax(allow_scrollbar_x ? window->ContentSize.x : 0.0f, window->Size.x - window->WindowPadding.x * 2.0f - window->ScrollbarSizes.x));
const float work_rect_size_y = (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : ImMax(allow_scrollbar_y ? window->ContentSize.y : 0.0f, window->Size.y - window->WindowPadding.y * 2.0f - decoration_up_height - window->ScrollbarSizes.y));
window->WorkRect.Min.x = ImFloor(window->InnerRect.Min.x - window->Scroll.x + ImMax(window->WindowPadding.x, window->WindowBorderSize));
window->WorkRect.Min.y = ImFloor(window->InnerRect.Min.y - window->Scroll.y + ImMax(window->WindowPadding.y, window->WindowBorderSize));
window->WorkRect.Max.x = window->WorkRect.Min.x + work_rect_size_x;
window->WorkRect.Max.y = window->WorkRect.Min.y + work_rect_size_y;
// [LEGACY] Content Region
// FIXME-OBSOLETE: window->ContentRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it.
// Used by:
// - Mouse wheel scrolling + many other things
window->ContentRegionRect.Min.x = window->Pos.x - window->Scroll.x + window->WindowPadding.x;
window->ContentRegionRect.Min.y = window->Pos.y - window->Scroll.y + window->WindowPadding.y + decoration_up_height;
window->ContentRegionRect.Max.x = window->ContentRegionRect.Min.x + (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : (window->Size.x - window->WindowPadding.x * 2.0f - window->ScrollbarSizes.x));
window->ContentRegionRect.Max.y = window->ContentRegionRect.Min.y + (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : (window->Size.y - window->WindowPadding.y * 2.0f - decoration_up_height - window->ScrollbarSizes.y));
// Setup drawing context
// (NB: That term "drawing context / DC" lost its meaning a long time ago. Initially was meant to hold transient data only. Nowadays difference between window-> and window->DC-> is dubious.)
window->DC.Indent.x = 0.0f + window->WindowPadding.x - window->Scroll.x;
window->DC.GroupOffset.x = 0.0f;
window->DC.ColumnsOffset.x = 0.0f;
window->DC.CursorStartPos = window->Pos + ImVec2(window->DC.Indent.x + window->DC.ColumnsOffset.x, decoration_up_height + window->WindowPadding.y - window->Scroll.y);
window->DC.CursorPos = window->DC.CursorStartPos;
window->DC.CursorPosPrevLine = window->DC.CursorPos;
window->DC.CursorMaxPos = window->DC.CursorStartPos;
window->DC.CurrLineSize = window->DC.PrevLineSize = ImVec2(0.0f, 0.0f);
window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f;
window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Main);
window->DC.NavLayerActiveMask = window->DC.NavLayerActiveMaskNext;
window->DC.NavLayerActiveMaskNext = 0x00;
window->DC.NavFocusScopeIdCurrent = 0;
window->DC.NavHideHighlightOneFrame = false;
window->DC.NavHasScroll = (window->ScrollMax.y > 0.0f);
window->DC.MenuBarAppending = false;
window->DC.MenuBarOffset.x = ImMax(ImMax(window->WindowPadding.x, style.ItemSpacing.x), g.NextWindowData.MenuBarOffsetMinVal.x);
window->DC.MenuBarOffset.y = g.NextWindowData.MenuBarOffsetMinVal.y;
window->DC.MenuColumns.Update(3, style.ItemSpacing.x, window_just_activated_by_user);
window->DC.TreeDepth = 0;
window->DC.TreeJumpToParentOnPopMask = 0x00;
window->DC.ChildWindows.resize(0);
window->DC.StateStorage = &window->StateStorage;
window->DC.CurrentColumns = NULL;
window->DC.LayoutType = ImGuiLayoutType_Vertical;
window->DC.ParentLayoutType = parent_window ? parent_window->DC.LayoutType : ImGuiLayoutType_Vertical;
window->DC.FocusCounterRegular = window->DC.FocusCounterTabStop = -1;
window->DC.ItemFlags = parent_window ? parent_window->DC.ItemFlags : ImGuiItemFlags_Default_;
window->DC.ItemWidth = window->ItemWidthDefault;
window->DC.TextWrapPos = -1.0f; // disabled
window->DC.ItemFlagsStack.resize(0);
window->DC.ItemWidthStack.resize(0);
window->DC.TextWrapPosStack.resize(0);
window->DC.GroupStack.resize(0);
if ((flags & ImGuiWindowFlags_ChildWindow) && (window->DC.ItemFlags != parent_window->DC.ItemFlags))
{
window->DC.ItemFlags = parent_window->DC.ItemFlags;
window->DC.ItemFlagsStack.push_back(window->DC.ItemFlags);
}
if (window->AutoFitFramesX > 0)
window->AutoFitFramesX--;
if (window->AutoFitFramesY > 0)
window->AutoFitFramesY--;
// Apply focus (we need to call FocusWindow() AFTER setting DC.CursorStartPos so our initial navigation reference rectangle can start around there)
if (want_focus)
{
FocusWindow(window);
NavInitWindow(window, false);
}
// Title bar
if (!(flags & ImGuiWindowFlags_NoTitleBar))
RenderWindowTitleBarContents(window, title_bar_rect, name, p_open);
// Pressing CTRL+C while holding on a window copy its content to the clipboard
// This works but 1. doesn't handle multiple Begin/End pairs, 2. recursing into another Begin/End pair - so we need to work that out and add better logging scope.
// Maybe we can support CTRL+C on every element?
/*
if (g.ActiveId == move_id)
if (g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_C))
LogToClipboard();
*/
// We fill last item data based on Title Bar/Tab, in order for IsItemHovered() and IsItemActive() to be usable after Begin().
// This is useful to allow creating context menus on title bar only, etc.
window->DC.LastItemId = window->MoveId;
window->DC.LastItemStatusFlags = IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max, false) ? ImGuiItemStatusFlags_HoveredRect : 0;
window->DC.LastItemRect = title_bar_rect;
#ifdef IMGUI_ENABLE_TEST_ENGINE
if (!(window->Flags & ImGuiWindowFlags_NoTitleBar))
IMGUI_TEST_ENGINE_ITEM_ADD(window->DC.LastItemRect, window->DC.LastItemId);
#endif
}
else
{
// Append
SetCurrentWindow(window);
}
PushClipRect(window->InnerClipRect.Min, window->InnerClipRect.Max, true);
// Clear 'accessed' flag last thing (After PushClipRect which will set the flag. We want the flag to stay false when the default "Debug" window is unused)
if (first_begin_of_the_frame)
window->WriteAccessed = false;
window->BeginCount++;
g.NextWindowData.ClearFlags();
if (flags & ImGuiWindowFlags_ChildWindow)
{
// Child window can be out of sight and have "negative" clip windows.
// Mark them as collapsed so commands are skipped earlier (we can't manually collapse them because they have no title bar).
IM_ASSERT((flags & ImGuiWindowFlags_NoTitleBar) != 0);
if (!(flags & ImGuiWindowFlags_AlwaysAutoResize) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
if (window->OuterRectClipped.Min.x >= window->OuterRectClipped.Max.x || window->OuterRectClipped.Min.y >= window->OuterRectClipped.Max.y)
window->HiddenFramesCanSkipItems = 1;
// Hide along with parent or if parent is collapsed
if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCanSkipItems > 0))
window->HiddenFramesCanSkipItems = 1;
if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCannotSkipItems > 0))
window->HiddenFramesCannotSkipItems = 1;
}
// Don't render if style alpha is 0.0 at the time of Begin(). This is arbitrary and inconsistent but has been there for a long while (may remove at some point)
if (style.Alpha <= 0.0f)
window->HiddenFramesCanSkipItems = 1;
// Update the Hidden flag
window->Hidden = (window->HiddenFramesCanSkipItems > 0) || (window->HiddenFramesCannotSkipItems > 0);
// Update the SkipItems flag, used to early out of all items functions (no layout required)
bool skip_items = false;
if (window->Collapsed || !window->Active || window->Hidden)
if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && window->HiddenFramesCannotSkipItems <= 0)
skip_items = true;
window->SkipItems = skip_items;
return !skip_items;
}
void ImGui::End()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
// Error checking: verify that user hasn't called End() too many times!
if (g.CurrentWindowStack.Size <= 1 && g.WithinFrameScopeWithImplicitWindow)
{
IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size > 1, "Calling End() too many times!");
return;
}
IM_ASSERT(g.CurrentWindowStack.Size > 0);
// Error checking: verify that user doesn't directly call End() on a child window.
if (window->Flags & ImGuiWindowFlags_ChildWindow)
IM_ASSERT_USER_ERROR(g.WithinEndChild, "Must call EndChild() and not End()!");
// Close anything that is open
if (window->DC.CurrentColumns)
EndColumns();
PopClipRect(); // Inner window clip rectangle
// Stop logging
if (!(window->Flags & ImGuiWindowFlags_ChildWindow)) // FIXME: add more options for scope of logging
LogFinish();
// Pop from window stack
g.CurrentWindowStack.pop_back();
if (window->Flags & ImGuiWindowFlags_Popup)
g.BeginPopupStack.pop_back();
ErrorCheckBeginEndCompareStacksSize(window, false);
SetCurrentWindow(g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back());
}
void ImGui::BringWindowToFocusFront(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
if (g.WindowsFocusOrder.back() == window)
return;
for (int i = g.WindowsFocusOrder.Size - 2; i >= 0; i--) // We can ignore the top-most window
if (g.WindowsFocusOrder[i] == window)
{
memmove(&g.WindowsFocusOrder[i], &g.WindowsFocusOrder[i + 1], (size_t)(g.WindowsFocusOrder.Size - i - 1) * sizeof(ImGuiWindow*));
g.WindowsFocusOrder[g.WindowsFocusOrder.Size - 1] = window;
break;
}
}
void ImGui::BringWindowToDisplayFront(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* current_front_window = g.Windows.back();
if (current_front_window == window || current_front_window->RootWindow == window)
return;
for (int i = g.Windows.Size - 2; i >= 0; i--) // We can ignore the top-most window
if (g.Windows[i] == window)
{
memmove(&g.Windows[i], &g.Windows[i + 1], (size_t)(g.Windows.Size - i - 1) * sizeof(ImGuiWindow*));
g.Windows[g.Windows.Size - 1] = window;
break;
}
}
void ImGui::BringWindowToDisplayBack(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
if (g.Windows[0] == window)
return;
for (int i = 0; i < g.Windows.Size; i++)
if (g.Windows[i] == window)
{
memmove(&g.Windows[1], &g.Windows[0], (size_t)i * sizeof(ImGuiWindow*));
g.Windows[0] = window;
break;
}
}
// Moving window to front of display and set focus (which happens to be back of our sorted list)
void ImGui::FocusWindow(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
if (g.NavWindow != window)
{
g.NavWindow = window;
if (window && g.NavDisableMouseHover)
g.NavMousePosDirty = true;
g.NavInitRequest = false;
g.NavId = window ? window->NavLastIds[0] : 0; // Restore NavId
g.NavFocusScopeId = 0;
g.NavIdIsAlive = false;
g.NavLayer = ImGuiNavLayer_Main;
//IMGUI_DEBUG_LOG("FocusWindow(\"%s\")\n", window ? window->Name : NULL);
}
// Close popups if any
ClosePopupsOverWindow(window, false);
// Passing NULL allow to disable keyboard focus
if (!window)
return;
// Move the root window to the top of the pile
IM_ASSERT(window->RootWindow != NULL);
ImGuiWindow* focus_front_window = window->RootWindow; // NB: In docking branch this is window->RootWindowDockStop
ImGuiWindow* display_front_window = window->RootWindow;
// Steal focus on active widgets
if (focus_front_window->Flags & ImGuiWindowFlags_Popup) // FIXME: This statement may be unnecessary? Need further testing before removing it..
if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != focus_front_window)
ClearActiveID();
// Bring to front
BringWindowToFocusFront(focus_front_window);
if (((window->Flags | display_front_window->Flags) & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)
BringWindowToDisplayFront(display_front_window);
}
void ImGui::FocusTopMostWindowUnderOne(ImGuiWindow* under_this_window, ImGuiWindow* ignore_window)
{
ImGuiContext& g = *GImGui;
int start_idx = g.WindowsFocusOrder.Size - 1;
if (under_this_window != NULL)
{
int under_this_window_idx = FindWindowFocusIndex(under_this_window);
if (under_this_window_idx != -1)
start_idx = under_this_window_idx - 1;
}
for (int i = start_idx; i >= 0; i--)
{
// We may later decide to test for different NoXXXInputs based on the active navigation input (mouse vs nav) but that may feel more confusing to the user.
ImGuiWindow* window = g.WindowsFocusOrder[i];
if (window != ignore_window && window->WasActive && !(window->Flags & ImGuiWindowFlags_ChildWindow))
if ((window->Flags & (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) != (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs))
{
ImGuiWindow* focus_window = NavRestoreLastChildNavWindow(window);
FocusWindow(focus_window);
return;
}
}
FocusWindow(NULL);
}
void ImGui::SetNextItemWidth(float item_width)
{
ImGuiContext& g = *GImGui;
g.NextItemData.Flags |= ImGuiNextItemDataFlags_HasWidth;
g.NextItemData.Width = item_width;
}
void ImGui::PushItemWidth(float item_width)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
window->DC.ItemWidth = (item_width == 0.0f ? window->ItemWidthDefault : item_width);
window->DC.ItemWidthStack.push_back(window->DC.ItemWidth);
g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
}
void ImGui::PushMultiItemsWidths(int components, float w_full)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
const ImGuiStyle& style = g.Style;
const float w_item_one = ImMax(1.0f, IM_FLOOR((w_full - (style.ItemInnerSpacing.x) * (components-1)) / (float)components));
const float w_item_last = ImMax(1.0f, IM_FLOOR(w_full - (w_item_one + style.ItemInnerSpacing.x) * (components-1)));
window->DC.ItemWidthStack.push_back(w_item_last);
for (int i = 0; i < components-1; i++)
window->DC.ItemWidthStack.push_back(w_item_one);
window->DC.ItemWidth = window->DC.ItemWidthStack.back();
g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
}
void ImGui::PopItemWidth()
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.ItemWidthStack.pop_back();
window->DC.ItemWidth = window->DC.ItemWidthStack.empty() ? window->ItemWidthDefault : window->DC.ItemWidthStack.back();
}
// Calculate default item width given value passed to PushItemWidth() or SetNextItemWidth().
// The SetNextItemWidth() data is generally cleared/consumed by ItemAdd() or NextItemData.ClearFlags()
float ImGui::CalcItemWidth()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
float w;
if (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasWidth)
w = g.NextItemData.Width;
else
w = window->DC.ItemWidth;
if (w < 0.0f)
{
float region_max_x = GetContentRegionMaxAbs().x;
w = ImMax(1.0f, region_max_x - window->DC.CursorPos.x + w);
}
w = IM_FLOOR(w);
return w;
}
// [Internal] Calculate full item size given user provided 'size' parameter and default width/height. Default width is often == CalcItemWidth().
// Those two functions CalcItemWidth vs CalcItemSize are awkwardly named because they are not fully symmetrical.
// Note that only CalcItemWidth() is publicly exposed.
// The 4.0f here may be changed to match CalcItemWidth() and/or BeginChild() (right now we have a mismatch which is harmless but undesirable)
ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_w, float default_h)
{
ImGuiWindow* window = GImGui->CurrentWindow;
ImVec2 region_max;
if (size.x < 0.0f || size.y < 0.0f)
region_max = GetContentRegionMaxAbs();
if (size.x == 0.0f)
size.x = default_w;
else if (size.x < 0.0f)
size.x = ImMax(4.0f, region_max.x - window->DC.CursorPos.x + size.x);
if (size.y == 0.0f)
size.y = default_h;
else if (size.y < 0.0f)
size.y = ImMax(4.0f, region_max.y - window->DC.CursorPos.y + size.y);
return size;
}
void ImGui::SetCurrentFont(ImFont* font)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(font && font->IsLoaded()); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ?
IM_ASSERT(font->Scale > 0.0f);
g.Font = font;
g.FontBaseSize = ImMax(1.0f, g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale);
g.FontSize = g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f;
ImFontAtlas* atlas = g.Font->ContainerAtlas;
g.DrawListSharedData.TexUvWhitePixel = atlas->TexUvWhitePixel;
g.DrawListSharedData.Font = g.Font;
g.DrawListSharedData.FontSize = g.FontSize;
}
void ImGui::PushFont(ImFont* font)
{
ImGuiContext& g = *GImGui;
if (!font)
font = GetDefaultFont();
SetCurrentFont(font);
g.FontStack.push_back(font);
g.CurrentWindow->DrawList->PushTextureID(font->ContainerAtlas->TexID);
}
void ImGui::PopFont()
{
ImGuiContext& g = *GImGui;
g.CurrentWindow->DrawList->PopTextureID();
g.FontStack.pop_back();
SetCurrentFont(g.FontStack.empty() ? GetDefaultFont() : g.FontStack.back());
}
void ImGui::PushItemFlag(ImGuiItemFlags option, bool enabled)
{
ImGuiWindow* window = GetCurrentWindow();
if (enabled)
window->DC.ItemFlags |= option;
else
window->DC.ItemFlags &= ~option;
window->DC.ItemFlagsStack.push_back(window->DC.ItemFlags);
}
void ImGui::PopItemFlag()
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.ItemFlagsStack.pop_back();
window->DC.ItemFlags = window->DC.ItemFlagsStack.empty() ? ImGuiItemFlags_Default_ : window->DC.ItemFlagsStack.back();
}
// FIXME: Look into renaming this once we have settled the new Focus/Activation/TabStop system.
void ImGui::PushAllowKeyboardFocus(bool allow_keyboard_focus)
{
PushItemFlag(ImGuiItemFlags_NoTabStop, !allow_keyboard_focus);
}
void ImGui::PopAllowKeyboardFocus()
{
PopItemFlag();
}
void ImGui::PushButtonRepeat(bool repeat)
{
PushItemFlag(ImGuiItemFlags_ButtonRepeat, repeat);
}
void ImGui::PopButtonRepeat()
{
PopItemFlag();
}
void ImGui::PushTextWrapPos(float wrap_pos_x)
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.TextWrapPos = wrap_pos_x;
window->DC.TextWrapPosStack.push_back(wrap_pos_x);
}
void ImGui::PopTextWrapPos()
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.TextWrapPosStack.pop_back();
window->DC.TextWrapPos = window->DC.TextWrapPosStack.empty() ? -1.0f : window->DC.TextWrapPosStack.back();
}
// FIXME: This may incur a round-trip (if the end user got their data from a float4) but eventually we aim to store the in-flight colors as ImU32
void ImGui::PushStyleColor(ImGuiCol idx, ImU32 col)
{
ImGuiContext& g = *GImGui;
ImGuiColorMod backup;
backup.Col = idx;
backup.BackupValue = g.Style.Colors[idx];
g.ColorModifiers.push_back(backup);
g.Style.Colors[idx] = ColorConvertU32ToFloat4(col);
}
void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col)
{
ImGuiContext& g = *GImGui;
ImGuiColorMod backup;
backup.Col = idx;
backup.BackupValue = g.Style.Colors[idx];
g.ColorModifiers.push_back(backup);
g.Style.Colors[idx] = col;
}
void ImGui::PopStyleColor(int count)
{
ImGuiContext& g = *GImGui;
while (count > 0)
{
ImGuiColorMod& backup = g.ColorModifiers.back();
g.Style.Colors[backup.Col] = backup.BackupValue;
g.ColorModifiers.pop_back();
count--;
}
}
struct ImGuiStyleVarInfo
{
ImGuiDataType Type;
ImU32 Count;
ImU32 Offset;
void* GetVarPtr(ImGuiStyle* style) const { return (void*)((unsigned char*)style + Offset); }
};
static const ImGuiStyleVarInfo GStyleVarInfo[] =
{
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, Alpha) }, // ImGuiStyleVar_Alpha
{ ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowPadding) }, // ImGuiStyleVar_WindowPadding
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowRounding) }, // ImGuiStyleVar_WindowRounding
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowBorderSize) }, // ImGuiStyleVar_WindowBorderSize
{ ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowMinSize) }, // ImGuiStyleVar_WindowMinSize
{ ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowTitleAlign) }, // ImGuiStyleVar_WindowTitleAlign
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildRounding) }, // ImGuiStyleVar_ChildRounding
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildBorderSize) }, // ImGuiStyleVar_ChildBorderSize
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupRounding) }, // ImGuiStyleVar_PopupRounding
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupBorderSize) }, // ImGuiStyleVar_PopupBorderSize
{ ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, FramePadding) }, // ImGuiStyleVar_FramePadding
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameRounding) }, // ImGuiStyleVar_FrameRounding
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameBorderSize) }, // ImGuiStyleVar_FrameBorderSize
{ ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemSpacing) }, // ImGuiStyleVar_ItemSpacing
{ ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemInnerSpacing) }, // ImGuiStyleVar_ItemInnerSpacing
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, IndentSpacing) }, // ImGuiStyleVar_IndentSpacing
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarSize) }, // ImGuiStyleVar_ScrollbarSize
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarRounding) }, // ImGuiStyleVar_ScrollbarRounding
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabMinSize) }, // ImGuiStyleVar_GrabMinSize
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabRounding) }, // ImGuiStyleVar_GrabRounding
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, TabRounding) }, // ImGuiStyleVar_TabRounding
{ ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ButtonTextAlign) }, // ImGuiStyleVar_ButtonTextAlign
{ ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, SelectableTextAlign) }, // ImGuiStyleVar_SelectableTextAlign
};
static const ImGuiStyleVarInfo* GetStyleVarInfo(ImGuiStyleVar idx)
{
IM_ASSERT(idx >= 0 && idx < ImGuiStyleVar_COUNT);
IM_ASSERT(IM_ARRAYSIZE(GStyleVarInfo) == ImGuiStyleVar_COUNT);
return &GStyleVarInfo[idx];
}
void ImGui::PushStyleVar(ImGuiStyleVar idx, float val)
{
const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
if (var_info->Type == ImGuiDataType_Float && var_info->Count == 1)
{
ImGuiContext& g = *GImGui;
float* pvar = (float*)var_info->GetVarPtr(&g.Style);
g.StyleModifiers.push_back(ImGuiStyleMod(idx, *pvar));
*pvar = val;
return;
}
IM_ASSERT(0 && "Called PushStyleVar() float variant but variable is not a float!");
}
void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val)
{
const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
if (var_info->Type == ImGuiDataType_Float && var_info->Count == 2)
{
ImGuiContext& g = *GImGui;
ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style);
g.StyleModifiers.push_back(ImGuiStyleMod(idx, *pvar));
*pvar = val;
return;
}
IM_ASSERT(0 && "Called PushStyleVar() ImVec2 variant but variable is not a ImVec2!");
}
void ImGui::PopStyleVar(int count)
{
ImGuiContext& g = *GImGui;
while (count > 0)
{
// We avoid a generic memcpy(data, &backup.Backup.., GDataTypeSize[info->Type] * info->Count), the overhead in Debug is not worth it.
ImGuiStyleMod& backup = g.StyleModifiers.back();
const ImGuiStyleVarInfo* info = GetStyleVarInfo(backup.VarIdx);
void* data = info->GetVarPtr(&g.Style);
if (info->Type == ImGuiDataType_Float && info->Count == 1) { ((float*)data)[0] = backup.BackupFloat[0]; }
else if (info->Type == ImGuiDataType_Float && info->Count == 2) { ((float*)data)[0] = backup.BackupFloat[0]; ((float*)data)[1] = backup.BackupFloat[1]; }
g.StyleModifiers.pop_back();
count--;
}
}
const char* ImGui::GetStyleColorName(ImGuiCol idx)
{
// Create switch-case from enum with regexp: ImGuiCol_{.*}, --> case ImGuiCol_\1: return "\1";
switch (idx)
{
case ImGuiCol_Text: return "Text";
case ImGuiCol_TextDisabled: return "TextDisabled";
case ImGuiCol_WindowBg: return "WindowBg";
case ImGuiCol_ChildBg: return "ChildBg";
case ImGuiCol_PopupBg: return "PopupBg";
case ImGuiCol_Border: return "Border";
case ImGuiCol_BorderShadow: return "BorderShadow";
case ImGuiCol_FrameBg: return "FrameBg";
case ImGuiCol_FrameBgHovered: return "FrameBgHovered";
case ImGuiCol_FrameBgActive: return "FrameBgActive";
case ImGuiCol_TitleBg: return "TitleBg";
case ImGuiCol_TitleBgActive: return "TitleBgActive";
case ImGuiCol_TitleBgCollapsed: return "TitleBgCollapsed";
case ImGuiCol_MenuBarBg: return "MenuBarBg";
case ImGuiCol_ScrollbarBg: return "ScrollbarBg";
case ImGuiCol_ScrollbarGrab: return "ScrollbarGrab";
case ImGuiCol_ScrollbarGrabHovered: return "ScrollbarGrabHovered";
case ImGuiCol_ScrollbarGrabActive: return "ScrollbarGrabActive";
case ImGuiCol_CheckMark: return "CheckMark";
case ImGuiCol_SliderGrab: return "SliderGrab";
case ImGuiCol_SliderGrabActive: return "SliderGrabActive";
case ImGuiCol_Button: return "Button";
case ImGuiCol_ButtonHovered: return "ButtonHovered";
case ImGuiCol_ButtonActive: return "ButtonActive";
case ImGuiCol_Header: return "Header";
case ImGuiCol_HeaderHovered: return "HeaderHovered";
case ImGuiCol_HeaderActive: return "HeaderActive";
case ImGuiCol_Separator: return "Separator";
case ImGuiCol_SeparatorHovered: return "SeparatorHovered";
case ImGuiCol_SeparatorActive: return "SeparatorActive";
case ImGuiCol_ResizeGrip: return "ResizeGrip";
case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered";
case ImGuiCol_ResizeGripActive: return "ResizeGripActive";
case ImGuiCol_Tab: return "Tab";
case ImGuiCol_TabHovered: return "TabHovered";
case ImGuiCol_TabActive: return "TabActive";
case ImGuiCol_TabUnfocused: return "TabUnfocused";
case ImGuiCol_TabUnfocusedActive: return "TabUnfocusedActive";
case ImGuiCol_PlotLines: return "PlotLines";
case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered";
case ImGuiCol_PlotHistogram: return "PlotHistogram";
case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered";
case ImGuiCol_TextSelectedBg: return "TextSelectedBg";
case ImGuiCol_DragDropTarget: return "DragDropTarget";
case ImGuiCol_NavHighlight: return "NavHighlight";
case ImGuiCol_NavWindowingHighlight: return "NavWindowingHighlight";
case ImGuiCol_NavWindowingDimBg: return "NavWindowingDimBg";
case ImGuiCol_ModalWindowDimBg: return "ModalWindowDimBg";
}
IM_ASSERT(0);
return "Unknown";
}
bool ImGui::IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent)
{
if (window->RootWindow == potential_parent)
return true;
while (window != NULL)
{
if (window == potential_parent)
return true;
window = window->ParentWindow;
}
return false;
}
bool ImGui::IsWindowHovered(ImGuiHoveredFlags flags)
{
IM_ASSERT((flags & ImGuiHoveredFlags_AllowWhenOverlapped) == 0); // Flags not supported by this function
ImGuiContext& g = *GImGui;
if (flags & ImGuiHoveredFlags_AnyWindow)
{
if (g.HoveredWindow == NULL)
return false;
}
else
{
switch (flags & (ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows))
{
case ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows:
if (g.HoveredRootWindow != g.CurrentWindow->RootWindow)
return false;
break;
case ImGuiHoveredFlags_RootWindow:
if (g.HoveredWindow != g.CurrentWindow->RootWindow)
return false;
break;
case ImGuiHoveredFlags_ChildWindows:
if (g.HoveredWindow == NULL || !IsWindowChildOf(g.HoveredWindow, g.CurrentWindow))
return false;
break;
default:
if (g.HoveredWindow != g.CurrentWindow)
return false;
break;
}
}
if (!IsWindowContentHoverable(g.HoveredWindow, flags))
return false;
if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
if (g.ActiveId != 0 && !g.ActiveIdAllowOverlap && g.ActiveId != g.HoveredWindow->MoveId)
return false;
return true;
}
bool ImGui::IsWindowFocused(ImGuiFocusedFlags flags)
{
ImGuiContext& g = *GImGui;
if (flags & ImGuiFocusedFlags_AnyWindow)
return g.NavWindow != NULL;
IM_ASSERT(g.CurrentWindow); // Not inside a Begin()/End()
switch (flags & (ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_ChildWindows))
{
case ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_ChildWindows:
return g.NavWindow && g.NavWindow->RootWindow == g.CurrentWindow->RootWindow;
case ImGuiFocusedFlags_RootWindow:
return g.NavWindow == g.CurrentWindow->RootWindow;
case ImGuiFocusedFlags_ChildWindows:
return g.NavWindow && IsWindowChildOf(g.NavWindow, g.CurrentWindow);
default:
return g.NavWindow == g.CurrentWindow;
}
}
// Can we focus this window with CTRL+TAB (or PadMenu + PadFocusPrev/PadFocusNext)
// Note that NoNavFocus makes the window not reachable with CTRL+TAB but it can still be focused with mouse or programmaticaly.
// If you want a window to never be focused, you may use the e.g. NoInputs flag.
bool ImGui::IsWindowNavFocusable(ImGuiWindow* window)
{
return window->Active && window == window->RootWindow && !(window->Flags & ImGuiWindowFlags_NoNavFocus);
}
float ImGui::GetWindowWidth()
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->Size.x;
}
float ImGui::GetWindowHeight()
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->Size.y;
}
ImVec2 ImGui::GetWindowPos()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
return window->Pos;
}
void ImGui::SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond)
{
// Test condition (NB: bit 0 is always true) and clear flags for next time
if (cond && (window->SetWindowPosAllowFlags & cond) == 0)
return;
IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
window->SetWindowPosVal = ImVec2(FLT_MAX, FLT_MAX);
// Set
const ImVec2 old_pos = window->Pos;
window->Pos = ImFloor(pos);
ImVec2 offset = window->Pos - old_pos;
window->DC.CursorPos += offset; // As we happen to move the window while it is being appended to (which is a bad idea - will smear) let's at least offset the cursor
window->DC.CursorMaxPos += offset; // And more importantly we need to offset CursorMaxPos/CursorStartPos this so ContentSize calculation doesn't get affected.
window->DC.CursorStartPos += offset;
}
void ImGui::SetWindowPos(const ImVec2& pos, ImGuiCond cond)
{
ImGuiWindow* window = GetCurrentWindowRead();
SetWindowPos(window, pos, cond);
}
void ImGui::SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond)
{
if (ImGuiWindow* window = FindWindowByName(name))
SetWindowPos(window, pos, cond);
}
ImVec2 ImGui::GetWindowSize()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->Size;
}
void ImGui::SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond)
{
// Test condition (NB: bit 0 is always true) and clear flags for next time
if (cond && (window->SetWindowSizeAllowFlags & cond) == 0)
return;
IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
window->SetWindowSizeAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
// Set
if (size.x > 0.0f)
{
window->AutoFitFramesX = 0;
window->SizeFull.x = IM_FLOOR(size.x);
}
else
{
window->AutoFitFramesX = 2;
window->AutoFitOnlyGrows = false;
}
if (size.y > 0.0f)
{
window->AutoFitFramesY = 0;
window->SizeFull.y = IM_FLOOR(size.y);
}
else
{
window->AutoFitFramesY = 2;
window->AutoFitOnlyGrows = false;
}
}
void ImGui::SetWindowSize(const ImVec2& size, ImGuiCond cond)
{
SetWindowSize(GImGui->CurrentWindow, size, cond);
}
void ImGui::SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond)
{
if (ImGuiWindow* window = FindWindowByName(name))
SetWindowSize(window, size, cond);
}
void ImGui::SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond)
{
// Test condition (NB: bit 0 is always true) and clear flags for next time
if (cond && (window->SetWindowCollapsedAllowFlags & cond) == 0)
return;
window->SetWindowCollapsedAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
// Set
window->Collapsed = collapsed;
}
void ImGui::SetWindowCollapsed(bool collapsed, ImGuiCond cond)
{
SetWindowCollapsed(GImGui->CurrentWindow, collapsed, cond);
}
bool ImGui::IsWindowCollapsed()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->Collapsed;
}
bool ImGui::IsWindowAppearing()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->Appearing;
}
void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond)
{
if (ImGuiWindow* window = FindWindowByName(name))
SetWindowCollapsed(window, collapsed, cond);
}
void ImGui::SetWindowFocus()
{
FocusWindow(GImGui->CurrentWindow);
}
void ImGui::SetWindowFocus(const char* name)
{
if (name)
{
if (ImGuiWindow* window = FindWindowByName(name))
FocusWindow(window);
}
else
{
FocusWindow(NULL);
}
}
void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiCond cond, const ImVec2& pivot)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasPos;
g.NextWindowData.PosVal = pos;
g.NextWindowData.PosPivotVal = pivot;
g.NextWindowData.PosCond = cond ? cond : ImGuiCond_Always;
}
void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiCond cond)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSize;
g.NextWindowData.SizeVal = size;
g.NextWindowData.SizeCond = cond ? cond : ImGuiCond_Always;
}
void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback, void* custom_callback_user_data)
{
ImGuiContext& g = *GImGui;
g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSizeConstraint;
g.NextWindowData.SizeConstraintRect = ImRect(size_min, size_max);
g.NextWindowData.SizeCallback = custom_callback;
g.NextWindowData.SizeCallbackUserData = custom_callback_user_data;
}
// Content size = inner scrollable rectangle, padded with WindowPadding.
// SetNextWindowContentSize(ImVec2(100,100) + ImGuiWindowFlags_AlwaysAutoResize will always allow submitting a 100x100 item.
void ImGui::SetNextWindowContentSize(const ImVec2& size)
{
ImGuiContext& g = *GImGui;
g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasContentSize;
g.NextWindowData.ContentSizeVal = size;
}
void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiCond cond)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasCollapsed;
g.NextWindowData.CollapsedVal = collapsed;
g.NextWindowData.CollapsedCond = cond ? cond : ImGuiCond_Always;
}
void ImGui::SetNextWindowFocus()
{
ImGuiContext& g = *GImGui;
g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasFocus;
}
void ImGui::SetNextWindowBgAlpha(float alpha)
{
ImGuiContext& g = *GImGui;
g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasBgAlpha;
g.NextWindowData.BgAlphaVal = alpha;
}
// FIXME: This is in window space (not screen space!). We should try to obsolete all those functions.
ImVec2 ImGui::GetContentRegionMax()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
ImVec2 mx = window->ContentRegionRect.Max - window->Pos;
if (window->DC.CurrentColumns)
mx.x = window->WorkRect.Max.x - window->Pos.x;
return mx;
}
// [Internal] Absolute coordinate. Saner. This is not exposed until we finishing refactoring work rect features.
ImVec2 ImGui::GetContentRegionMaxAbs()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
ImVec2 mx = window->ContentRegionRect.Max;
if (window->DC.CurrentColumns)
mx.x = window->WorkRect.Max.x;
return mx;
}
ImVec2 ImGui::GetContentRegionAvail()
{
ImGuiWindow* window = GImGui->CurrentWindow;
return GetContentRegionMaxAbs() - window->DC.CursorPos;
}
// In window space (not screen space!)
ImVec2 ImGui::GetWindowContentRegionMin()
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->ContentRegionRect.Min - window->Pos;
}
ImVec2 ImGui::GetWindowContentRegionMax()
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->ContentRegionRect.Max - window->Pos;
}
float ImGui::GetWindowContentRegionWidth()
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->ContentRegionRect.GetWidth();
}
float ImGui::GetTextLineHeight()
{
ImGuiContext& g = *GImGui;
return g.FontSize;
}
float ImGui::GetTextLineHeightWithSpacing()
{
ImGuiContext& g = *GImGui;
return g.FontSize + g.Style.ItemSpacing.y;
}
float ImGui::GetFrameHeight()
{
ImGuiContext& g = *GImGui;
return g.FontSize + g.Style.FramePadding.y * 2.0f;
}
float ImGui::GetFrameHeightWithSpacing()
{
ImGuiContext& g = *GImGui;
return g.FontSize + g.Style.FramePadding.y * 2.0f + g.Style.ItemSpacing.y;
}
ImDrawList* ImGui::GetWindowDrawList()
{
ImGuiWindow* window = GetCurrentWindow();
return window->DrawList;
}
ImFont* ImGui::GetFont()
{
return GImGui->Font;
}
float ImGui::GetFontSize()
{
return GImGui->FontSize;
}
ImVec2 ImGui::GetFontTexUvWhitePixel()
{
return GImGui->DrawListSharedData.TexUvWhitePixel;
}
void ImGui::SetWindowFontScale(float scale)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
window->FontWindowScale = scale;
g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
}
// User generally sees positions in window coordinates. Internally we store CursorPos in absolute screen coordinates because it is more convenient.
// Conversion happens as we pass the value to user, but it makes our naming convention confusing because GetCursorPos() == (DC.CursorPos - window.Pos). May want to rename 'DC.CursorPos'.
ImVec2 ImGui::GetCursorPos()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.CursorPos - window->Pos + window->Scroll;
}
float ImGui::GetCursorPosX()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.CursorPos.x - window->Pos.x + window->Scroll.x;
}
float ImGui::GetCursorPosY()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.CursorPos.y - window->Pos.y + window->Scroll.y;
}
void ImGui::SetCursorPos(const ImVec2& local_pos)
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.CursorPos = window->Pos - window->Scroll + local_pos;
window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
}
void ImGui::SetCursorPosX(float x)
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + x;
window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPos.x);
}
void ImGui::SetCursorPosY(float y)
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.CursorPos.y = window->Pos.y - window->Scroll.y + y;
window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y);
}
ImVec2 ImGui::GetCursorStartPos()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.CursorStartPos - window->Pos;
}
ImVec2 ImGui::GetCursorScreenPos()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.CursorPos;
}
void ImGui::SetCursorScreenPos(const ImVec2& pos)
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.CursorPos = pos;
window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
}
void ImGui::ActivateItem(ImGuiID id)
{
ImGuiContext& g = *GImGui;
g.NavNextActivateId = id;
}
void ImGui::PushFocusScope(ImGuiID id)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
window->IDStack.push_back(window->DC.NavFocusScopeIdCurrent);
window->DC.NavFocusScopeIdCurrent = id;
}
void ImGui::PopFocusScope()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
window->DC.NavFocusScopeIdCurrent = window->IDStack.back();
window->IDStack.pop_back();
}
void ImGui::SetKeyboardFocusHere(int offset)
{
IM_ASSERT(offset >= -1); // -1 is allowed but not below
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
g.FocusRequestNextWindow = window;
g.FocusRequestNextCounterRegular = window->DC.FocusCounterRegular + 1 + offset;
g.FocusRequestNextCounterTabStop = INT_MAX;
}
void ImGui::SetItemDefaultFocus()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (!window->Appearing)
return;
if (g.NavWindow == window->RootWindowForNav && (g.NavInitRequest || g.NavInitResultId != 0) && g.NavLayer == g.NavWindow->DC.NavLayerCurrent)
{
g.NavInitRequest = false;
g.NavInitResultId = g.NavWindow->DC.LastItemId;
g.NavInitResultRectRel = ImRect(g.NavWindow->DC.LastItemRect.Min - g.NavWindow->Pos, g.NavWindow->DC.LastItemRect.Max - g.NavWindow->Pos);
NavUpdateAnyRequestFlag();
if (!IsItemVisible())
SetScrollHereY();
}
}
void ImGui::SetStateStorage(ImGuiStorage* tree)
{
ImGuiWindow* window = GImGui->CurrentWindow;
window->DC.StateStorage = tree ? tree : &window->StateStorage;
}
ImGuiStorage* ImGui::GetStateStorage()
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->DC.StateStorage;
}
void ImGui::PushID(const char* str_id)
{
ImGuiWindow* window = GImGui->CurrentWindow;
window->IDStack.push_back(window->GetIDNoKeepAlive(str_id));
}
void ImGui::PushID(const char* str_id_begin, const char* str_id_end)
{
ImGuiWindow* window = GImGui->CurrentWindow;
window->IDStack.push_back(window->GetIDNoKeepAlive(str_id_begin, str_id_end));
}
void ImGui::PushID(const void* ptr_id)
{
ImGuiWindow* window = GImGui->CurrentWindow;
window->IDStack.push_back(window->GetIDNoKeepAlive(ptr_id));
}
void ImGui::PushID(int int_id)
{
ImGuiWindow* window = GImGui->CurrentWindow;
window->IDStack.push_back(window->GetIDNoKeepAlive(int_id));
}
// Push a given id value ignoring the ID stack as a seed.
void ImGui::PushOverrideID(ImGuiID id)
{
ImGuiWindow* window = GImGui->CurrentWindow;
window->IDStack.push_back(id);
}
void ImGui::PopID()
{
ImGuiWindow* window = GImGui->CurrentWindow;
window->IDStack.pop_back();
}
ImGuiID ImGui::GetID(const char* str_id)
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->GetID(str_id);
}
ImGuiID ImGui::GetID(const char* str_id_begin, const char* str_id_end)
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->GetID(str_id_begin, str_id_end);
}
ImGuiID ImGui::GetID(const void* ptr_id)
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->GetID(ptr_id);
}
bool ImGui::IsRectVisible(const ImVec2& size)
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->ClipRect.Overlaps(ImRect(window->DC.CursorPos, window->DC.CursorPos + size));
}
bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max)
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->ClipRect.Overlaps(ImRect(rect_min, rect_max));
}
// Lock horizontal starting position + capture group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.)
void ImGui::BeginGroup()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
window->DC.GroupStack.resize(window->DC.GroupStack.Size + 1);
ImGuiGroupData& group_data = window->DC.GroupStack.back();
group_data.BackupCursorPos = window->DC.CursorPos;
group_data.BackupCursorMaxPos = window->DC.CursorMaxPos;
group_data.BackupIndent = window->DC.Indent;
group_data.BackupGroupOffset = window->DC.GroupOffset;
group_data.BackupCurrLineSize = window->DC.CurrLineSize;
group_data.BackupCurrLineTextBaseOffset = window->DC.CurrLineTextBaseOffset;
group_data.BackupActiveIdIsAlive = g.ActiveIdIsAlive;
group_data.BackupActiveIdPreviousFrameIsAlive = g.ActiveIdPreviousFrameIsAlive;
group_data.EmitItem = true;
window->DC.GroupOffset.x = window->DC.CursorPos.x - window->Pos.x - window->DC.ColumnsOffset.x;
window->DC.Indent = window->DC.GroupOffset;
window->DC.CursorMaxPos = window->DC.CursorPos;
window->DC.CurrLineSize = ImVec2(0.0f, 0.0f);
if (g.LogEnabled)
g.LogLinePosY = -FLT_MAX; // To enforce Log carriage return
}
void ImGui::EndGroup()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
IM_ASSERT(!window->DC.GroupStack.empty()); // Mismatched BeginGroup()/EndGroup() calls
ImGuiGroupData& group_data = window->DC.GroupStack.back();
ImRect group_bb(group_data.BackupCursorPos, ImMax(window->DC.CursorMaxPos, group_data.BackupCursorPos));
window->DC.CursorPos = group_data.BackupCursorPos;
window->DC.CursorMaxPos = ImMax(group_data.BackupCursorMaxPos, window->DC.CursorMaxPos);
window->DC.Indent = group_data.BackupIndent;
window->DC.GroupOffset = group_data.BackupGroupOffset;
window->DC.CurrLineSize = group_data.BackupCurrLineSize;
window->DC.CurrLineTextBaseOffset = group_data.BackupCurrLineTextBaseOffset;
if (g.LogEnabled)
g.LogLinePosY = -FLT_MAX; // To enforce Log carriage return
if (!group_data.EmitItem)
{
window->DC.GroupStack.pop_back();
return;
}
window->DC.CurrLineTextBaseOffset = ImMax(window->DC.PrevLineTextBaseOffset, group_data.BackupCurrLineTextBaseOffset); // FIXME: Incorrect, we should grab the base offset from the *first line* of the group but it is hard to obtain now.
ItemSize(group_bb.GetSize());
ItemAdd(group_bb, 0);
// If the current ActiveId was declared within the boundary of our group, we copy it to LastItemId so IsItemActive(), IsItemDeactivated() etc. will be functional on the entire group.
// It would be be neater if we replaced window.DC.LastItemId by e.g. 'bool LastItemIsActive', but would put a little more burden on individual widgets.
// Also if you grep for LastItemId you'll notice it is only used in that context.
// (The tests not symmetrical because ActiveIdIsAlive is an ID itself, in order to be able to handle ActiveId being overwritten during the frame.)
const bool group_contains_curr_active_id = (group_data.BackupActiveIdIsAlive != g.ActiveId) && (g.ActiveIdIsAlive == g.ActiveId) && g.ActiveId;
const bool group_contains_prev_active_id = !group_data.BackupActiveIdPreviousFrameIsAlive && g.ActiveIdPreviousFrameIsAlive;
if (group_contains_curr_active_id)
window->DC.LastItemId = g.ActiveId;
else if (group_contains_prev_active_id)
window->DC.LastItemId = g.ActiveIdPreviousFrame;
window->DC.LastItemRect = group_bb;
// Forward Edited flag
if (group_contains_curr_active_id && g.ActiveIdHasBeenEditedThisFrame)
window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_Edited;
// Forward Deactivated flag
window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_HasDeactivated;
if (group_contains_prev_active_id && g.ActiveId != g.ActiveIdPreviousFrame)
window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_Deactivated;
window->DC.GroupStack.pop_back();
//window->DrawList->AddRect(group_bb.Min, group_bb.Max, IM_COL32(255,0,255,255)); // [Debug]
}
// Gets back to previous line and continue with horizontal layout
// offset_from_start_x == 0 : follow right after previous item
// offset_from_start_x != 0 : align to specified x position (relative to window/group left)
// spacing_w < 0 : use default spacing if pos_x == 0, no spacing if pos_x != 0
// spacing_w >= 0 : enforce spacing amount
void ImGui::SameLine(float offset_from_start_x, float spacing_w)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
ImGuiContext& g = *GImGui;
if (offset_from_start_x != 0.0f)
{
if (spacing_w < 0.0f) spacing_w = 0.0f;
window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + offset_from_start_x + spacing_w + window->DC.GroupOffset.x + window->DC.ColumnsOffset.x;
window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
}
else
{
if (spacing_w < 0.0f) spacing_w = g.Style.ItemSpacing.x;
window->DC.CursorPos.x = window->DC.CursorPosPrevLine.x + spacing_w;
window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
}
window->DC.CurrLineSize = window->DC.PrevLineSize;
window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset;
}
void ImGui::Indent(float indent_w)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
window->DC.Indent.x += (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
}
void ImGui::Unindent(float indent_w)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
window->DC.Indent.x -= (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
}
//-----------------------------------------------------------------------------
// [SECTION] ERROR CHECKING
//-----------------------------------------------------------------------------
static void ImGui::ErrorCheckEndFrame()
{
// Report when there is a mismatch of Begin/BeginChild vs End/EndChild calls. Important: Remember that the Begin/BeginChild API requires you
// to always call End/EndChild even if Begin/BeginChild returns false! (this is unfortunately inconsistent with most other Begin* API).
ImGuiContext& g = *GImGui;
if (g.CurrentWindowStack.Size != 1)
{
if (g.CurrentWindowStack.Size > 1)
{
IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you forget to call End/EndChild?");
while (g.CurrentWindowStack.Size > 1)
End();
}
else
{
IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you call End/EndChild too much?");
}
}
}
// Save and compare stack sizes on Begin()/End() to detect usage errors
// Begin() calls this with write=true
// End() calls this with write=false
static void ImGui::ErrorCheckBeginEndCompareStacksSize(ImGuiWindow* window, bool write)
{
ImGuiContext& g = *GImGui;
short* p = &window->DC.StackSizesBackup[0];
// Window stacks
// NOT checking: DC.ItemWidth, DC.AllowKeyboardFocus, DC.ButtonRepeat, DC.TextWrapPos (per window) to allow user to conveniently push once and not pop (they are cleared on Begin)
{ int n = window->IDStack.Size; if (write) *p = (short)n; else IM_ASSERT(*p == n && "PushID/PopID or TreeNode/TreePop Mismatch!"); p++; } // Too few or too many PopID()/TreePop()
{ int n = window->DC.GroupStack.Size; if (write) *p = (short)n; else IM_ASSERT(*p == n && "BeginGroup/EndGroup Mismatch!"); p++; } // Too few or too many EndGroup()
// Global stacks
// For color, style and font stacks there is an incentive to use Push/Begin/Pop/.../End patterns, so we relax our checks a little to allow them.
{ int n = g.BeginPopupStack.Size; if (write) *p = (short)n; else IM_ASSERT(*p == n && "BeginMenu/EndMenu or BeginPopup/EndPopup Mismatch!"); p++; }// Too few or too many EndMenu()/EndPopup()
{ int n = g.ColorModifiers.Size; if (write) *p = (short)n; else IM_ASSERT(*p >= n && "PushStyleColor/PopStyleColor Mismatch!"); p++; } // Too few or too many PopStyleColor()
{ int n = g.StyleModifiers.Size; if (write) *p = (short)n; else IM_ASSERT(*p >= n && "PushStyleVar/PopStyleVar Mismatch!"); p++; } // Too few or too many PopStyleVar()
{ int n = g.FontStack.Size; if (write) *p = (short)n; else IM_ASSERT(*p >= n && "PushFont/PopFont Mismatch!"); p++; } // Too few or too many PopFont()
IM_ASSERT(p == window->DC.StackSizesBackup + IM_ARRAYSIZE(window->DC.StackSizesBackup));
}
//-----------------------------------------------------------------------------
// [SECTION] SCROLLING
//-----------------------------------------------------------------------------
static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window, bool snap_on_edges)
{
ImGuiContext& g = *GImGui;
ImVec2 scroll = window->Scroll;
if (window->ScrollTarget.x < FLT_MAX)
{
float cr_x = window->ScrollTargetCenterRatio.x;
float target_x = window->ScrollTarget.x;
if (snap_on_edges && cr_x <= 0.0f && target_x <= window->WindowPadding.x)
target_x = 0.0f;
else if (snap_on_edges && cr_x >= 1.0f && target_x >= window->ContentSize.x + window->WindowPadding.x + g.Style.ItemSpacing.x)
target_x = window->ContentSize.x + window->WindowPadding.x * 2.0f;
scroll.x = target_x - cr_x * (window->SizeFull.x - window->ScrollbarSizes.x);
}
if (window->ScrollTarget.y < FLT_MAX)
{
// 'snap_on_edges' allows for a discontinuity at the edge of scrolling limits to take account of WindowPadding so that scrolling to make the last item visible scroll far enough to see the padding.
float decoration_up_height = window->TitleBarHeight() + window->MenuBarHeight();
float cr_y = window->ScrollTargetCenterRatio.y;
float target_y = window->ScrollTarget.y;
if (snap_on_edges && cr_y <= 0.0f && target_y <= window->WindowPadding.y)
target_y = 0.0f;
if (snap_on_edges && cr_y >= 1.0f && target_y >= window->ContentSize.y + window->WindowPadding.y + g.Style.ItemSpacing.y)
target_y = window->ContentSize.y + window->WindowPadding.y * 2.0f;
scroll.y = target_y - cr_y * (window->SizeFull.y - window->ScrollbarSizes.y - decoration_up_height);
}
scroll = ImMax(scroll, ImVec2(0.0f, 0.0f));
if (!window->Collapsed && !window->SkipItems)
{
scroll.x = ImMin(scroll.x, window->ScrollMax.x);
scroll.y = ImMin(scroll.y, window->ScrollMax.y);
}
return scroll;
}
// Scroll to keep newly navigated item fully into view
ImVec2 ImGui::ScrollToBringRectIntoView(ImGuiWindow* window, const ImRect& item_rect)
{
ImGuiContext& g = *GImGui;
ImRect window_rect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1));
//GetForegroundDrawList(window)->AddRect(window_rect.Min, window_rect.Max, IM_COL32_WHITE); // [DEBUG]
ImVec2 delta_scroll;
if (!window_rect.Contains(item_rect))
{
if (window->ScrollbarX && item_rect.Min.x < window_rect.Min.x)
SetScrollFromPosX(window, item_rect.Min.x - window->Pos.x + g.Style.ItemSpacing.x, 0.0f);
else if (window->ScrollbarX && item_rect.Max.x >= window_rect.Max.x)
SetScrollFromPosX(window, item_rect.Max.x - window->Pos.x + g.Style.ItemSpacing.x, 1.0f);
if (item_rect.Min.y < window_rect.Min.y)
SetScrollFromPosY(window, item_rect.Min.y - window->Pos.y - g.Style.ItemSpacing.y, 0.0f);
else if (item_rect.Max.y >= window_rect.Max.y)
SetScrollFromPosY(window, item_rect.Max.y - window->Pos.y + g.Style.ItemSpacing.y, 1.0f);
ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window, false);
delta_scroll = next_scroll - window->Scroll;
}
// Also scroll parent window to keep us into view if necessary
if (window->Flags & ImGuiWindowFlags_ChildWindow)
delta_scroll += ScrollToBringRectIntoView(window->ParentWindow, ImRect(item_rect.Min - delta_scroll, item_rect.Max - delta_scroll));
return delta_scroll;
}
float ImGui::GetScrollX()
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->Scroll.x;
}
float ImGui::GetScrollY()
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->Scroll.y;
}
float ImGui::GetScrollMaxX()
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->ScrollMax.x;
}
float ImGui::GetScrollMaxY()
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->ScrollMax.y;
}
void ImGui::SetScrollX(float scroll_x)
{
ImGuiWindow* window = GetCurrentWindow();
window->ScrollTarget.x = scroll_x;
window->ScrollTargetCenterRatio.x = 0.0f;
}
void ImGui::SetScrollY(float scroll_y)
{
ImGuiWindow* window = GetCurrentWindow();
window->ScrollTarget.y = scroll_y;
window->ScrollTargetCenterRatio.y = 0.0f;
}
void ImGui::SetScrollX(ImGuiWindow* window, float new_scroll_x)
{
window->ScrollTarget.x = new_scroll_x;
window->ScrollTargetCenterRatio.x = 0.0f;
}
void ImGui::SetScrollY(ImGuiWindow* window, float new_scroll_y)
{
window->ScrollTarget.y = new_scroll_y;
window->ScrollTargetCenterRatio.y = 0.0f;
}
void ImGui::SetScrollFromPosX(ImGuiWindow* window, float local_x, float center_x_ratio)
{
// We store a target position so centering can occur on the next frame when we are guaranteed to have a known window size
IM_ASSERT(center_x_ratio >= 0.0f && center_x_ratio <= 1.0f);
window->ScrollTarget.x = IM_FLOOR(local_x + window->Scroll.x);
window->ScrollTargetCenterRatio.x = center_x_ratio;
}
void ImGui::SetScrollFromPosY(ImGuiWindow* window, float local_y, float center_y_ratio)
{
// We store a target position so centering can occur on the next frame when we are guaranteed to have a known window size
IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f);
const float decoration_up_height = window->TitleBarHeight() + window->MenuBarHeight();
local_y -= decoration_up_height;
window->ScrollTarget.y = IM_FLOOR(local_y + window->Scroll.y);
window->ScrollTargetCenterRatio.y = center_y_ratio;
}
void ImGui::SetScrollFromPosX(float local_x, float center_x_ratio)
{
ImGuiContext& g = *GImGui;
SetScrollFromPosX(g.CurrentWindow, local_x, center_x_ratio);
}
void ImGui::SetScrollFromPosY(float local_y, float center_y_ratio)
{
ImGuiContext& g = *GImGui;
SetScrollFromPosY(g.CurrentWindow, local_y, center_y_ratio);
}
// center_x_ratio: 0.0f left of last item, 0.5f horizontal center of last item, 1.0f right of last item.
void ImGui::SetScrollHereX(float center_x_ratio)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
float target_x = window->DC.LastItemRect.Min.x - window->Pos.x; // Left of last item, in window space
float last_item_width = window->DC.LastItemRect.GetWidth();
target_x += (last_item_width * center_x_ratio) + (g.Style.ItemSpacing.x * (center_x_ratio - 0.5f) * 2.0f); // Precisely aim before, in the middle or after the last item.
SetScrollFromPosX(target_x, center_x_ratio);
}
// center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item.
void ImGui::SetScrollHereY(float center_y_ratio)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
float target_y = window->DC.CursorPosPrevLine.y - window->Pos.y; // Top of last item, in window space
target_y += (window->DC.PrevLineSize.y * center_y_ratio) + (g.Style.ItemSpacing.y * (center_y_ratio - 0.5f) * 2.0f); // Precisely aim above, in the middle or below the last line.
SetScrollFromPosY(target_y, center_y_ratio);
}
//-----------------------------------------------------------------------------
// [SECTION] TOOLTIPS
//-----------------------------------------------------------------------------
void ImGui::BeginTooltip()
{
BeginTooltipEx(ImGuiWindowFlags_None, ImGuiTooltipFlags_None);
}
void ImGui::BeginTooltipEx(ImGuiWindowFlags extra_flags, ImGuiTooltipFlags tooltip_flags)
{
ImGuiContext& g = *GImGui;
if (g.DragDropWithinSourceOrTarget)
{
// The default tooltip position is a little offset to give space to see the context menu (it's also clamped within the current viewport/monitor)
// In the context of a dragging tooltip we try to reduce that offset and we enforce following the cursor.
// Whatever we do we want to call SetNextWindowPos() to enforce a tooltip position and disable clipping the tooltip without our display area, like regular tooltip do.
//ImVec2 tooltip_pos = g.IO.MousePos - g.ActiveIdClickOffset - g.Style.WindowPadding;
ImVec2 tooltip_pos = g.IO.MousePos + ImVec2(16 * g.Style.MouseCursorScale, 8 * g.Style.MouseCursorScale);
SetNextWindowPos(tooltip_pos);
SetNextWindowBgAlpha(g.Style.Colors[ImGuiCol_PopupBg].w * 0.60f);
//PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * 0.60f); // This would be nice but e.g ColorButton with checkboard has issue with transparent colors :(
tooltip_flags |= ImGuiTooltipFlags_OverridePreviousTooltip;
}
char window_name[16];
ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", g.TooltipOverrideCount);
if (tooltip_flags & ImGuiTooltipFlags_OverridePreviousTooltip)
if (ImGuiWindow* window = FindWindowByName(window_name))
if (window->Active)
{
// Hide previous tooltip from being displayed. We can't easily "reset" the content of a window so we create a new one.
window->Hidden = true;
window->HiddenFramesCanSkipItems = 1;
ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", ++g.TooltipOverrideCount);
}
ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip|ImGuiWindowFlags_NoInputs|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_AlwaysAutoResize;
Begin(window_name, NULL, flags | extra_flags);
}
void ImGui::EndTooltip()
{
IM_ASSERT(GetCurrentWindowRead()->Flags & ImGuiWindowFlags_Tooltip); // Mismatched BeginTooltip()/EndTooltip() calls
End();
}
void ImGui::SetTooltipV(const char* fmt, va_list args)
{
BeginTooltipEx(0, ImGuiTooltipFlags_OverridePreviousTooltip);
TextV(fmt, args);
EndTooltip();
}
void ImGui::SetTooltip(const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
SetTooltipV(fmt, args);
va_end(args);
}
//-----------------------------------------------------------------------------
// [SECTION] POPUPS
//-----------------------------------------------------------------------------
bool ImGui::IsPopupOpen(ImGuiID id)
{
ImGuiContext& g = *GImGui;
return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == id;
}
bool ImGui::IsPopupOpen(const char* str_id)
{
ImGuiContext& g = *GImGui;
return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == g.CurrentWindow->GetID(str_id);
}
ImGuiWindow* ImGui::GetTopMostPopupModal()
{
ImGuiContext& g = *GImGui;
for (int n = g.OpenPopupStack.Size-1; n >= 0; n--)
if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
if (popup->Flags & ImGuiWindowFlags_Modal)
return popup;
return NULL;
}
void ImGui::OpenPopup(const char* str_id)
{
ImGuiContext& g = *GImGui;
OpenPopupEx(g.CurrentWindow->GetID(str_id));
}
// Mark popup as open (toggle toward open state).
// Popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block.
// Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level).
// One open popup per level of the popup hierarchy (NB: when assigning we reset the Window member of ImGuiPopupRef to NULL)
void ImGui::OpenPopupEx(ImGuiID id)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* parent_window = g.CurrentWindow;
int current_stack_size = g.BeginPopupStack.Size;
ImGuiPopupData popup_ref; // Tagged as new ref as Window will be set back to NULL if we write this into OpenPopupStack.
popup_ref.PopupId = id;
popup_ref.Window = NULL;
popup_ref.SourceWindow = g.NavWindow;
popup_ref.OpenFrameCount = g.FrameCount;
popup_ref.OpenParentId = parent_window->IDStack.back();
popup_ref.OpenPopupPos = NavCalcPreferredRefPos();
popup_ref.OpenMousePos = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : popup_ref.OpenPopupPos;
//IMGUI_DEBUG_LOG("OpenPopupEx(0x%08X)\n", g.FrameCount, id);
if (g.OpenPopupStack.Size < current_stack_size + 1)
{
g.OpenPopupStack.push_back(popup_ref);
}
else
{
// Gently handle the user mistakenly calling OpenPopup() every frame. It is a programming mistake! However, if we were to run the regular code path, the ui
// would become completely unusable because the popup will always be in hidden-while-calculating-size state _while_ claiming focus. Which would be a very confusing
// situation for the programmer. Instead, we silently allow the popup to proceed, it will keep reappearing and the programming error will be more obvious to understand.
if (g.OpenPopupStack[current_stack_size].PopupId == id && g.OpenPopupStack[current_stack_size].OpenFrameCount == g.FrameCount - 1)
{
g.OpenPopupStack[current_stack_size].OpenFrameCount = popup_ref.OpenFrameCount;
}
else
{
// Close child popups if any, then flag popup for open/reopen
g.OpenPopupStack.resize(current_stack_size + 1);
g.OpenPopupStack[current_stack_size] = popup_ref;
}
// When reopening a popup we first refocus its parent, otherwise if its parent is itself a popup it would get closed by ClosePopupsOverWindow().
// This is equivalent to what ClosePopupToLevel() does.
//if (g.OpenPopupStack[current_stack_size].PopupId == id)
// FocusWindow(parent_window);
}
}
void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to_window_under_popup)
{
ImGuiContext& g = *GImGui;
if (g.OpenPopupStack.empty())
return;
// When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it.
// Don't close our own child popup windows.
int popup_count_to_keep = 0;
if (ref_window)
{
// Find the highest popup which is a descendant of the reference window (generally reference window = NavWindow)
for (; popup_count_to_keep < g.OpenPopupStack.Size; popup_count_to_keep++)
{
ImGuiPopupData& popup = g.OpenPopupStack[popup_count_to_keep];
if (!popup.Window)
continue;
IM_ASSERT((popup.Window->Flags & ImGuiWindowFlags_Popup) != 0);
if (popup.Window->Flags & ImGuiWindowFlags_ChildWindow)
continue;
// Trim the stack when popups are not direct descendant of the reference window (the reference window is often the NavWindow)
bool popup_or_descendent_is_ref_window = false;
for (int m = popup_count_to_keep; m < g.OpenPopupStack.Size && !popup_or_descendent_is_ref_window; m++)
if (ImGuiWindow* popup_window = g.OpenPopupStack[m].Window)
if (popup_window->RootWindow == ref_window->RootWindow)
popup_or_descendent_is_ref_window = true;
if (!popup_or_descendent_is_ref_window)
break;
}
}
if (popup_count_to_keep < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the statement below
{
//IMGUI_DEBUG_LOG("ClosePopupsOverWindow(%s) -> ClosePopupToLevel(%d)\n", ref_window->Name, popup_count_to_keep);
ClosePopupToLevel(popup_count_to_keep, restore_focus_to_window_under_popup);
}
}
void ImGui::ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_popup)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(remaining >= 0 && remaining < g.OpenPopupStack.Size);
ImGuiWindow* focus_window = g.OpenPopupStack[remaining].SourceWindow;
ImGuiWindow* popup_window = g.OpenPopupStack[remaining].Window;
g.OpenPopupStack.resize(remaining);
if (restore_focus_to_window_under_popup)
{
if (focus_window && !focus_window->WasActive && popup_window)
{
// Fallback
FocusTopMostWindowUnderOne(popup_window, NULL);
}
else
{
if (g.NavLayer == 0 && focus_window)
focus_window = NavRestoreLastChildNavWindow(focus_window);
FocusWindow(focus_window);
}
}
}
// Close the popup we have begin-ed into.
void ImGui::CloseCurrentPopup()
{
ImGuiContext& g = *GImGui;
int popup_idx = g.BeginPopupStack.Size - 1;
if (popup_idx < 0 || popup_idx >= g.OpenPopupStack.Size || g.BeginPopupStack[popup_idx].PopupId != g.OpenPopupStack[popup_idx].PopupId)
return;
// Closing a menu closes its top-most parent popup (unless a modal)
while (popup_idx > 0)
{
ImGuiWindow* popup_window = g.OpenPopupStack[popup_idx].Window;
ImGuiWindow* parent_popup_window = g.OpenPopupStack[popup_idx - 1].Window;
bool close_parent = false;
if (popup_window && (popup_window->Flags & ImGuiWindowFlags_ChildMenu))
if (parent_popup_window == NULL || !(parent_popup_window->Flags & ImGuiWindowFlags_Modal))
close_parent = true;
if (!close_parent)
break;
popup_idx--;
}
//IMGUI_DEBUG_LOG("CloseCurrentPopup %d -> %d\n", g.BeginPopupStack.Size - 1, popup_idx);
ClosePopupToLevel(popup_idx, true);
// A common pattern is to close a popup when selecting a menu item/selectable that will open another window.
// To improve this usage pattern, we avoid nav highlight for a single frame in the parent window.
// Similarly, we could avoid mouse hover highlight in this window but it is less visually problematic.
if (ImGuiWindow* window = g.NavWindow)
window->DC.NavHideHighlightOneFrame = true;
}
bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags flags)
{
ImGuiContext& g = *GImGui;
if (!IsPopupOpen(id))
{
g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
return false;
}
char name[20];
if (flags & ImGuiWindowFlags_ChildMenu)
ImFormatString(name, IM_ARRAYSIZE(name), "##Menu_%02d", g.BeginPopupStack.Size); // Recycle windows based on depth
else
ImFormatString(name, IM_ARRAYSIZE(name), "##Popup_%08x", id); // Not recycling, so we can close/open during the same frame
flags |= ImGuiWindowFlags_Popup;
bool is_open = Begin(name, NULL, flags);
if (!is_open) // NB: Begin can return false when the popup is completely clipped (e.g. zero size display)
EndPopup();
return is_open;
}
bool ImGui::BeginPopup(const char* str_id, ImGuiWindowFlags flags)
{
ImGuiContext& g = *GImGui;
if (g.OpenPopupStack.Size <= g.BeginPopupStack.Size) // Early out for performance
{
g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
return false;
}
flags |= ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings;
return BeginPopupEx(g.CurrentWindow->GetID(str_id), flags);
}
// If 'p_open' is specified for a modal popup window, the popup will have a regular close button which will close the popup.
// Note that popup visibility status is owned by Dear ImGui (and manipulated with e.g. OpenPopup) so the actual value of *p_open is meaningless here.
bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
const ImGuiID id = window->GetID(name);
if (!IsPopupOpen(id))
{
g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
return false;
}
// Center modal windows by default
// FIXME: Should test for (PosCond & window->SetWindowPosAllowFlags) with the upcoming window.
if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) == 0)
SetNextWindowPos(g.IO.DisplaySize * 0.5f, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f));
flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoSavedSettings;
const bool is_open = Begin(name, p_open, flags);
if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
{
EndPopup();
if (is_open)
ClosePopupToLevel(g.BeginPopupStack.Size, true);
return false;
}
return is_open;
}
void ImGui::EndPopup()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
IM_ASSERT(window->Flags & ImGuiWindowFlags_Popup); // Mismatched BeginPopup()/EndPopup() calls
IM_ASSERT(g.BeginPopupStack.Size > 0);
// Make all menus and popups wrap around for now, may need to expose that policy.
NavMoveRequestTryWrapping(window, ImGuiNavMoveFlags_LoopY);
// Child-popups don't need to be layed out
IM_ASSERT(g.WithinEndChild == false);
if (window->Flags & ImGuiWindowFlags_ChildWindow)
g.WithinEndChild = true;
End();
g.WithinEndChild = false;
}
bool ImGui::OpenPopupOnItemClick(const char* str_id, ImGuiMouseButton mouse_button)
{
ImGuiWindow* window = GImGui->CurrentWindow;
if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
{
ImGuiID id = str_id ? window->GetID(str_id) : window->DC.LastItemId; // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
IM_ASSERT(id != 0); // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
OpenPopupEx(id);
return true;
}
return false;
}
// This is a helper to handle the simplest case of associating one named popup to one given widget.
// You may want to handle this on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters).
// You can pass a NULL str_id to use the identifier of the last item.
bool ImGui::BeginPopupContextItem(const char* str_id, ImGuiMouseButton mouse_button)
{
ImGuiWindow* window = GImGui->CurrentWindow;
if (window->SkipItems)
return false;
ImGuiID id = str_id ? window->GetID(str_id) : window->DC.LastItemId; // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
IM_ASSERT(id != 0); // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
OpenPopupEx(id);
return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings);
}
bool ImGui::BeginPopupContextWindow(const char* str_id, ImGuiMouseButton mouse_button, bool also_over_items)
{
if (!str_id)
str_id = "window_context";
ImGuiID id = GImGui->CurrentWindow->GetID(str_id);
if (IsMouseReleased(mouse_button) && IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
if (also_over_items || !IsAnyItemHovered())
OpenPopupEx(id);
return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings);
}
bool ImGui::BeginPopupContextVoid(const char* str_id, ImGuiMouseButton mouse_button)
{
if (!str_id)
str_id = "void_context";
ImGuiID id = GImGui->CurrentWindow->GetID(str_id);
if (IsMouseReleased(mouse_button) && !IsWindowHovered(ImGuiHoveredFlags_AnyWindow))
OpenPopupEx(id);
return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings);
}
// r_avoid = the rectangle to avoid (e.g. for tooltip it is a rectangle around the mouse cursor which we want to avoid. for popups it's a small point around the cursor.)
// r_outer = the visible area rectangle, minus safe area padding. If our popup size won't fit because of safe area padding we ignore it.
ImVec2 ImGui::FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_outer, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy)
{
ImVec2 base_pos_clamped = ImClamp(ref_pos, r_outer.Min, r_outer.Max - size);
//GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255,0,0,255));
//GetForegroundDrawList()->AddRect(r_outer.Min, r_outer.Max, IM_COL32(0,255,0,255));
// Combo Box policy (we want a connecting edge)
if (policy == ImGuiPopupPositionPolicy_ComboBox)
{
const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Down, ImGuiDir_Right, ImGuiDir_Left, ImGuiDir_Up };
for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
{
const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
if (n != -1 && dir == *last_dir) // Already tried this direction?
continue;
ImVec2 pos;
if (dir == ImGuiDir_Down) pos = ImVec2(r_avoid.Min.x, r_avoid.Max.y); // Below, Toward Right (default)
if (dir == ImGuiDir_Right) pos = ImVec2(r_avoid.Min.x, r_avoid.Min.y - size.y); // Above, Toward Right
if (dir == ImGuiDir_Left) pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Max.y); // Below, Toward Left
if (dir == ImGuiDir_Up) pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Min.y - size.y); // Above, Toward Left
if (!r_outer.Contains(ImRect(pos, pos + size)))
continue;
*last_dir = dir;
return pos;
}
}
// Default popup policy
const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Right, ImGuiDir_Down, ImGuiDir_Up, ImGuiDir_Left };
for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
{
const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
if (n != -1 && dir == *last_dir) // Already tried this direction?
continue;
float avail_w = (dir == ImGuiDir_Left ? r_avoid.Min.x : r_outer.Max.x) - (dir == ImGuiDir_Right ? r_avoid.Max.x : r_outer.Min.x);
float avail_h = (dir == ImGuiDir_Up ? r_avoid.Min.y : r_outer.Max.y) - (dir == ImGuiDir_Down ? r_avoid.Max.y : r_outer.Min.y);
if (avail_w < size.x || avail_h < size.y)
continue;
ImVec2 pos;
pos.x = (dir == ImGuiDir_Left) ? r_avoid.Min.x - size.x : (dir == ImGuiDir_Right) ? r_avoid.Max.x : base_pos_clamped.x;
pos.y = (dir == ImGuiDir_Up) ? r_avoid.Min.y - size.y : (dir == ImGuiDir_Down) ? r_avoid.Max.y : base_pos_clamped.y;
*last_dir = dir;
return pos;
}
// Fallback, try to keep within display
*last_dir = ImGuiDir_None;
ImVec2 pos = ref_pos;
pos.x = ImMax(ImMin(pos.x + size.x, r_outer.Max.x) - size.x, r_outer.Min.x);
pos.y = ImMax(ImMin(pos.y + size.y, r_outer.Max.y) - size.y, r_outer.Min.y);
return pos;
}
ImRect ImGui::GetWindowAllowedExtentRect(ImGuiWindow* window)
{
IM_UNUSED(window);
ImVec2 padding = GImGui->Style.DisplaySafeAreaPadding;
ImRect r_screen = GetViewportRect();
r_screen.Expand(ImVec2((r_screen.GetWidth() > padding.x * 2) ? -padding.x : 0.0f, (r_screen.GetHeight() > padding.y * 2) ? -padding.y : 0.0f));
return r_screen;
}
ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
ImRect r_outer = GetWindowAllowedExtentRect(window);
if (window->Flags & ImGuiWindowFlags_ChildMenu)
{
// Child menus typically request _any_ position within the parent menu item, and then we move the new menu outside the parent bounds.
// This is how we end up with child menus appearing (most-commonly) on the right of the parent menu.
IM_ASSERT(g.CurrentWindow == window);
ImGuiWindow* parent_window = g.CurrentWindowStack[g.CurrentWindowStack.Size - 2];
float horizontal_overlap = g.Style.ItemInnerSpacing.x; // We want some overlap to convey the relative depth of each menu (currently the amount of overlap is hard-coded to style.ItemSpacing.x).
ImRect r_avoid;
if (parent_window->DC.MenuBarAppending)
r_avoid = ImRect(-FLT_MAX, parent_window->Pos.y + parent_window->TitleBarHeight(), FLT_MAX, parent_window->Pos.y + parent_window->TitleBarHeight() + parent_window->MenuBarHeight());
else
r_avoid = ImRect(parent_window->Pos.x + horizontal_overlap, -FLT_MAX, parent_window->Pos.x + parent_window->Size.x - horizontal_overlap - parent_window->ScrollbarSizes.x, FLT_MAX);
return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid);
}
if (window->Flags & ImGuiWindowFlags_Popup)
{
ImRect r_avoid = ImRect(window->Pos.x - 1, window->Pos.y - 1, window->Pos.x + 1, window->Pos.y + 1);
return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid);
}
if (window->Flags & ImGuiWindowFlags_Tooltip)
{
// Position tooltip (always follows mouse)
float sc = g.Style.MouseCursorScale;
ImVec2 ref_pos = NavCalcPreferredRefPos();
ImRect r_avoid;
if (!g.NavDisableHighlight && g.NavDisableMouseHover && !(g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos))
r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 16, ref_pos.y + 8);
else
r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 24 * sc, ref_pos.y + 24 * sc); // FIXME: Hard-coded based on mouse cursor shape expectation. Exact dimension not very important.
ImVec2 pos = FindBestWindowPosForPopupEx(ref_pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid);
if (window->AutoPosLastDirection == ImGuiDir_None)
pos = ref_pos + ImVec2(2, 2); // If there's not enough room, for tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible.
return pos;
}
IM_ASSERT(0);
return window->Pos;
}
//-----------------------------------------------------------------------------
// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
//-----------------------------------------------------------------------------
// FIXME-NAV: The existence of SetNavID vs SetNavIDWithRectRel vs SetFocusID is incredibly messy and confusing,
// and needs some explanation or serious refactoring.
void ImGui::SetNavID(ImGuiID id, int nav_layer, ImGuiID focus_scope_id)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.NavWindow);
IM_ASSERT(nav_layer == 0 || nav_layer == 1);
g.NavId = id;
g.NavFocusScopeId = focus_scope_id;
g.NavWindow->NavLastIds[nav_layer] = id;
}
void ImGui::SetNavIDWithRectRel(ImGuiID id, int nav_layer, ImGuiID focus_scope_id, const ImRect& rect_rel)
{
ImGuiContext& g = *GImGui;
SetNavID(id, nav_layer, focus_scope_id);
g.NavWindow->NavRectRel[nav_layer] = rect_rel;
g.NavMousePosDirty = true;
g.NavDisableHighlight = false;
g.NavDisableMouseHover = true;
}
void ImGui::SetFocusID(ImGuiID id, ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(id != 0);
// Assume that SetFocusID() is called in the context where its window->DC.NavLayerCurrent and window->DC.NavFocusScopeIdCurrent are valid.
// Note that window may be != g.CurrentWindow (e.g. SetFocusID call in InputTextEx for multi-line text)
const ImGuiNavLayer nav_layer = window->DC.NavLayerCurrent;
if (g.NavWindow != window)
g.NavInitRequest = false;
g.NavWindow = window;
g.NavId = id;
g.NavLayer = nav_layer;
g.NavFocusScopeId = window->DC.NavFocusScopeIdCurrent;
window->NavLastIds[nav_layer] = id;
if (window->DC.LastItemId == id)
window->NavRectRel[nav_layer] = ImRect(window->DC.LastItemRect.Min - window->Pos, window->DC.LastItemRect.Max - window->Pos);
if (g.ActiveIdSource == ImGuiInputSource_Nav)
g.NavDisableMouseHover = true;
else
g.NavDisableHighlight = true;
}
ImGuiDir ImGetDirQuadrantFromDelta(float dx, float dy)
{
if (ImFabs(dx) > ImFabs(dy))
return (dx > 0.0f) ? ImGuiDir_Right : ImGuiDir_Left;
return (dy > 0.0f) ? ImGuiDir_Down : ImGuiDir_Up;
}
static float inline NavScoreItemDistInterval(float a0, float a1, float b0, float b1)
{
if (a1 < b0)
return a1 - b0;
if (b1 < a0)
return a0 - b1;
return 0.0f;
}
static void inline NavClampRectToVisibleAreaForMoveDir(ImGuiDir move_dir, ImRect& r, const ImRect& clip_rect)
{
if (move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right)
{
r.Min.y = ImClamp(r.Min.y, clip_rect.Min.y, clip_rect.Max.y);
r.Max.y = ImClamp(r.Max.y, clip_rect.Min.y, clip_rect.Max.y);
}
else
{
r.Min.x = ImClamp(r.Min.x, clip_rect.Min.x, clip_rect.Max.x);
r.Max.x = ImClamp(r.Max.x, clip_rect.Min.x, clip_rect.Max.x);
}
}
// Scoring function for directional navigation. Based on https://gist.github.com/rygorous/6981057
static bool ImGui::NavScoreItem(ImGuiNavMoveResult* result, ImRect cand)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (g.NavLayer != window->DC.NavLayerCurrent)
return false;
const ImRect& curr = g.NavScoringRectScreen; // Current modified source rect (NB: we've applied Max.x = Min.x in NavUpdate() to inhibit the effect of having varied item width)
g.NavScoringCount++;
// When entering through a NavFlattened border, we consider child window items as fully clipped for scoring
if (window->ParentWindow == g.NavWindow)
{
IM_ASSERT((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened);
if (!window->ClipRect.Overlaps(cand))
return false;
cand.ClipWithFull(window->ClipRect); // This allows the scored item to not overlap other candidates in the parent window
}
// We perform scoring on items bounding box clipped by the current clipping rectangle on the other axis (clipping on our movement axis would give us equal scores for all clipped items)
// For example, this ensure that items in one column are not reached when moving vertically from items in another column.
NavClampRectToVisibleAreaForMoveDir(g.NavMoveClipDir, cand, window->ClipRect);
// Compute distance between boxes
// FIXME-NAV: Introducing biases for vertical navigation, needs to be removed.
float dbx = NavScoreItemDistInterval(cand.Min.x, cand.Max.x, curr.Min.x, curr.Max.x);
float dby = NavScoreItemDistInterval(ImLerp(cand.Min.y, cand.Max.y, 0.2f), ImLerp(cand.Min.y, cand.Max.y, 0.8f), ImLerp(curr.Min.y, curr.Max.y, 0.2f), ImLerp(curr.Min.y, curr.Max.y, 0.8f)); // Scale down on Y to keep using box-distance for vertically touching items
if (dby != 0.0f && dbx != 0.0f)
dbx = (dbx/1000.0f) + ((dbx > 0.0f) ? +1.0f : -1.0f);
float dist_box = ImFabs(dbx) + ImFabs(dby);
// Compute distance between centers (this is off by a factor of 2, but we only compare center distances with each other so it doesn't matter)
float dcx = (cand.Min.x + cand.Max.x) - (curr.Min.x + curr.Max.x);
float dcy = (cand.Min.y + cand.Max.y) - (curr.Min.y + curr.Max.y);
float dist_center = ImFabs(dcx) + ImFabs(dcy); // L1 metric (need this for our connectedness guarantee)
// Determine which quadrant of 'curr' our candidate item 'cand' lies in based on distance
ImGuiDir quadrant;
float dax = 0.0f, day = 0.0f, dist_axial = 0.0f;
if (dbx != 0.0f || dby != 0.0f)
{
// For non-overlapping boxes, use distance between boxes
dax = dbx;
day = dby;
dist_axial = dist_box;
quadrant = ImGetDirQuadrantFromDelta(dbx, dby);
}
else if (dcx != 0.0f || dcy != 0.0f)
{
// For overlapping boxes with different centers, use distance between centers
dax = dcx;
day = dcy;
dist_axial = dist_center;
quadrant = ImGetDirQuadrantFromDelta(dcx, dcy);
}
else
{
// Degenerate case: two overlapping buttons with same center, break ties arbitrarily (note that LastItemId here is really the _previous_ item order, but it doesn't matter)
quadrant = (window->DC.LastItemId < g.NavId) ? ImGuiDir_Left : ImGuiDir_Right;
}
#if IMGUI_DEBUG_NAV_SCORING
char buf[128];
if (IsMouseHoveringRect(cand.Min, cand.Max))
{
ImFormatString(buf, IM_ARRAYSIZE(buf), "dbox (%.2f,%.2f->%.4f)\ndcen (%.2f,%.2f->%.4f)\nd (%.2f,%.2f->%.4f)\nnav %c, quadrant %c", dbx, dby, dist_box, dcx, dcy, dist_center, dax, day, dist_axial, "WENS"[g.NavMoveDir], "WENS"[quadrant]);
ImDrawList* draw_list = GetForegroundDrawList(window);
draw_list->AddRect(curr.Min, curr.Max, IM_COL32(255,200,0,100));
draw_list->AddRect(cand.Min, cand.Max, IM_COL32(255,255,0,200));
draw_list->AddRectFilled(cand.Max - ImVec2(4,4), cand.Max + CalcTextSize(buf) + ImVec2(4,4), IM_COL32(40,0,0,150));
draw_list->AddText(g.IO.FontDefault, 13.0f, cand.Max, ~0U, buf);
}
else if (g.IO.KeyCtrl) // Hold to preview score in matching quadrant. Press C to rotate.
{
if (IsKeyPressedMap(ImGuiKey_C)) { g.NavMoveDirLast = (ImGuiDir)((g.NavMoveDirLast + 1) & 3); g.IO.KeysDownDuration[g.IO.KeyMap[ImGuiKey_C]] = 0.01f; }
if (quadrant == g.NavMoveDir)
{
ImFormatString(buf, IM_ARRAYSIZE(buf), "%.0f/%.0f", dist_box, dist_center);
ImDrawList* draw_list = GetForegroundDrawList(window);
draw_list->AddRectFilled(cand.Min, cand.Max, IM_COL32(255, 0, 0, 200));
draw_list->AddText(g.IO.FontDefault, 13.0f, cand.Min, IM_COL32(255, 255, 255, 255), buf);
}
}
#endif
// Is it in the quadrant we're interesting in moving to?
bool new_best = false;
if (quadrant == g.NavMoveDir)
{
// Does it beat the current best candidate?
if (dist_box < result->DistBox)
{
result->DistBox = dist_box;
result->DistCenter = dist_center;
return true;
}
if (dist_box == result->DistBox)
{
// Try using distance between center points to break ties
if (dist_center < result->DistCenter)
{
result->DistCenter = dist_center;
new_best = true;
}
else if (dist_center == result->DistCenter)
{
// Still tied! we need to be extra-careful to make sure everything gets linked properly. We consistently break ties by symbolically moving "later" items
// (with higher index) to the right/downwards by an infinitesimal amount since we the current "best" button already (so it must have a lower index),
// this is fairly easy. This rule ensures that all buttons with dx==dy==0 will end up being linked in order of appearance along the x axis.
if (((g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) ? dby : dbx) < 0.0f) // moving bj to the right/down decreases distance
new_best = true;
}
}
}
// Axial check: if 'curr' has no link at all in some direction and 'cand' lies roughly in that direction, add a tentative link. This will only be kept if no "real" matches
// are found, so it only augments the graph produced by the above method using extra links. (important, since it doesn't guarantee strong connectedness)
// This is just to avoid buttons having no links in a particular direction when there's a suitable neighbor. you get good graphs without this too.
// 2017/09/29: FIXME: This now currently only enabled inside menu bars, ideally we'd disable it everywhere. Menus in particular need to catch failure. For general navigation it feels awkward.
// Disabling it may lead to disconnected graphs when nodes are very spaced out on different axis. Perhaps consider offering this as an option?
if (result->DistBox == FLT_MAX && dist_axial < result->DistAxial) // Check axial match
if (g.NavLayer == 1 && !(g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu))
if ((g.NavMoveDir == ImGuiDir_Left && dax < 0.0f) || (g.NavMoveDir == ImGuiDir_Right && dax > 0.0f) || (g.NavMoveDir == ImGuiDir_Up && day < 0.0f) || (g.NavMoveDir == ImGuiDir_Down && day > 0.0f))
{
result->DistAxial = dist_axial;
new_best = true;
}
return new_best;
}
// We get there when either NavId == id, or when g.NavAnyRequest is set (which is updated by NavUpdateAnyRequestFlag above)
static void ImGui::NavProcessItem(ImGuiWindow* window, const ImRect& nav_bb, const ImGuiID id)
{
ImGuiContext& g = *GImGui;
//if (!g.IO.NavActive) // [2017/10/06] Removed this possibly redundant test but I am not sure of all the side-effects yet. Some of the feature here will need to work regardless of using a _NoNavInputs flag.
// return;
const ImGuiItemFlags item_flags = window->DC.ItemFlags;
const ImRect nav_bb_rel(nav_bb.Min - window->Pos, nav_bb.Max - window->Pos);
// Process Init Request
if (g.NavInitRequest && g.NavLayer == window->DC.NavLayerCurrent)
{
// Even if 'ImGuiItemFlags_NoNavDefaultFocus' is on (typically collapse/close button) we record the first ResultId so they can be used as a fallback
if (!(item_flags & ImGuiItemFlags_NoNavDefaultFocus) || g.NavInitResultId == 0)
{
g.NavInitResultId = id;
g.NavInitResultRectRel = nav_bb_rel;
}
if (!(item_flags & ImGuiItemFlags_NoNavDefaultFocus))
{
g.NavInitRequest = false; // Found a match, clear request
NavUpdateAnyRequestFlag();
}
}
// Process Move Request (scoring for navigation)
// FIXME-NAV: Consider policy for double scoring (scoring from NavScoringRectScreen + scoring from a rect wrapped according to current wrapping policy)
if ((g.NavId != id || (g.NavMoveRequestFlags & ImGuiNavMoveFlags_AllowCurrentNavId)) && !(item_flags & (ImGuiItemFlags_Disabled|ImGuiItemFlags_NoNav)))
{
ImGuiNavMoveResult* result = (window == g.NavWindow) ? &g.NavMoveResultLocal : &g.NavMoveResultOther;
#if IMGUI_DEBUG_NAV_SCORING
// [DEBUG] Score all items in NavWindow at all times
if (!g.NavMoveRequest)
g.NavMoveDir = g.NavMoveDirLast;
bool new_best = NavScoreItem(result, nav_bb) && g.NavMoveRequest;
#else
bool new_best = g.NavMoveRequest && NavScoreItem(result, nav_bb);
#endif
if (new_best)
{
result->Window = window;
result->ID = id;
result->FocusScopeId = window->DC.NavFocusScopeIdCurrent;
result->RectRel = nav_bb_rel;
}
// Features like PageUp/PageDown need to maintain a separate score for the visible set of items.
const float VISIBLE_RATIO = 0.70f;
if ((g.NavMoveRequestFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet) && window->ClipRect.Overlaps(nav_bb))
if (ImClamp(nav_bb.Max.y, window->ClipRect.Min.y, window->ClipRect.Max.y) - ImClamp(nav_bb.Min.y, window->ClipRect.Min.y, window->ClipRect.Max.y) >= (nav_bb.Max.y - nav_bb.Min.y) * VISIBLE_RATIO)
if (NavScoreItem(&g.NavMoveResultLocalVisibleSet, nav_bb))
{
result = &g.NavMoveResultLocalVisibleSet;
result->Window = window;
result->ID = id;
result->FocusScopeId = window->DC.NavFocusScopeIdCurrent;
result->RectRel = nav_bb_rel;
}
}
// Update window-relative bounding box of navigated item
if (g.NavId == id)
{
g.NavWindow = window; // Always refresh g.NavWindow, because some operations such as FocusItem() don't have a window.
g.NavLayer = window->DC.NavLayerCurrent;
g.NavFocusScopeId = window->DC.NavFocusScopeIdCurrent;
g.NavIdIsAlive = true;
g.NavIdTabCounter = window->DC.FocusCounterTabStop;
window->NavRectRel[window->DC.NavLayerCurrent] = nav_bb_rel; // Store item bounding box (relative to window position)
}
}
bool ImGui::NavMoveRequestButNoResultYet()
{
ImGuiContext& g = *GImGui;
return g.NavMoveRequest && g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0;
}
void ImGui::NavMoveRequestCancel()
{
ImGuiContext& g = *GImGui;
g.NavMoveRequest = false;
NavUpdateAnyRequestFlag();
}
void ImGui::NavMoveRequestForward(ImGuiDir move_dir, ImGuiDir clip_dir, const ImRect& bb_rel, ImGuiNavMoveFlags move_flags)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.NavMoveRequestForward == ImGuiNavForward_None);
NavMoveRequestCancel();
g.NavMoveDir = move_dir;
g.NavMoveClipDir = clip_dir;
g.NavMoveRequestForward = ImGuiNavForward_ForwardQueued;
g.NavMoveRequestFlags = move_flags;
g.NavWindow->NavRectRel[g.NavLayer] = bb_rel;
}
void ImGui::NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags move_flags)
{
ImGuiContext& g = *GImGui;
if (g.NavWindow != window || !NavMoveRequestButNoResultYet() || g.NavMoveRequestForward != ImGuiNavForward_None || g.NavLayer != 0)
return;
IM_ASSERT(move_flags != 0); // No points calling this with no wrapping
ImRect bb_rel = window->NavRectRel[0];
ImGuiDir clip_dir = g.NavMoveDir;
if (g.NavMoveDir == ImGuiDir_Left && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
{
bb_rel.Min.x = bb_rel.Max.x = ImMax(window->SizeFull.x, window->ContentSize.x + window->WindowPadding.x * 2.0f) - window->Scroll.x;
if (move_flags & ImGuiNavMoveFlags_WrapX) { bb_rel.TranslateY(-bb_rel.GetHeight()); clip_dir = ImGuiDir_Up; }
NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags);
}
if (g.NavMoveDir == ImGuiDir_Right && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
{
bb_rel.Min.x = bb_rel.Max.x = -window->Scroll.x;
if (move_flags & ImGuiNavMoveFlags_WrapX) { bb_rel.TranslateY(+bb_rel.GetHeight()); clip_dir = ImGuiDir_Down; }
NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags);
}
if (g.NavMoveDir == ImGuiDir_Up && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
{
bb_rel.Min.y = bb_rel.Max.y = ImMax(window->SizeFull.y, window->ContentSize.y + window->WindowPadding.y * 2.0f) - window->Scroll.y;
if (move_flags & ImGuiNavMoveFlags_WrapY) { bb_rel.TranslateX(-bb_rel.GetWidth()); clip_dir = ImGuiDir_Left; }
NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags);
}
if (g.NavMoveDir == ImGuiDir_Down && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
{
bb_rel.Min.y = bb_rel.Max.y = -window->Scroll.y;
if (move_flags & ImGuiNavMoveFlags_WrapY) { bb_rel.TranslateX(+bb_rel.GetWidth()); clip_dir = ImGuiDir_Right; }
NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags);
}
}
// FIXME: This could be replaced by updating a frame number in each window when (window == NavWindow) and (NavLayer == 0).
// This way we could find the last focused window among our children. It would be much less confusing this way?
static void ImGui::NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window)
{
ImGuiWindow* parent_window = nav_window;
while (parent_window && (parent_window->Flags & ImGuiWindowFlags_ChildWindow) != 0 && (parent_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
parent_window = parent_window->ParentWindow;
if (parent_window && parent_window != nav_window)
parent_window->NavLastChildNavWindow = nav_window;
}
// Restore the last focused child.
// Call when we are expected to land on the Main Layer (0) after FocusWindow()
static ImGuiWindow* ImGui::NavRestoreLastChildNavWindow(ImGuiWindow* window)
{
return window->NavLastChildNavWindow ? window->NavLastChildNavWindow : window;
}
static void NavRestoreLayer(ImGuiNavLayer layer)
{
ImGuiContext& g = *GImGui;
g.NavLayer = layer;
if (layer == 0)
g.NavWindow = ImGui::NavRestoreLastChildNavWindow(g.NavWindow);
ImGuiWindow* window = g.NavWindow;
if (layer == 0 && window->NavLastIds[0] != 0)
ImGui::SetNavIDWithRectRel(window->NavLastIds[0], layer, 0, window->NavRectRel[0]);
else
ImGui::NavInitWindow(window, true);
}
static inline void ImGui::NavUpdateAnyRequestFlag()
{
ImGuiContext& g = *GImGui;
g.NavAnyRequest = g.NavMoveRequest || g.NavInitRequest || (IMGUI_DEBUG_NAV_SCORING && g.NavWindow != NULL);
if (g.NavAnyRequest)
IM_ASSERT(g.NavWindow != NULL);
}
// This needs to be called before we submit any widget (aka in or before Begin)
void ImGui::NavInitWindow(ImGuiWindow* window, bool force_reinit)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(window == g.NavWindow);
bool init_for_nav = false;
if (!(window->Flags & ImGuiWindowFlags_NoNavInputs))
if (!(window->Flags & ImGuiWindowFlags_ChildWindow) || (window->Flags & ImGuiWindowFlags_Popup) || (window->NavLastIds[0] == 0) || force_reinit)
init_for_nav = true;
//IMGUI_DEBUG_LOG("[Nav] NavInitWindow() init_for_nav=%d, window=\"%s\", layer=%d\n", init_for_nav, window->Name, g.NavLayer);
if (init_for_nav)
{
SetNavID(0, g.NavLayer, 0);
g.NavInitRequest = true;
g.NavInitRequestFromMove = false;
g.NavInitResultId = 0;
g.NavInitResultRectRel = ImRect();
NavUpdateAnyRequestFlag();
}
else
{
g.NavId = window->NavLastIds[0];
g.NavFocusScopeId = 0;
}
}
static ImVec2 ImGui::NavCalcPreferredRefPos()
{
ImGuiContext& g = *GImGui;
if (g.NavDisableHighlight || !g.NavDisableMouseHover || !g.NavWindow)
{
// Mouse (we need a fallback in case the mouse becomes invalid after being used)
if (IsMousePosValid(&g.IO.MousePos))
return g.IO.MousePos;
return g.LastValidMousePos;
}
else
{
// When navigation is active and mouse is disabled, decide on an arbitrary position around the bottom left of the currently navigated item.
const ImRect& rect_rel = g.NavWindow->NavRectRel[g.NavLayer];
ImVec2 pos = g.NavWindow->Pos + ImVec2(rect_rel.Min.x + ImMin(g.Style.FramePadding.x * 4, rect_rel.GetWidth()), rect_rel.Max.y - ImMin(g.Style.FramePadding.y, rect_rel.GetHeight()));
ImRect visible_rect = GetViewportRect();
return ImFloor(ImClamp(pos, visible_rect.Min, visible_rect.Max)); // ImFloor() is important because non-integer mouse position application in back-end might be lossy and result in undesirable non-zero delta.
}
}
float ImGui::GetNavInputAmount(ImGuiNavInput n, ImGuiInputReadMode mode)
{
ImGuiContext& g = *GImGui;
if (mode == ImGuiInputReadMode_Down)
return g.IO.NavInputs[n]; // Instant, read analog input (0.0f..1.0f, as provided by user)
const float t = g.IO.NavInputsDownDuration[n];
if (t < 0.0f && mode == ImGuiInputReadMode_Released) // Return 1.0f when just released, no repeat, ignore analog input.
return (g.IO.NavInputsDownDurationPrev[n] >= 0.0f ? 1.0f : 0.0f);
if (t < 0.0f)
return 0.0f;
if (mode == ImGuiInputReadMode_Pressed) // Return 1.0f when just pressed, no repeat, ignore analog input.
return (t == 0.0f) ? 1.0f : 0.0f;
if (mode == ImGuiInputReadMode_Repeat)
return (float)CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay * 0.72f, g.IO.KeyRepeatRate * 0.80f);
if (mode == ImGuiInputReadMode_RepeatSlow)
return (float)CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay * 1.25f, g.IO.KeyRepeatRate * 2.00f);
if (mode == ImGuiInputReadMode_RepeatFast)
return (float)CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay * 0.72f, g.IO.KeyRepeatRate * 0.30f);
return 0.0f;
}
ImVec2 ImGui::GetNavInputAmount2d(ImGuiNavDirSourceFlags dir_sources, ImGuiInputReadMode mode, float slow_factor, float fast_factor)
{
ImVec2 delta(0.0f, 0.0f);
if (dir_sources & ImGuiNavDirSourceFlags_Keyboard)
delta += ImVec2(GetNavInputAmount(ImGuiNavInput_KeyRight_, mode) - GetNavInputAmount(ImGuiNavInput_KeyLeft_, mode), GetNavInputAmount(ImGuiNavInput_KeyDown_, mode) - GetNavInputAmount(ImGuiNavInput_KeyUp_, mode));
if (dir_sources & ImGuiNavDirSourceFlags_PadDPad)
delta += ImVec2(GetNavInputAmount(ImGuiNavInput_DpadRight, mode) - GetNavInputAmount(ImGuiNavInput_DpadLeft, mode), GetNavInputAmount(ImGuiNavInput_DpadDown, mode) - GetNavInputAmount(ImGuiNavInput_DpadUp, mode));
if (dir_sources & ImGuiNavDirSourceFlags_PadLStick)
delta += ImVec2(GetNavInputAmount(ImGuiNavInput_LStickRight, mode) - GetNavInputAmount(ImGuiNavInput_LStickLeft, mode), GetNavInputAmount(ImGuiNavInput_LStickDown, mode) - GetNavInputAmount(ImGuiNavInput_LStickUp, mode));
if (slow_factor != 0.0f && IsNavInputDown(ImGuiNavInput_TweakSlow))
delta *= slow_factor;
if (fast_factor != 0.0f && IsNavInputDown(ImGuiNavInput_TweakFast))
delta *= fast_factor;
return delta;
}
static void ImGui::NavUpdate()
{
ImGuiContext& g = *GImGui;
g.IO.WantSetMousePos = false;
#if 0
if (g.NavScoringCount > 0) IMGUI_DEBUG_LOG("NavScoringCount %d for '%s' layer %d (Init:%d, Move:%d)\n", g.FrameCount, g.NavScoringCount, g.NavWindow ? g.NavWindow->Name : "NULL", g.NavLayer, g.NavInitRequest || g.NavInitResultId != 0, g.NavMoveRequest);
#endif
// Set input source as Gamepad when buttons are pressed (as some features differs when used with Gamepad vs Keyboard)
// (do it before we map Keyboard input!)
bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
bool nav_gamepad_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (g.IO.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
if (nav_gamepad_active)
if (g.IO.NavInputs[ImGuiNavInput_Activate] > 0.0f || g.IO.NavInputs[ImGuiNavInput_Input] > 0.0f || g.IO.NavInputs[ImGuiNavInput_Cancel] > 0.0f || g.IO.NavInputs[ImGuiNavInput_Menu] > 0.0f)
g.NavInputSource = ImGuiInputSource_NavGamepad;
// Update Keyboard->Nav inputs mapping
if (nav_keyboard_active)
{
#define NAV_MAP_KEY(_KEY, _NAV_INPUT) do { if (IsKeyDown(g.IO.KeyMap[_KEY])) { g.IO.NavInputs[_NAV_INPUT] = 1.0f; g.NavInputSource = ImGuiInputSource_NavKeyboard; } } while (0)
NAV_MAP_KEY(ImGuiKey_Space, ImGuiNavInput_Activate );
NAV_MAP_KEY(ImGuiKey_Enter, ImGuiNavInput_Input );
NAV_MAP_KEY(ImGuiKey_Escape, ImGuiNavInput_Cancel );
NAV_MAP_KEY(ImGuiKey_LeftArrow, ImGuiNavInput_KeyLeft_ );
NAV_MAP_KEY(ImGuiKey_RightArrow,ImGuiNavInput_KeyRight_);
NAV_MAP_KEY(ImGuiKey_UpArrow, ImGuiNavInput_KeyUp_ );
NAV_MAP_KEY(ImGuiKey_DownArrow, ImGuiNavInput_KeyDown_ );
if (g.IO.KeyCtrl)
g.IO.NavInputs[ImGuiNavInput_TweakSlow] = 1.0f;
if (g.IO.KeyShift)
g.IO.NavInputs[ImGuiNavInput_TweakFast] = 1.0f;
if (g.IO.KeyAlt && !g.IO.KeyCtrl) // AltGR is Alt+Ctrl, also even on keyboards without AltGR we don't want Alt+Ctrl to open menu.
g.IO.NavInputs[ImGuiNavInput_KeyMenu_] = 1.0f;
#undef NAV_MAP_KEY
}
memcpy(g.IO.NavInputsDownDurationPrev, g.IO.NavInputsDownDuration, sizeof(g.IO.NavInputsDownDuration));
for (int i = 0; i < IM_ARRAYSIZE(g.IO.NavInputs); i++)
g.IO.NavInputsDownDuration[i] = (g.IO.NavInputs[i] > 0.0f) ? (g.IO.NavInputsDownDuration[i] < 0.0f ? 0.0f : g.IO.NavInputsDownDuration[i] + g.IO.DeltaTime) : -1.0f;
// Process navigation init request (select first/default focus)
// In very rare cases g.NavWindow may be null (e.g. clearing focus after requesting an init request, which does happen when releasing Alt while clicking on void)
if (g.NavInitResultId != 0 && (!g.NavDisableHighlight || g.NavInitRequestFromMove) && g.NavWindow)
{
// Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called)
//IMGUI_DEBUG_LOG("[Nav] Apply NavInitRequest result: 0x%08X Layer %d in \"%s\"\n", g.NavInitResultId, g.NavLayer, g.NavWindow->Name);
if (g.NavInitRequestFromMove)
SetNavIDWithRectRel(g.NavInitResultId, g.NavLayer, 0, g.NavInitResultRectRel);
else
SetNavID(g.NavInitResultId, g.NavLayer, 0);
g.NavWindow->NavRectRel[g.NavLayer] = g.NavInitResultRectRel;
}
g.NavInitRequest = false;
g.NavInitRequestFromMove = false;
g.NavInitResultId = 0;
g.NavJustMovedToId = 0;
// Process navigation move request
if (g.NavMoveRequest)
NavUpdateMoveResult();
// When a forwarded move request failed, we restore the highlight that we disabled during the forward frame
if (g.NavMoveRequestForward == ImGuiNavForward_ForwardActive)
{
IM_ASSERT(g.NavMoveRequest);
if (g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0)
g.NavDisableHighlight = false;
g.NavMoveRequestForward = ImGuiNavForward_None;
}
// Apply application mouse position movement, after we had a chance to process move request result.
if (g.NavMousePosDirty && g.NavIdIsAlive)
{
// Set mouse position given our knowledge of the navigated item position from last frame
if ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos) && (g.IO.BackendFlags & ImGuiBackendFlags_HasSetMousePos))
{
if (!g.NavDisableHighlight && g.NavDisableMouseHover && g.NavWindow)
{
g.IO.MousePos = g.IO.MousePosPrev = NavCalcPreferredRefPos();
g.IO.WantSetMousePos = true;
}
}
g.NavMousePosDirty = false;
}
g.NavIdIsAlive = false;
g.NavJustTabbedId = 0;
IM_ASSERT(g.NavLayer == 0 || g.NavLayer == 1);
// Store our return window (for returning from Layer 1 to Layer 0) and clear it as soon as we step back in our own Layer 0
if (g.NavWindow)
NavSaveLastChildNavWindowIntoParent(g.NavWindow);
if (g.NavWindow && g.NavWindow->NavLastChildNavWindow != NULL && g.NavLayer == 0)
g.NavWindow->NavLastChildNavWindow = NULL;
// Update CTRL+TAB and Windowing features (hold Square to move/resize/etc.)
NavUpdateWindowing();
// Set output flags for user application
g.IO.NavActive = (nav_keyboard_active || nav_gamepad_active) && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs);
g.IO.NavVisible = (g.IO.NavActive && g.NavId != 0 && !g.NavDisableHighlight) || (g.NavWindowingTarget != NULL);
// Process NavCancel input (to close a popup, get back to parent, clear focus)
if (IsNavInputTest(ImGuiNavInput_Cancel, ImGuiInputReadMode_Pressed))
{
if (g.ActiveId != 0)
{
if (!IsActiveIdUsingNavInput(ImGuiNavInput_Cancel))
ClearActiveID();
}
else if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow) && !(g.NavWindow->Flags & ImGuiWindowFlags_Popup) && g.NavWindow->ParentWindow)
{
// Exit child window
ImGuiWindow* child_window = g.NavWindow;
ImGuiWindow* parent_window = g.NavWindow->ParentWindow;
IM_ASSERT(child_window->ChildId != 0);
FocusWindow(parent_window);
SetNavID(child_window->ChildId, 0, 0);
// Reassigning with same value, we're being explicit here.
g.NavIdIsAlive = false; // -V1048
if (g.NavDisableMouseHover)
g.NavMousePosDirty = true;
}
else if (g.OpenPopupStack.Size > 0)
{
// Close open popup/menu
if (!(g.OpenPopupStack.back().Window->Flags & ImGuiWindowFlags_Modal))
ClosePopupToLevel(g.OpenPopupStack.Size - 1, true);
}
else if (g.NavLayer != 0)
{
// Leave the "menu" layer
NavRestoreLayer(ImGuiNavLayer_Main);
}
else
{
// Clear NavLastId for popups but keep it for regular child window so we can leave one and come back where we were
if (g.NavWindow && ((g.NavWindow->Flags & ImGuiWindowFlags_Popup) || !(g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow)))
g.NavWindow->NavLastIds[0] = 0;
g.NavId = g.NavFocusScopeId = 0;
}
}
// Process manual activation request
g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavInputId = 0;
if (g.NavId != 0 && !g.NavDisableHighlight && !g.NavWindowingTarget && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
{
bool activate_down = IsNavInputDown(ImGuiNavInput_Activate);
bool activate_pressed = activate_down && IsNavInputTest(ImGuiNavInput_Activate, ImGuiInputReadMode_Pressed);
if (g.ActiveId == 0 && activate_pressed)
g.NavActivateId = g.NavId;
if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && activate_down)
g.NavActivateDownId = g.NavId;
if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && activate_pressed)
g.NavActivatePressedId = g.NavId;
if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && IsNavInputTest(ImGuiNavInput_Input, ImGuiInputReadMode_Pressed))
g.NavInputId = g.NavId;
}
if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
g.NavDisableHighlight = true;
if (g.NavActivateId != 0)
IM_ASSERT(g.NavActivateDownId == g.NavActivateId);
g.NavMoveRequest = false;
// Process programmatic activation request
if (g.NavNextActivateId != 0)
g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavInputId = g.NavNextActivateId;
g.NavNextActivateId = 0;
// Initiate directional inputs request
if (g.NavMoveRequestForward == ImGuiNavForward_None)
{
g.NavMoveDir = ImGuiDir_None;
g.NavMoveRequestFlags = ImGuiNavMoveFlags_None;
if (g.NavWindow && !g.NavWindowingTarget && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
{
const ImGuiInputReadMode read_mode = ImGuiInputReadMode_Repeat;
if (!IsActiveIdUsingNavDir(ImGuiDir_Left) && (IsNavInputTest(ImGuiNavInput_DpadLeft, read_mode) || IsNavInputTest(ImGuiNavInput_KeyLeft_, read_mode))) { g.NavMoveDir = ImGuiDir_Left; }
if (!IsActiveIdUsingNavDir(ImGuiDir_Right) && (IsNavInputTest(ImGuiNavInput_DpadRight, read_mode) || IsNavInputTest(ImGuiNavInput_KeyRight_, read_mode))) { g.NavMoveDir = ImGuiDir_Right; }
if (!IsActiveIdUsingNavDir(ImGuiDir_Up) && (IsNavInputTest(ImGuiNavInput_DpadUp, read_mode) || IsNavInputTest(ImGuiNavInput_KeyUp_, read_mode))) { g.NavMoveDir = ImGuiDir_Up; }
if (!IsActiveIdUsingNavDir(ImGuiDir_Down) && (IsNavInputTest(ImGuiNavInput_DpadDown, read_mode) || IsNavInputTest(ImGuiNavInput_KeyDown_, read_mode))) { g.NavMoveDir = ImGuiDir_Down; }
}
g.NavMoveClipDir = g.NavMoveDir;
}
else
{
// Forwarding previous request (which has been modified, e.g. wrap around menus rewrite the requests with a starting rectangle at the other side of the window)
// (Preserve g.NavMoveRequestFlags, g.NavMoveClipDir which were set by the NavMoveRequestForward() function)
IM_ASSERT(g.NavMoveDir != ImGuiDir_None && g.NavMoveClipDir != ImGuiDir_None);
IM_ASSERT(g.NavMoveRequestForward == ImGuiNavForward_ForwardQueued);
g.NavMoveRequestForward = ImGuiNavForward_ForwardActive;
}
// Update PageUp/PageDown/Home/End scroll
// FIXME-NAV: Consider enabling those keys even without the master ImGuiConfigFlags_NavEnableKeyboard flag?
float nav_scoring_rect_offset_y = 0.0f;
if (nav_keyboard_active)
nav_scoring_rect_offset_y = NavUpdatePageUpPageDown();
// If we initiate a movement request and have no current NavId, we initiate a InitDefautRequest that will be used as a fallback if the direction fails to find a match
if (g.NavMoveDir != ImGuiDir_None)
{
g.NavMoveRequest = true;
g.NavMoveDirLast = g.NavMoveDir;
}
if (g.NavMoveRequest && g.NavId == 0)
{
//IMGUI_DEBUG_LOG("[Nav] NavInitRequest from move, window \"%s\", layer=%d\n", g.NavWindow->Name, g.NavLayer);
g.NavInitRequest = g.NavInitRequestFromMove = true;
// Reassigning with same value, we're being explicit here.
g.NavInitResultId = 0; // -V1048
g.NavDisableHighlight = false;
}
NavUpdateAnyRequestFlag();
// Scrolling
if (g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.NavWindowingTarget)
{
// *Fallback* manual-scroll with Nav directional keys when window has no navigable item
ImGuiWindow* window = g.NavWindow;
const float scroll_speed = IM_ROUND(window->CalcFontSize() * 100 * g.IO.DeltaTime); // We need round the scrolling speed because sub-pixel scroll isn't reliably supported.
if (window->DC.NavLayerActiveMask == 0x00 && window->DC.NavHasScroll && g.NavMoveRequest)
{
if (g.NavMoveDir == ImGuiDir_Left || g.NavMoveDir == ImGuiDir_Right)
SetScrollX(window, ImFloor(window->Scroll.x + ((g.NavMoveDir == ImGuiDir_Left) ? -1.0f : +1.0f) * scroll_speed));
if (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down)
SetScrollY(window, ImFloor(window->Scroll.y + ((g.NavMoveDir == ImGuiDir_Up) ? -1.0f : +1.0f) * scroll_speed));
}
// *Normal* Manual scroll with NavScrollXXX keys
// Next movement request will clamp the NavId reference rectangle to the visible area, so navigation will resume within those bounds.
ImVec2 scroll_dir = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadLStick, ImGuiInputReadMode_Down, 1.0f/10.0f, 10.0f);
if (scroll_dir.x != 0.0f && window->ScrollbarX)
{
SetScrollX(window, ImFloor(window->Scroll.x + scroll_dir.x * scroll_speed));
g.NavMoveFromClampedRefRect = true;
}
if (scroll_dir.y != 0.0f)
{
SetScrollY(window, ImFloor(window->Scroll.y + scroll_dir.y * scroll_speed));
g.NavMoveFromClampedRefRect = true;
}
}
// Reset search results
g.NavMoveResultLocal.Clear();
g.NavMoveResultLocalVisibleSet.Clear();
g.NavMoveResultOther.Clear();
// When we have manually scrolled (without using navigation) and NavId becomes out of bounds, we project its bounding box to the visible area to restart navigation within visible items
if (g.NavMoveRequest && g.NavMoveFromClampedRefRect && g.NavLayer == 0)
{
ImGuiWindow* window = g.NavWindow;
ImRect window_rect_rel(window->InnerRect.Min - window->Pos - ImVec2(1,1), window->InnerRect.Max - window->Pos + ImVec2(1,1));
if (!window_rect_rel.Contains(window->NavRectRel[g.NavLayer]))
{
float pad = window->CalcFontSize() * 0.5f;
window_rect_rel.Expand(ImVec2(-ImMin(window_rect_rel.GetWidth(), pad), -ImMin(window_rect_rel.GetHeight(), pad))); // Terrible approximation for the intent of starting navigation from first fully visible item
window->NavRectRel[g.NavLayer].ClipWith(window_rect_rel);
g.NavId = g.NavFocusScopeId = 0;
}
g.NavMoveFromClampedRefRect = false;
}
// For scoring we use a single segment on the left side our current item bounding box (not touching the edge to avoid box overlap with zero-spaced items)
ImRect nav_rect_rel = (g.NavWindow && !g.NavWindow->NavRectRel[g.NavLayer].IsInverted()) ? g.NavWindow->NavRectRel[g.NavLayer] : ImRect(0,0,0,0);
g.NavScoringRectScreen = g.NavWindow ? ImRect(g.NavWindow->Pos + nav_rect_rel.Min, g.NavWindow->Pos + nav_rect_rel.Max) : GetViewportRect();
g.NavScoringRectScreen.TranslateY(nav_scoring_rect_offset_y);
g.NavScoringRectScreen.Min.x = ImMin(g.NavScoringRectScreen.Min.x + 1.0f, g.NavScoringRectScreen.Max.x);
g.NavScoringRectScreen.Max.x = g.NavScoringRectScreen.Min.x;
IM_ASSERT(!g.NavScoringRectScreen.IsInverted()); // Ensure if we have a finite, non-inverted bounding box here will allows us to remove extraneous ImFabs() calls in NavScoreItem().
//GetForegroundDrawList()->AddRect(g.NavScoringRectScreen.Min, g.NavScoringRectScreen.Max, IM_COL32(255,200,0,255)); // [DEBUG]
g.NavScoringCount = 0;
#if IMGUI_DEBUG_NAV_RECTS
if (g.NavWindow)
{
ImDrawList* draw_list = GetForegroundDrawList(g.NavWindow);
if (1) { for (int layer = 0; layer < 2; layer++) draw_list->AddRect(g.NavWindow->Pos + g.NavWindow->NavRectRel[layer].Min, g.NavWindow->Pos + g.NavWindow->NavRectRel[layer].Max, IM_COL32(255,200,0,255)); } // [DEBUG]
if (1) { ImU32 col = (!g.NavWindow->Hidden) ? IM_COL32(255,0,255,255) : IM_COL32(255,0,0,255); ImVec2 p = NavCalcPreferredRefPos(); char buf[32]; ImFormatString(buf, 32, "%d", g.NavLayer); draw_list->AddCircleFilled(p, 3.0f, col); draw_list->AddText(NULL, 13.0f, p + ImVec2(8,-4), col, buf); }
}
#endif
}
// Apply result from previous frame navigation directional move request
static void ImGui::NavUpdateMoveResult()
{
ImGuiContext& g = *GImGui;
if (g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0)
{
// In a situation when there is no results but NavId != 0, re-enable the Navigation highlight (because g.NavId is not considered as a possible result)
if (g.NavId != 0)
{
g.NavDisableHighlight = false;
g.NavDisableMouseHover = true;
}
return;
}
// Select which result to use
ImGuiNavMoveResult* result = (g.NavMoveResultLocal.ID != 0) ? &g.NavMoveResultLocal : &g.NavMoveResultOther;
// PageUp/PageDown behavior first jumps to the bottom/top mostly visible item, _otherwise_ use the result from the previous/next page.
if (g.NavMoveRequestFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet)
if (g.NavMoveResultLocalVisibleSet.ID != 0 && g.NavMoveResultLocalVisibleSet.ID != g.NavId)
result = &g.NavMoveResultLocalVisibleSet;
// Maybe entering a flattened child from the outside? In this case solve the tie using the regular scoring rules.
if (result != &g.NavMoveResultOther && g.NavMoveResultOther.ID != 0 && g.NavMoveResultOther.Window->ParentWindow == g.NavWindow)
if ((g.NavMoveResultOther.DistBox < result->DistBox) || (g.NavMoveResultOther.DistBox == result->DistBox && g.NavMoveResultOther.DistCenter < result->DistCenter))
result = &g.NavMoveResultOther;
IM_ASSERT(g.NavWindow && result->Window);
// Scroll to keep newly navigated item fully into view.
if (g.NavLayer == 0)
{
ImVec2 delta_scroll;
if (g.NavMoveRequestFlags & ImGuiNavMoveFlags_ScrollToEdge)
{
float scroll_target = (g.NavMoveDir == ImGuiDir_Up) ? result->Window->ScrollMax.y : 0.0f;
delta_scroll.y = result->Window->Scroll.y - scroll_target;
SetScrollY(result->Window, scroll_target);
}
else
{
ImRect rect_abs = ImRect(result->RectRel.Min + result->Window->Pos, result->RectRel.Max + result->Window->Pos);
delta_scroll = ScrollToBringRectIntoView(result->Window, rect_abs);
}
// Offset our result position so mouse position can be applied immediately after in NavUpdate()
result->RectRel.TranslateX(-delta_scroll.x);
result->RectRel.TranslateY(-delta_scroll.y);
}
ClearActiveID();
g.NavWindow = result->Window;
if (g.NavId != result->ID)
{
// Don't set NavJustMovedToId if just landed on the same spot (which may happen with ImGuiNavMoveFlags_AllowCurrentNavId)
g.NavJustMovedToId = result->ID;
g.NavJustMovedToFocusScopeId = result->FocusScopeId;
}
SetNavIDWithRectRel(result->ID, g.NavLayer, result->FocusScopeId, result->RectRel);
g.NavMoveFromClampedRefRect = false;
}
// Handle PageUp/PageDown/Home/End keys
static float ImGui::NavUpdatePageUpPageDown()
{
ImGuiContext& g = *GImGui;
if (g.NavMoveDir != ImGuiDir_None || g.NavWindow == NULL)
return 0.0f;
if ((g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) || g.NavWindowingTarget != NULL || g.NavLayer != 0)
return 0.0f;
ImGuiWindow* window = g.NavWindow;
const bool page_up_held = IsKeyDown(g.IO.KeyMap[ImGuiKey_PageUp]) && !IsActiveIdUsingKey(ImGuiKey_PageUp);
const bool page_down_held = IsKeyDown(g.IO.KeyMap[ImGuiKey_PageDown]) && !IsActiveIdUsingKey(ImGuiKey_PageDown);
const bool home_pressed = IsKeyPressed(g.IO.KeyMap[ImGuiKey_Home]) && !IsActiveIdUsingKey(ImGuiKey_Home);
const bool end_pressed = IsKeyPressed(g.IO.KeyMap[ImGuiKey_End]) && !IsActiveIdUsingKey(ImGuiKey_End);
if (page_up_held != page_down_held || home_pressed != end_pressed) // If either (not both) are pressed
{
if (window->DC.NavLayerActiveMask == 0x00 && window->DC.NavHasScroll)
{
// Fallback manual-scroll when window has no navigable item
if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageUp], true))
SetScrollY(window, window->Scroll.y - window->InnerRect.GetHeight());
else if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageDown], true))
SetScrollY(window, window->Scroll.y + window->InnerRect.GetHeight());
else if (home_pressed)
SetScrollY(window, 0.0f);
else if (end_pressed)
SetScrollY(window, window->ScrollMax.y);
}
else
{
ImRect& nav_rect_rel = window->NavRectRel[g.NavLayer];
const float page_offset_y = ImMax(0.0f, window->InnerRect.GetHeight() - window->CalcFontSize() * 1.0f + nav_rect_rel.GetHeight());
float nav_scoring_rect_offset_y = 0.0f;
if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageUp], true))
{
nav_scoring_rect_offset_y = -page_offset_y;
g.NavMoveDir = ImGuiDir_Down; // Because our scoring rect is offset up, we request the down direction (so we can always land on the last item)
g.NavMoveClipDir = ImGuiDir_Up;
g.NavMoveRequestFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet;
}
else if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageDown], true))
{
nav_scoring_rect_offset_y = +page_offset_y;
g.NavMoveDir = ImGuiDir_Up; // Because our scoring rect is offset down, we request the up direction (so we can always land on the last item)
g.NavMoveClipDir = ImGuiDir_Down;
g.NavMoveRequestFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet;
}
else if (home_pressed)
{
// FIXME-NAV: handling of Home/End is assuming that the top/bottom most item will be visible with Scroll.y == 0/ScrollMax.y
// Scrolling will be handled via the ImGuiNavMoveFlags_ScrollToEdge flag, we don't scroll immediately to avoid scrolling happening before nav result.
// Preserve current horizontal position if we have any.
nav_rect_rel.Min.y = nav_rect_rel.Max.y = -window->Scroll.y;
if (nav_rect_rel.IsInverted())
nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
g.NavMoveDir = ImGuiDir_Down;
g.NavMoveRequestFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdge;
}
else if (end_pressed)
{
nav_rect_rel.Min.y = nav_rect_rel.Max.y = window->ScrollMax.y + window->SizeFull.y - window->Scroll.y;
if (nav_rect_rel.IsInverted())
nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
g.NavMoveDir = ImGuiDir_Up;
g.NavMoveRequestFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdge;
}
return nav_scoring_rect_offset_y;
}
}
return 0.0f;
}
static int ImGui::FindWindowFocusIndex(ImGuiWindow* window) // FIXME-OPT O(N)
{
ImGuiContext& g = *GImGui;
for (int i = g.WindowsFocusOrder.Size-1; i >= 0; i--)
if (g.WindowsFocusOrder[i] == window)
return i;
return -1;
}
static ImGuiWindow* FindWindowNavFocusable(int i_start, int i_stop, int dir) // FIXME-OPT O(N)
{
ImGuiContext& g = *GImGui;
for (int i = i_start; i >= 0 && i < g.WindowsFocusOrder.Size && i != i_stop; i += dir)
if (ImGui::IsWindowNavFocusable(g.WindowsFocusOrder[i]))
return g.WindowsFocusOrder[i];
return NULL;
}
static void NavUpdateWindowingHighlightWindow(int focus_change_dir)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.NavWindowingTarget);
if (g.NavWindowingTarget->Flags & ImGuiWindowFlags_Modal)
return;
const int i_current = ImGui::FindWindowFocusIndex(g.NavWindowingTarget);
ImGuiWindow* window_target = FindWindowNavFocusable(i_current + focus_change_dir, -INT_MAX, focus_change_dir);
if (!window_target)
window_target = FindWindowNavFocusable((focus_change_dir < 0) ? (g.WindowsFocusOrder.Size - 1) : 0, i_current, focus_change_dir);
if (window_target) // Don't reset windowing target if there's a single window in the list
g.NavWindowingTarget = g.NavWindowingTargetAnim = window_target;
g.NavWindowingToggleLayer = false;
}
// Windowing management mode
// Keyboard: CTRL+Tab (change focus/move/resize), Alt (toggle menu layer)
// Gamepad: Hold Menu/Square (change focus/move/resize), Tap Menu/Square (toggle menu layer)
static void ImGui::NavUpdateWindowing()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* apply_focus_window = NULL;
bool apply_toggle_layer = false;
ImGuiWindow* modal_window = GetTopMostPopupModal();
if (modal_window != NULL)
{
g.NavWindowingTarget = NULL;
return;
}
// Fade out
if (g.NavWindowingTargetAnim && g.NavWindowingTarget == NULL)
{
g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha - g.IO.DeltaTime * 10.0f, 0.0f);
if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
g.NavWindowingTargetAnim = NULL;
}
// Start CTRL-TAB or Square+L/R window selection
bool start_windowing_with_gamepad = !g.NavWindowingTarget && IsNavInputTest(ImGuiNavInput_Menu, ImGuiInputReadMode_Pressed);
bool start_windowing_with_keyboard = !g.NavWindowingTarget && g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_Tab) && (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard);
if (start_windowing_with_gamepad || start_windowing_with_keyboard)
if (ImGuiWindow* window = g.NavWindow ? g.NavWindow : FindWindowNavFocusable(g.WindowsFocusOrder.Size - 1, -INT_MAX, -1))
{
g.NavWindowingTarget = g.NavWindowingTargetAnim = window->RootWindow; // FIXME-DOCK: Will need to use RootWindowDockStop
g.NavWindowingTimer = g.NavWindowingHighlightAlpha = 0.0f;
g.NavWindowingToggleLayer = start_windowing_with_keyboard ? false : true;
g.NavInputSource = start_windowing_with_keyboard ? ImGuiInputSource_NavKeyboard : ImGuiInputSource_NavGamepad;
}
// Gamepad update
g.NavWindowingTimer += g.IO.DeltaTime;
if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_NavGamepad)
{
// Highlight only appears after a brief time holding the button, so that a fast tap on PadMenu (to toggle NavLayer) doesn't add visual noise
g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f));
// Select window to focus
const int focus_change_dir = (int)IsNavInputTest(ImGuiNavInput_FocusPrev, ImGuiInputReadMode_RepeatSlow) - (int)IsNavInputTest(ImGuiNavInput_FocusNext, ImGuiInputReadMode_RepeatSlow);
if (focus_change_dir != 0)
{
NavUpdateWindowingHighlightWindow(focus_change_dir);
g.NavWindowingHighlightAlpha = 1.0f;
}
// Single press toggles NavLayer, long press with L/R apply actual focus on release (until then the window was merely rendered top-most)
if (!IsNavInputDown(ImGuiNavInput_Menu))
{
g.NavWindowingToggleLayer &= (g.NavWindowingHighlightAlpha < 1.0f); // Once button was held long enough we don't consider it a tap-to-toggle-layer press anymore.
if (g.NavWindowingToggleLayer && g.NavWindow)
apply_toggle_layer = true;
else if (!g.NavWindowingToggleLayer)
apply_focus_window = g.NavWindowingTarget;
g.NavWindowingTarget = NULL;
}
}
// Keyboard: Focus
if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_NavKeyboard)
{
// Visuals only appears after a brief time after pressing TAB the first time, so that a fast CTRL+TAB doesn't add visual noise
g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f)); // 1.0f
if (IsKeyPressedMap(ImGuiKey_Tab, true))
NavUpdateWindowingHighlightWindow(g.IO.KeyShift ? +1 : -1);
if (!g.IO.KeyCtrl)
apply_focus_window = g.NavWindowingTarget;
}
// Keyboard: Press and Release ALT to toggle menu layer
// FIXME: We lack an explicit IO variable for "is the imgui window focused", so compare mouse validity to detect the common case of back-end clearing releases all keys on ALT-TAB
if (IsNavInputTest(ImGuiNavInput_KeyMenu_, ImGuiInputReadMode_Pressed))
g.NavWindowingToggleLayer = true;
if ((g.ActiveId == 0 || g.ActiveIdAllowOverlap) && g.NavWindowingToggleLayer && IsNavInputTest(ImGuiNavInput_KeyMenu_, ImGuiInputReadMode_Released))
if (IsMousePosValid(&g.IO.MousePos) == IsMousePosValid(&g.IO.MousePosPrev))
apply_toggle_layer = true;
// Move window
if (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoMove))
{
ImVec2 move_delta;
if (g.NavInputSource == ImGuiInputSource_NavKeyboard && !g.IO.KeyShift)
move_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard, ImGuiInputReadMode_Down);
if (g.NavInputSource == ImGuiInputSource_NavGamepad)
move_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadLStick, ImGuiInputReadMode_Down);
if (move_delta.x != 0.0f || move_delta.y != 0.0f)
{
const float NAV_MOVE_SPEED = 800.0f;
const float move_speed = ImFloor(NAV_MOVE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y)); // FIXME: Doesn't code variable framerate very well
SetWindowPos(g.NavWindowingTarget->RootWindow, g.NavWindowingTarget->RootWindow->Pos + move_delta * move_speed, ImGuiCond_Always);
g.NavDisableMouseHover = true;
MarkIniSettingsDirty(g.NavWindowingTarget);
}
}
// Apply final focus
if (apply_focus_window && (g.NavWindow == NULL || apply_focus_window != g.NavWindow->RootWindow))
{
ClearActiveID();
g.NavDisableHighlight = false;
g.NavDisableMouseHover = true;
apply_focus_window = NavRestoreLastChildNavWindow(apply_focus_window);
ClosePopupsOverWindow(apply_focus_window, false);
FocusWindow(apply_focus_window);
if (apply_focus_window->NavLastIds[0] == 0)
NavInitWindow(apply_focus_window, false);
// If the window only has a menu layer, select it directly
if (apply_focus_window->DC.NavLayerActiveMask == (1 << ImGuiNavLayer_Menu))
g.NavLayer = ImGuiNavLayer_Menu;
}
if (apply_focus_window)
g.NavWindowingTarget = NULL;
// Apply menu/layer toggle
if (apply_toggle_layer && g.NavWindow)
{
// Move to parent menu if necessary
ImGuiWindow* new_nav_window = g.NavWindow;
while (new_nav_window->ParentWindow
&& (new_nav_window->DC.NavLayerActiveMask & (1 << ImGuiNavLayer_Menu)) == 0
&& (new_nav_window->Flags & ImGuiWindowFlags_ChildWindow) != 0
&& (new_nav_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
new_nav_window = new_nav_window->ParentWindow;
if (new_nav_window != g.NavWindow)
{
ImGuiWindow* old_nav_window = g.NavWindow;
FocusWindow(new_nav_window);
new_nav_window->NavLastChildNavWindow = old_nav_window;
}
g.NavDisableHighlight = false;
g.NavDisableMouseHover = true;
// When entering a regular menu bar with the Alt key, we always reinitialize the navigation ID.
const ImGuiNavLayer new_nav_layer = (g.NavWindow->DC.NavLayerActiveMask & (1 << ImGuiNavLayer_Menu)) ? (ImGuiNavLayer)((int)g.NavLayer ^ 1) : ImGuiNavLayer_Main;
NavRestoreLayer(new_nav_layer);
}
}
// Window has already passed the IsWindowNavFocusable()
static const char* GetFallbackWindowNameForWindowingList(ImGuiWindow* window)
{
if (window->Flags & ImGuiWindowFlags_Popup)
return "(Popup)";
if ((window->Flags & ImGuiWindowFlags_MenuBar) && strcmp(window->Name, "##MainMenuBar") == 0)
return "(Main menu bar)";
return "(Untitled)";
}
// Overlay displayed when using CTRL+TAB. Called by EndFrame().
void ImGui::NavUpdateWindowingOverlay()
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.NavWindowingTarget != NULL);
if (g.NavWindowingTimer < NAV_WINDOWING_LIST_APPEAR_DELAY)
return;
if (g.NavWindowingList == NULL)
g.NavWindowingList = FindWindowByName("###NavWindowingList");
SetNextWindowSizeConstraints(ImVec2(g.IO.DisplaySize.x * 0.20f, g.IO.DisplaySize.y * 0.20f), ImVec2(FLT_MAX, FLT_MAX));
SetNextWindowPos(g.IO.DisplaySize * 0.5f, ImGuiCond_Always, ImVec2(0.5f, 0.5f));
PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.WindowPadding * 2.0f);
Begin("###NavWindowingList", NULL, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings);
for (int n = g.WindowsFocusOrder.Size - 1; n >= 0; n--)
{
ImGuiWindow* window = g.WindowsFocusOrder[n];
if (!IsWindowNavFocusable(window))
continue;
const char* label = window->Name;
if (label == FindRenderedTextEnd(label))
label = GetFallbackWindowNameForWindowingList(window);
Selectable(label, g.NavWindowingTarget == window);
}
End();
PopStyleVar();
}
//-----------------------------------------------------------------------------
// [SECTION] DRAG AND DROP
//-----------------------------------------------------------------------------
void ImGui::ClearDragDrop()
{
ImGuiContext& g = *GImGui;
g.DragDropActive = false;
g.DragDropPayload.Clear();
g.DragDropAcceptFlags = ImGuiDragDropFlags_None;
g.DragDropAcceptIdCurr = g.DragDropAcceptIdPrev = 0;
g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
g.DragDropAcceptFrameCount = -1;
g.DragDropPayloadBufHeap.clear();
memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
}
// Call when current ID is active.
// When this returns true you need to: a) call SetDragDropPayload() exactly once, b) you may render the payload visual/description, c) call EndDragDropSource()
bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
bool source_drag_active = false;
ImGuiID source_id = 0;
ImGuiID source_parent_id = 0;
ImGuiMouseButton mouse_button = ImGuiMouseButton_Left;
if (!(flags & ImGuiDragDropFlags_SourceExtern))
{
source_id = window->DC.LastItemId;
if (source_id != 0 && g.ActiveId != source_id) // Early out for most common case
return false;
if (g.IO.MouseDown[mouse_button] == false)
return false;
if (source_id == 0)
{
// If you want to use BeginDragDropSource() on an item with no unique identifier for interaction, such as Text() or Image(), you need to:
// A) Read the explanation below, B) Use the ImGuiDragDropFlags_SourceAllowNullID flag, C) Swallow your programmer pride.
if (!(flags & ImGuiDragDropFlags_SourceAllowNullID))
{
IM_ASSERT(0);
return false;
}
// Early out
if ((window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect) == 0 && (g.ActiveId == 0 || g.ActiveIdWindow != window))
return false;
// Magic fallback (=somehow reprehensible) to handle items with no assigned ID, e.g. Text(), Image()
// We build a throwaway ID based on current ID stack + relative AABB of items in window.
// THE IDENTIFIER WON'T SURVIVE ANY REPOSITIONING OF THE WIDGET, so if your widget moves your dragging operation will be canceled.
// We don't need to maintain/call ClearActiveID() as releasing the button will early out this function and trigger !ActiveIdIsAlive.
source_id = window->DC.LastItemId = window->GetIDFromRectangle(window->DC.LastItemRect);
bool is_hovered = ItemHoverable(window->DC.LastItemRect, source_id);
if (is_hovered && g.IO.MouseClicked[mouse_button])
{
SetActiveID(source_id, window);
FocusWindow(window);
}
if (g.ActiveId == source_id) // Allow the underlying widget to display/return hovered during the mouse release frame, else we would get a flicker.
g.ActiveIdAllowOverlap = is_hovered;
}
else
{
g.ActiveIdAllowOverlap = false;
}
if (g.ActiveId != source_id)
return false;
source_parent_id = window->IDStack.back();
source_drag_active = IsMouseDragging(mouse_button);
}
else
{
window = NULL;
source_id = ImHashStr("#SourceExtern");
source_drag_active = true;
}
if (source_drag_active)
{
if (!g.DragDropActive)
{
IM_ASSERT(source_id != 0);
ClearDragDrop();
ImGuiPayload& payload = g.DragDropPayload;
payload.SourceId = source_id;
payload.SourceParentId = source_parent_id;
g.DragDropActive = true;
g.DragDropSourceFlags = flags;
g.DragDropMouseButton = mouse_button;
}
g.DragDropSourceFrameCount = g.FrameCount;
g.DragDropWithinSourceOrTarget = true;
if (!(flags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
{
// Target can request the Source to not display its tooltip (we use a dedicated flag to make this request explicit)
// We unfortunately can't just modify the source flags and skip the call to BeginTooltip, as caller may be emitting contents.
BeginTooltip();
if (g.DragDropAcceptIdPrev && (g.DragDropAcceptFlags & ImGuiDragDropFlags_AcceptNoPreviewTooltip))
{
ImGuiWindow* tooltip_window = g.CurrentWindow;
tooltip_window->SkipItems = true;
tooltip_window->HiddenFramesCanSkipItems = 1;
}
}
if (!(flags & ImGuiDragDropFlags_SourceNoDisableHover) && !(flags & ImGuiDragDropFlags_SourceExtern))
window->DC.LastItemStatusFlags &= ~ImGuiItemStatusFlags_HoveredRect;
return true;
}
return false;
}
void ImGui::EndDragDropSource()
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.DragDropActive);
IM_ASSERT(g.DragDropWithinSourceOrTarget && "Not after a BeginDragDropSource()?");
if (!(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
EndTooltip();
// Discard the drag if have not called SetDragDropPayload()
if (g.DragDropPayload.DataFrameCount == -1)
ClearDragDrop();
g.DragDropWithinSourceOrTarget = false;
}
// Use 'cond' to choose to submit payload on drag start or every frame
bool ImGui::SetDragDropPayload(const char* type, const void* data, size_t data_size, ImGuiCond cond)
{
ImGuiContext& g = *GImGui;
ImGuiPayload& payload = g.DragDropPayload;
if (cond == 0)
cond = ImGuiCond_Always;
IM_ASSERT(type != NULL);
IM_ASSERT(strlen(type) < IM_ARRAYSIZE(payload.DataType) && "Payload type can be at most 32 characters long");
IM_ASSERT((data != NULL && data_size > 0) || (data == NULL && data_size == 0));
IM_ASSERT(cond == ImGuiCond_Always || cond == ImGuiCond_Once);
IM_ASSERT(payload.SourceId != 0); // Not called between BeginDragDropSource() and EndDragDropSource()
if (cond == ImGuiCond_Always || payload.DataFrameCount == -1)
{
// Copy payload
ImStrncpy(payload.DataType, type, IM_ARRAYSIZE(payload.DataType));
g.DragDropPayloadBufHeap.resize(0);
if (data_size > sizeof(g.DragDropPayloadBufLocal))
{
// Store in heap
g.DragDropPayloadBufHeap.resize((int)data_size);
payload.Data = g.DragDropPayloadBufHeap.Data;
memcpy(payload.Data, data, data_size);
}
else if (data_size > 0)
{
// Store locally
memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
payload.Data = g.DragDropPayloadBufLocal;
memcpy(payload.Data, data, data_size);
}
else
{
payload.Data = NULL;
}
payload.DataSize = (int)data_size;
}
payload.DataFrameCount = g.FrameCount;
return (g.DragDropAcceptFrameCount == g.FrameCount) || (g.DragDropAcceptFrameCount == g.FrameCount - 1);
}
bool ImGui::BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id)
{
ImGuiContext& g = *GImGui;
if (!g.DragDropActive)
return false;
ImGuiWindow* window = g.CurrentWindow;
if (g.HoveredWindow == NULL || window->RootWindow != g.HoveredWindow->RootWindow)
return false;
IM_ASSERT(id != 0);
if (!IsMouseHoveringRect(bb.Min, bb.Max) || (id == g.DragDropPayload.SourceId))
return false;
if (window->SkipItems)
return false;
IM_ASSERT(g.DragDropWithinSourceOrTarget == false);
g.DragDropTargetRect = bb;
g.DragDropTargetId = id;
g.DragDropWithinSourceOrTarget = true;
return true;
}
// We don't use BeginDragDropTargetCustom() and duplicate its code because:
// 1) we use LastItemRectHoveredRect which handles items that pushes a temporarily clip rectangle in their code. Calling BeginDragDropTargetCustom(LastItemRect) would not handle them.
// 2) and it's faster. as this code may be very frequently called, we want to early out as fast as we can.
// Also note how the HoveredWindow test is positioned differently in both functions (in both functions we optimize for the cheapest early out case)
bool ImGui::BeginDragDropTarget()
{
ImGuiContext& g = *GImGui;
if (!g.DragDropActive)
return false;
ImGuiWindow* window = g.CurrentWindow;
if (!(window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect))
return false;
if (g.HoveredWindow == NULL || window->RootWindow != g.HoveredWindow->RootWindow)
return false;
const ImRect& display_rect = (window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HasDisplayRect) ? window->DC.LastItemDisplayRect : window->DC.LastItemRect;
ImGuiID id = window->DC.LastItemId;
if (id == 0)
id = window->GetIDFromRectangle(display_rect);
if (g.DragDropPayload.SourceId == id)
return false;
IM_ASSERT(g.DragDropWithinSourceOrTarget == false);
g.DragDropTargetRect = display_rect;
g.DragDropTargetId = id;
g.DragDropWithinSourceOrTarget = true;
return true;
}
bool ImGui::IsDragDropPayloadBeingAccepted()
{
ImGuiContext& g = *GImGui;
return g.DragDropActive && g.DragDropAcceptIdPrev != 0;
}
const ImGuiPayload* ImGui::AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
ImGuiPayload& payload = g.DragDropPayload;
IM_ASSERT(g.DragDropActive); // Not called between BeginDragDropTarget() and EndDragDropTarget() ?
IM_ASSERT(payload.DataFrameCount != -1); // Forgot to call EndDragDropTarget() ?
if (type != NULL && !payload.IsDataType(type))
return NULL;
// Accept smallest drag target bounding box, this allows us to nest drag targets conveniently without ordering constraints.
// NB: We currently accept NULL id as target. However, overlapping targets requires a unique ID to function!
const bool was_accepted_previously = (g.DragDropAcceptIdPrev == g.DragDropTargetId);
ImRect r = g.DragDropTargetRect;
float r_surface = r.GetWidth() * r.GetHeight();
if (r_surface < g.DragDropAcceptIdCurrRectSurface)
{
g.DragDropAcceptFlags = flags;
g.DragDropAcceptIdCurr = g.DragDropTargetId;
g.DragDropAcceptIdCurrRectSurface = r_surface;
}
// Render default drop visuals
payload.Preview = was_accepted_previously;
flags |= (g.DragDropSourceFlags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect); // Source can also inhibit the preview (useful for external sources that lives for 1 frame)
if (!(flags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect) && payload.Preview)
{
// FIXME-DRAG: Settle on a proper default visuals for drop target.
r.Expand(3.5f);
bool push_clip_rect = !window->ClipRect.Contains(r);
if (push_clip_rect) window->DrawList->PushClipRect(r.Min-ImVec2(1,1), r.Max+ImVec2(1,1));
window->DrawList->AddRect(r.Min, r.Max, GetColorU32(ImGuiCol_DragDropTarget), 0.0f, ~0, 2.0f);
if (push_clip_rect) window->DrawList->PopClipRect();
}
g.DragDropAcceptFrameCount = g.FrameCount;
payload.Delivery = was_accepted_previously && !IsMouseDown(g.DragDropMouseButton); // For extern drag sources affecting os window focus, it's easier to just test !IsMouseDown() instead of IsMouseReleased()
if (!payload.Delivery && !(flags & ImGuiDragDropFlags_AcceptBeforeDelivery))
return NULL;
return &payload;
}
const ImGuiPayload* ImGui::GetDragDropPayload()
{
ImGuiContext& g = *GImGui;
return g.DragDropActive ? &g.DragDropPayload : NULL;
}
// We don't really use/need this now, but added it for the sake of consistency and because we might need it later.
void ImGui::EndDragDropTarget()
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.DragDropActive);
IM_ASSERT(g.DragDropWithinSourceOrTarget);
g.DragDropWithinSourceOrTarget = false;
}
//-----------------------------------------------------------------------------
// [SECTION] LOGGING/CAPTURING
//-----------------------------------------------------------------------------
// All text output from the interface can be captured into tty/file/clipboard.
// By default, tree nodes are automatically opened during logging.
//-----------------------------------------------------------------------------
// Pass text data straight to log (without being displayed)
void ImGui::LogText(const char* fmt, ...)
{
ImGuiContext& g = *GImGui;
if (!g.LogEnabled)
return;
va_list args;
va_start(args, fmt);
if (g.LogFile)
{
g.LogBuffer.Buf.resize(0);
g.LogBuffer.appendfv(fmt, args);
ImFileWrite(g.LogBuffer.c_str(), sizeof(char), (ImU64)g.LogBuffer.size(), g.LogFile);
}
else
{
g.LogBuffer.appendfv(fmt, args);
}
va_end(args);
}
// Internal version that takes a position to decide on newline placement and pad items according to their depth.
// We split text into individual lines to add current tree level padding
void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (!text_end)
text_end = FindRenderedTextEnd(text, text_end);
const bool log_new_line = ref_pos && (ref_pos->y > g.LogLinePosY + 1);
if (ref_pos)
g.LogLinePosY = ref_pos->y;
if (log_new_line)
g.LogLineFirstItem = true;
const char* text_remaining = text;
if (g.LogDepthRef > window->DC.TreeDepth) // Re-adjust padding if we have popped out of our starting depth
g.LogDepthRef = window->DC.TreeDepth;
const int tree_depth = (window->DC.TreeDepth - g.LogDepthRef);
for (;;)
{
// Split the string. Each new line (after a '\n') is followed by spacing corresponding to the current depth of our log entry.
// We don't add a trailing \n to allow a subsequent item on the same line to be captured.
const char* line_start = text_remaining;
const char* line_end = ImStreolRange(line_start, text_end);
const bool is_first_line = (line_start == text);
const bool is_last_line = (line_end == text_end);
if (!is_last_line || (line_start != line_end))
{
const int char_count = (int)(line_end - line_start);
if (log_new_line || !is_first_line)
LogText(IM_NEWLINE "%*s%.*s", tree_depth * 4, "", char_count, line_start);
else if (g.LogLineFirstItem)
LogText("%*s%.*s", tree_depth * 4, "", char_count, line_start);
else
LogText(" %.*s", char_count, line_start);
g.LogLineFirstItem = false;
}
else if (log_new_line)
{
// An empty "" string at a different Y position should output a carriage return.
LogText(IM_NEWLINE);
break;
}
if (is_last_line)
break;
text_remaining = line_end + 1;
}
}
// Start logging/capturing text output
void ImGui::LogBegin(ImGuiLogType type, int auto_open_depth)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
IM_ASSERT(g.LogEnabled == false);
IM_ASSERT(g.LogFile == NULL);
IM_ASSERT(g.LogBuffer.empty());
g.LogEnabled = true;
g.LogType = type;
g.LogDepthRef = window->DC.TreeDepth;
g.LogDepthToExpand = ((auto_open_depth >= 0) ? auto_open_depth : g.LogDepthToExpandDefault);
g.LogLinePosY = FLT_MAX;
g.LogLineFirstItem = true;
}
void ImGui::LogToTTY(int auto_open_depth)
{
ImGuiContext& g = *GImGui;
if (g.LogEnabled)
return;
IM_UNUSED(auto_open_depth);
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
LogBegin(ImGuiLogType_TTY, auto_open_depth);
g.LogFile = stdout;
#endif
}
// Start logging/capturing text output to given file
void ImGui::LogToFile(int auto_open_depth, const char* filename)
{
ImGuiContext& g = *GImGui;
if (g.LogEnabled)
return;
// FIXME: We could probably open the file in text mode "at", however note that clipboard/buffer logging will still
// be subject to outputting OS-incompatible carriage return if within strings the user doesn't use IM_NEWLINE.
// By opening the file in binary mode "ab" we have consistent output everywhere.
if (!filename)
filename = g.IO.LogFilename;
if (!filename || !filename[0])
return;
ImFileHandle f = ImFileOpen(filename, "ab");
if (!f)
{
IM_ASSERT(0);
return;
}
LogBegin(ImGuiLogType_File, auto_open_depth);
g.LogFile = f;
}
// Start logging/capturing text output to clipboard
void ImGui::LogToClipboard(int auto_open_depth)
{
ImGuiContext& g = *GImGui;
if (g.LogEnabled)
return;
LogBegin(ImGuiLogType_Clipboard, auto_open_depth);
}
void ImGui::LogToBuffer(int auto_open_depth)
{
ImGuiContext& g = *GImGui;
if (g.LogEnabled)
return;
LogBegin(ImGuiLogType_Buffer, auto_open_depth);
}
void ImGui::LogFinish()
{
ImGuiContext& g = *GImGui;
if (!g.LogEnabled)
return;
LogText(IM_NEWLINE);
switch (g.LogType)
{
case ImGuiLogType_TTY:
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
fflush(g.LogFile);
#endif
break;
case ImGuiLogType_File:
ImFileClose(g.LogFile);
break;
case ImGuiLogType_Buffer:
break;
case ImGuiLogType_Clipboard:
if (!g.LogBuffer.empty())
SetClipboardText(g.LogBuffer.begin());
break;
case ImGuiLogType_None:
IM_ASSERT(0);
break;
}
g.LogEnabled = false;
g.LogType = ImGuiLogType_None;
g.LogFile = NULL;
g.LogBuffer.clear();
}
// Helper to display logging buttons
// FIXME-OBSOLETE: We should probably obsolete this and let the user have their own helper (this is one of the oldest function alive!)
void ImGui::LogButtons()
{
ImGuiContext& g = *GImGui;
PushID("LogButtons");
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
const bool log_to_tty = Button("Log To TTY"); SameLine();
#else
const bool log_to_tty = false;
#endif
const bool log_to_file = Button("Log To File"); SameLine();
const bool log_to_clipboard = Button("Log To Clipboard"); SameLine();
PushAllowKeyboardFocus(false);
SetNextItemWidth(80.0f);
SliderInt("Default Depth", &g.LogDepthToExpandDefault, 0, 9, NULL);
PopAllowKeyboardFocus();
PopID();
// Start logging at the end of the function so that the buttons don't appear in the log
if (log_to_tty)
LogToTTY();
if (log_to_file)
LogToFile();
if (log_to_clipboard)
LogToClipboard();
}
//-----------------------------------------------------------------------------
// [SECTION] SETTINGS
//-----------------------------------------------------------------------------
void ImGui::MarkIniSettingsDirty()
{
ImGuiContext& g = *GImGui;
if (g.SettingsDirtyTimer <= 0.0f)
g.SettingsDirtyTimer = g.IO.IniSavingRate;
}
void ImGui::MarkIniSettingsDirty(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
if (!(window->Flags & ImGuiWindowFlags_NoSavedSettings))
if (g.SettingsDirtyTimer <= 0.0f)
g.SettingsDirtyTimer = g.IO.IniSavingRate;
}
ImGuiWindowSettings* ImGui::CreateNewWindowSettings(const char* name)
{
ImGuiContext& g = *GImGui;
#if !IMGUI_DEBUG_INI_SETTINGS
// Skip to the "###" marker if any. We don't skip past to match the behavior of GetID()
// Preserve the full string when IMGUI_DEBUG_INI_SETTINGS is set to make .ini inspection easier.
if (const char* p = strstr(name, "###"))
name = p;
#endif
const size_t name_len = strlen(name);
// Allocate chunk
const size_t chunk_size = sizeof(ImGuiWindowSettings) + name_len + 1;
ImGuiWindowSettings* settings = g.SettingsWindows.alloc_chunk(chunk_size);
IM_PLACEMENT_NEW(settings) ImGuiWindowSettings();
settings->ID = ImHashStr(name, name_len);
memcpy(settings->GetName(), name, name_len + 1); // Store with zero terminator
return settings;
}
ImGuiWindowSettings* ImGui::FindWindowSettings(ImGuiID id)
{
ImGuiContext& g = *GImGui;
for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
if (settings->ID == id)
return settings;
return NULL;
}
ImGuiWindowSettings* ImGui::FindOrCreateWindowSettings(const char* name)
{
if (ImGuiWindowSettings* settings = FindWindowSettings(ImHashStr(name)))
return settings;
return CreateNewWindowSettings(name);
}
void ImGui::LoadIniSettingsFromDisk(const char* ini_filename)
{
size_t file_data_size = 0;
char* file_data = (char*)ImFileLoadToMemory(ini_filename, "rb", &file_data_size);
if (!file_data)
return;
LoadIniSettingsFromMemory(file_data, (size_t)file_data_size);
IM_FREE(file_data);
}
ImGuiSettingsHandler* ImGui::FindSettingsHandler(const char* type_name)
{
ImGuiContext& g = *GImGui;
const ImGuiID type_hash = ImHashStr(type_name);
for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
if (g.SettingsHandlers[handler_n].TypeHash == type_hash)
return &g.SettingsHandlers[handler_n];
return NULL;
}
// Zero-tolerance, no error reporting, cheap .ini parsing
void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.Initialized);
IM_ASSERT(g.SettingsLoaded == false && g.FrameCount == 0);
// For user convenience, we allow passing a non zero-terminated string (hence the ini_size parameter).
// For our convenience and to make the code simpler, we'll also write zero-terminators within the buffer. So let's create a writable copy..
if (ini_size == 0)
ini_size = strlen(ini_data);
char* buf = (char*)IM_ALLOC(ini_size + 1);
char* buf_end = buf + ini_size;
memcpy(buf, ini_data, ini_size);
buf[ini_size] = 0;
void* entry_data = NULL;
ImGuiSettingsHandler* entry_handler = NULL;
char* line_end = NULL;
for (char* line = buf; line < buf_end; line = line_end + 1)
{
// Skip new lines markers, then find end of the line
while (*line == '\n' || *line == '\r')
line++;
line_end = line;
while (line_end < buf_end && *line_end != '\n' && *line_end != '\r')
line_end++;
line_end[0] = 0;
if (line[0] == ';')
continue;
if (line[0] == '[' && line_end > line && line_end[-1] == ']')
{
// Parse "[Type][Name]". Note that 'Name' can itself contains [] characters, which is acceptable with the current format and parsing code.
line_end[-1] = 0;
const char* name_end = line_end - 1;
const char* type_start = line + 1;
char* type_end = (char*)(void*)ImStrchrRange(type_start, name_end, ']');
const char* name_start = type_end ? ImStrchrRange(type_end + 1, name_end, '[') : NULL;
if (!type_end || !name_start)
continue;
*type_end = 0; // Overwrite first ']'
name_start++; // Skip second '['
entry_handler = FindSettingsHandler(type_start);
entry_data = entry_handler ? entry_handler->ReadOpenFn(&g, entry_handler, name_start) : NULL;
}
else if (entry_handler != NULL && entry_data != NULL)
{
// Let type handler parse the line
entry_handler->ReadLineFn(&g, entry_handler, entry_data, line);
}
}
IM_FREE(buf);
g.SettingsLoaded = true;
}
void ImGui::SaveIniSettingsToDisk(const char* ini_filename)
{
ImGuiContext& g = *GImGui;
g.SettingsDirtyTimer = 0.0f;
if (!ini_filename)
return;
size_t ini_data_size = 0;
const char* ini_data = SaveIniSettingsToMemory(&ini_data_size);
ImFileHandle f = ImFileOpen(ini_filename, "wt");
if (!f)
return;
ImFileWrite(ini_data, sizeof(char), ini_data_size, f);
ImFileClose(f);
}
// Call registered handlers (e.g. SettingsHandlerWindow_WriteAll() + custom handlers) to write their stuff into a text buffer
const char* ImGui::SaveIniSettingsToMemory(size_t* out_size)
{
ImGuiContext& g = *GImGui;
g.SettingsDirtyTimer = 0.0f;
g.SettingsIniData.Buf.resize(0);
g.SettingsIniData.Buf.push_back(0);
for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
{
ImGuiSettingsHandler* handler = &g.SettingsHandlers[handler_n];
handler->WriteAllFn(&g, handler, &g.SettingsIniData);
}
if (out_size)
*out_size = (size_t)g.SettingsIniData.size();
return g.SettingsIniData.c_str();
}
static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
{
ImGuiWindowSettings* settings = ImGui::FindWindowSettings(ImHashStr(name));
if (!settings)
settings = ImGui::CreateNewWindowSettings(name);
return (void*)settings;
}
static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line)
{
ImGuiWindowSettings* settings = (ImGuiWindowSettings*)entry;
int x, y;
int i;
if (sscanf(line, "Pos=%i,%i", &x, &y) == 2) settings->Pos = ImVec2ih((short)x, (short)y);
else if (sscanf(line, "Size=%i,%i", &x, &y) == 2) settings->Size = ImVec2ih((short)x, (short)y);
else if (sscanf(line, "Collapsed=%d", &i) == 1) settings->Collapsed = (i != 0);
}
static void WindowSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
{
// Gather data from windows that were active during this session
// (if a window wasn't opened in this session we preserve its settings)
ImGuiContext& g = *ctx;
for (int i = 0; i != g.Windows.Size; i++)
{
ImGuiWindow* window = g.Windows[i];
if (window->Flags & ImGuiWindowFlags_NoSavedSettings)
continue;
ImGuiWindowSettings* settings = (window->SettingsOffset != -1) ? g.SettingsWindows.ptr_from_offset(window->SettingsOffset) : ImGui::FindWindowSettings(window->ID);
if (!settings)
{
settings = ImGui::CreateNewWindowSettings(window->Name);
window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
}
IM_ASSERT(settings->ID == window->ID);
settings->Pos = ImVec2ih((short)window->Pos.x, (short)window->Pos.y);
settings->Size = ImVec2ih((short)window->SizeFull.x, (short)window->SizeFull.y);
settings->Collapsed = window->Collapsed;
}
// Write to text buffer
buf->reserve(buf->size() + g.SettingsWindows.size() * 6); // ballpark reserve
for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
{
const char* settings_name = settings->GetName();
buf->appendf("[%s][%s]\n", handler->TypeName, settings_name);
buf->appendf("Pos=%d,%d\n", settings->Pos.x, settings->Pos.y);
buf->appendf("Size=%d,%d\n", settings->Size.x, settings->Size.y);
buf->appendf("Collapsed=%d\n", settings->Collapsed);
buf->append("\n");
}
}
//-----------------------------------------------------------------------------
// [SECTION] VIEWPORTS, PLATFORM WINDOWS
//-----------------------------------------------------------------------------
// (this section is filled in the 'docking' branch)
//-----------------------------------------------------------------------------
// [SECTION] DOCKING
//-----------------------------------------------------------------------------
// (this section is filled in the 'docking' branch)
//-----------------------------------------------------------------------------
// [SECTION] PLATFORM DEPENDENT HELPERS
//-----------------------------------------------------------------------------
#if defined(_WIN32) && !defined(_WINDOWS_) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && (!defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS) || !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS))
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#ifndef __MINGW32__
#include <Windows.h>
#else
#include <windows.h>
#endif
#if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP) // UWP doesn't have Win32 functions
#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS
#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
#endif
#elif defined(__APPLE__)
#include <TargetConditionals.h>
#endif
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS)
#ifdef _MSC_VER
#pragma comment(lib, "user32")
#endif
// Win32 clipboard implementation
static const char* GetClipboardTextFn_DefaultImpl(void*)
{
static ImVector<char> buf_local;
buf_local.clear();
if (!::OpenClipboard(NULL))
return NULL;
HANDLE wbuf_handle = ::GetClipboardData(CF_UNICODETEXT);
if (wbuf_handle == NULL)
{
::CloseClipboard();
return NULL;
}
if (ImWchar* wbuf_global = (ImWchar*)::GlobalLock(wbuf_handle))
{
int buf_len = ImTextCountUtf8BytesFromStr(wbuf_global, NULL) + 1;
buf_local.resize(buf_len);
ImTextStrToUtf8(buf_local.Data, buf_len, wbuf_global, NULL);
}
::GlobalUnlock(wbuf_handle);
::CloseClipboard();
return buf_local.Data;
}
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
{
if (!::OpenClipboard(NULL))
return;
const int wbuf_length = ImTextCountCharsFromUtf8(text, NULL) + 1;
HGLOBAL wbuf_handle = ::GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(ImWchar));
if (wbuf_handle == NULL)
{
::CloseClipboard();
return;
}
ImWchar* wbuf_global = (ImWchar*)::GlobalLock(wbuf_handle);
ImTextStrFromUtf8(wbuf_global, wbuf_length, text, NULL);
::GlobalUnlock(wbuf_handle);
::EmptyClipboard();
if (::SetClipboardData(CF_UNICODETEXT, wbuf_handle) == NULL)
::GlobalFree(wbuf_handle);
::CloseClipboard();
}
#elif defined(__APPLE__) && TARGET_OS_OSX && defined(IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS)
#include <Carbon/Carbon.h> // Use old API to avoid need for separate .mm file
static PasteboardRef main_clipboard = 0;
// OSX clipboard implementation
// If you enable this you will need to add '-framework ApplicationServices' to your linker command-line!
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
{
if (!main_clipboard)
PasteboardCreate(kPasteboardClipboard, &main_clipboard);
PasteboardClear(main_clipboard);
CFDataRef cf_data = CFDataCreate(kCFAllocatorDefault, (const UInt8*)text, strlen(text));
if (cf_data)
{
PasteboardPutItemFlavor(main_clipboard, (PasteboardItemID)1, CFSTR("public.utf8-plain-text"), cf_data, 0);
CFRelease(cf_data);
}
}
static const char* GetClipboardTextFn_DefaultImpl(void*)
{
if (!main_clipboard)
PasteboardCreate(kPasteboardClipboard, &main_clipboard);
PasteboardSynchronize(main_clipboard);
ItemCount item_count = 0;
PasteboardGetItemCount(main_clipboard, &item_count);
for (ItemCount i = 0; i < item_count; i++)
{
PasteboardItemID item_id = 0;
PasteboardGetItemIdentifier(main_clipboard, i + 1, &item_id);
CFArrayRef flavor_type_array = 0;
PasteboardCopyItemFlavors(main_clipboard, item_id, &flavor_type_array);
for (CFIndex j = 0, nj = CFArrayGetCount(flavor_type_array); j < nj; j++)
{
CFDataRef cf_data;
if (PasteboardCopyItemFlavorData(main_clipboard, item_id, CFSTR("public.utf8-plain-text"), &cf_data) == noErr)
{
static ImVector<char> clipboard_text;
int length = (int)CFDataGetLength(cf_data);
clipboard_text.resize(length + 1);
CFDataGetBytes(cf_data, CFRangeMake(0, length), (UInt8*)clipboard_text.Data);
clipboard_text[length] = 0;
CFRelease(cf_data);
return clipboard_text.Data;
}
}
}
return NULL;
}
#else
// Local Dear ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers.
static const char* GetClipboardTextFn_DefaultImpl(void*)
{
ImGuiContext& g = *GImGui;
return g.PrivateClipboard.empty() ? NULL : g.PrivateClipboard.begin();
}
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
{
ImGuiContext& g = *GImGui;
g.PrivateClipboard.clear();
const char* text_end = text + strlen(text);
g.PrivateClipboard.resize((int)(text_end - text) + 1);
memcpy(&g.PrivateClipboard[0], text, (size_t)(text_end - text));
g.PrivateClipboard[(int)(text_end - text)] = 0;
}
#endif
// Win32 API IME support (for Asian languages, etc.)
#if defined(_WIN32) && !defined(__GNUC__) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
#include <imm.h>
#ifdef _MSC_VER
#pragma comment(lib, "imm32")
#endif
static void ImeSetInputScreenPosFn_DefaultImpl(int x, int y)
{
// Notify OS Input Method Editor of text input position
ImGuiIO& io = ImGui::GetIO();
if (HWND hwnd = (HWND)io.ImeWindowHandle)
if (HIMC himc = ::ImmGetContext(hwnd))
{
COMPOSITIONFORM cf;
cf.ptCurrentPos.x = x;
cf.ptCurrentPos.y = y;
cf.dwStyle = CFS_FORCE_POSITION;
::ImmSetCompositionWindow(himc, &cf);
::ImmReleaseContext(hwnd, himc);
}
}
#else
static void ImeSetInputScreenPosFn_DefaultImpl(int, int) {}
#endif
//-----------------------------------------------------------------------------
// [SECTION] METRICS/DEBUG WINDOW
//-----------------------------------------------------------------------------
#ifndef IMGUI_DISABLE_METRICS_WINDOW
// Avoid naming collision with imgui_demo.cpp's HelpMarker() for unity builds.
static void MetricsHelpMarker(const char* desc)
{
ImGui::TextDisabled("(?)");
if (ImGui::IsItemHovered())
{
ImGui::BeginTooltip();
ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f);
ImGui::TextUnformatted(desc);
ImGui::PopTextWrapPos();
ImGui::EndTooltip();
}
}
void ImGui::ShowMetricsWindow(bool* p_open)
{
if (!ImGui::Begin("Dear ImGui Metrics", p_open))
{
ImGui::End();
return;
}
// Debugging enums
enum { WRT_OuterRect, WRT_OuterRectClipped, WRT_InnerRect, WRT_InnerClipRect, WRT_WorkRect, WRT_Content, WRT_ContentRegionRect, WRT_Count }; // Windows Rect Type
const char* wrt_rects_names[WRT_Count] = { "OuterRect", "OuterRectClipped", "InnerRect", "InnerClipRect", "WorkRect", "Content", "ContentRegionRect" };
enum { TRT_OuterRect, TRT_WorkRect, TRT_HostClipRect, TRT_InnerClipRect, TRT_BackgroundClipRect, TRT_ColumnsRect, TRT_ColumnsClipRect, TRT_ColumnsContentHeadersUsed, TRT_ColumnsContentHeadersDesired, TRT_ColumnsContentRowsFrozen, TRT_ColumnsContentRowsUnfrozen, TRT_Count }; // Tables Rect Type
const char* trt_rects_names[TRT_Count] = { "OuterRect", "WorkRect", "HostClipRect", "InnerClipRect", "BackgroundClipRect", "ColumnsRect", "ColumnsClipRect", "ColumnsContentHeadersUsed", "ColumnsContentHeadersDesired", "ColumnsContentRowsFrozen", "ColumnsContentRowsUnfrozen" };
// State
static bool show_windows_rects = false;
static int show_windows_rect_type = WRT_WorkRect;
static bool show_windows_begin_order = false;
static bool show_tables_rects = false;
static int show_tables_rect_type = TRT_WorkRect;
static bool show_drawcmd_details = true;
// Basic info
ImGuiContext& g = *GImGui;
ImGuiIO& io = ImGui::GetIO();
ImGui::Text("Dear ImGui %s", ImGui::GetVersion());
ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
ImGui::Text("%d vertices, %d indices (%d triangles)", io.MetricsRenderVertices, io.MetricsRenderIndices, io.MetricsRenderIndices / 3);
ImGui::Text("%d active windows (%d visible)", io.MetricsActiveWindows, io.MetricsRenderWindows);
ImGui::Text("%d active allocations", io.MetricsActiveAllocations);
ImGui::Separator();
// Helper functions to display common structures:
// - NodeDrawList()
// - NodeColumns()
// - NodeWindow()
// - NodeWindows()
// - NodeTabBar()
// - NodeStorage()
struct Funcs
{
static ImRect GetWindowRect(ImGuiWindow* window, int rect_type)
{
if (rect_type == WRT_OuterRect) { return window->Rect(); }
else if (rect_type == WRT_OuterRectClipped) { return window->OuterRectClipped; }
else if (rect_type == WRT_InnerRect) { return window->InnerRect; }
else if (rect_type == WRT_InnerClipRect) { return window->InnerClipRect; }
else if (rect_type == WRT_WorkRect) { return window->WorkRect; }
else if (rect_type == WRT_Content) { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSize); }
else if (rect_type == WRT_ContentRegionRect) { return window->ContentRegionRect; }
IM_ASSERT(0);
return ImRect();
}
static void NodeDrawList(ImGuiWindow* window, ImDrawList* draw_list, const char* label)
{
bool node_open = ImGui::TreeNode(draw_list, "%s: '%s' %d vtx, %d indices, %d cmds", label, draw_list->_OwnerName ? draw_list->_OwnerName : "", draw_list->VtxBuffer.Size, draw_list->IdxBuffer.Size, draw_list->CmdBuffer.Size);
if (draw_list == ImGui::GetWindowDrawList())
{
ImGui::SameLine();
ImGui::TextColored(ImVec4(1.0f,0.4f,0.4f,1.0f), "CURRENTLY APPENDING"); // Can't display stats for active draw list! (we don't have the data double-buffered)
if (node_open) ImGui::TreePop();
return;
}
ImDrawList* fg_draw_list = GetForegroundDrawList(window); // Render additional visuals into the top-most draw list
if (window && IsItemHovered())
fg_draw_list->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
if (!node_open)
return;
if (window && !window->WasActive)
ImGui::TextDisabled("Warning: owning Window is inactive. This DrawList is not being rendered!");
unsigned int elem_offset = 0;
for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.begin(); pcmd < draw_list->CmdBuffer.end(); elem_offset += pcmd->ElemCount, pcmd++)
{
if (pcmd->UserCallback == NULL && pcmd->ElemCount == 0)
continue;
if (pcmd->UserCallback)
{
ImGui::BulletText("Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData);
continue;
}
ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL;
char buf[300];
ImFormatString(buf, IM_ARRAYSIZE(buf), "DrawCmd: %4d triangles, Tex 0x%p, ClipRect (%4.0f,%4.0f)-(%4.0f,%4.0f)",
pcmd->ElemCount/3, (void*)(intptr_t)pcmd->TextureId,
pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w);
bool pcmd_node_open = ImGui::TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "%s", buf);
if (show_drawcmd_details && fg_draw_list && ImGui::IsItemHovered())
{
ImRect clip_rect = pcmd->ClipRect;
ImRect vtxs_rect(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
for (unsigned int i = elem_offset; i < elem_offset + (int)pcmd->ElemCount; i++)
vtxs_rect.Add(draw_list->VtxBuffer[idx_buffer ? idx_buffer[i] : i].pos);
fg_draw_list->AddRect(ImFloor(clip_rect.Min), ImFloor(clip_rect.Max), IM_COL32(255,0,255,255));
fg_draw_list->AddRect(ImFloor(vtxs_rect.Min), ImFloor(vtxs_rect.Max), IM_COL32(255,255,0,255));
}
if (!pcmd_node_open)
continue;
// Calculate approximate coverage area (touched pixel count)
// This will be in pixels squared as long there's no post-scaling happening to the renderer output.
float total_area = 0.0f;
for (unsigned int base_idx = elem_offset; base_idx < (elem_offset + pcmd->ElemCount); base_idx += 3)
{
ImVec2 triangle[3];
for (int n = 0; n < 3; n++)
triangle[n] = draw_list->VtxBuffer[idx_buffer ? idx_buffer[base_idx + n] : (base_idx + n)].pos;
total_area += ImTriangleArea(triangle[0], triangle[1], triangle[2]);
}
// Display vertex information summary. Hover to get all triangles drawn in wire-frame
ImFormatString(buf, IM_ARRAYSIZE(buf), "Mesh: ElemCount: %d, VtxOffset: +%d, IdxOffset: +%d, Area: ~%0.f px", pcmd->ElemCount, pcmd->VtxOffset, pcmd->IdxOffset, total_area);
ImGui::Selectable(buf);
if (fg_draw_list && ImGui::IsItemHovered() && show_drawcmd_details)
{
// Draw wire-frame version of everything
ImDrawListFlags backup_flags = fg_draw_list->Flags;
fg_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
ImRect clip_rect = pcmd->ClipRect;
fg_draw_list->AddRect(ImFloor(clip_rect.Min), ImFloor(clip_rect.Max), IM_COL32(255, 0, 255, 255));
for (unsigned int base_idx = elem_offset; base_idx < (elem_offset + pcmd->ElemCount); base_idx += 3)
{
ImVec2 triangle[3];
for (int n = 0; n < 3; n++)
triangle[n] = draw_list->VtxBuffer[idx_buffer ? idx_buffer[base_idx + n] : (base_idx + n)].pos;
fg_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), true, 1.0f);
}
fg_draw_list->Flags = backup_flags;
}
// Display individual triangles/vertices. Hover on to get the corresponding triangle highlighted.
ImGuiListClipper clipper(pcmd->ElemCount/3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible.
while (clipper.Step())
for (int prim = clipper.DisplayStart, idx_i = elem_offset + clipper.DisplayStart*3; prim < clipper.DisplayEnd; prim++)
{
char *buf_p = buf, *buf_end = buf + IM_ARRAYSIZE(buf);
ImVec2 triangle[3];
for (int n = 0; n < 3; n++, idx_i++)
{
ImDrawVert& v = draw_list->VtxBuffer[idx_buffer ? idx_buffer[idx_i] : idx_i];
triangle[n] = v.pos;
buf_p += ImFormatString(buf_p, buf_end - buf_p, "%s %04d: pos (%8.2f,%8.2f), uv (%.6f,%.6f), col %08X\n",
(n == 0) ? "Vert:" : " ", idx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col);
}
ImGui::Selectable(buf, false);
if (fg_draw_list && ImGui::IsItemHovered())
{
ImDrawListFlags backup_flags = fg_draw_list->Flags;
fg_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
fg_draw_list->AddPolyline(triangle, 3, IM_COL32(255,255,0,255), true, 1.0f);
fg_draw_list->Flags = backup_flags;
}
}
ImGui::TreePop();
}
ImGui::TreePop();
}
static void NodeColumns(const ImGuiColumns* columns)
{
if (!ImGui::TreeNode((void*)(uintptr_t)columns->ID, "Columns Id: 0x%08X, Count: %d, Flags: 0x%04X", columns->ID, columns->Count, columns->Flags))
return;
ImGui::BulletText("Width: %.1f (MinX: %.1f, MaxX: %.1f)", columns->OffMaxX - columns->OffMinX, columns->OffMinX, columns->OffMaxX);
for (int column_n = 0; column_n < columns->Columns.Size; column_n++)
ImGui::BulletText("Column %02d: OffsetNorm %.3f (= %.1f px)", column_n, columns->Columns[column_n].OffsetNorm, GetColumnOffsetFromNorm(columns, columns->Columns[column_n].OffsetNorm));
ImGui::TreePop();
}
static void NodeWindows(ImVector<ImGuiWindow*>& windows, const char* label)
{
if (!ImGui::TreeNode(label, "%s (%d)", label, windows.Size))
return;
for (int i = 0; i < windows.Size; i++)
{
ImGui::PushID(windows[i]);
Funcs::NodeWindow(windows[i], "Window");
ImGui::PopID();
}
ImGui::TreePop();
}
static void NodeWindow(ImGuiWindow* window, const char* label)
{
if (window == NULL)
{
ImGui::BulletText("%s: NULL", label);
return;
}
bool open = ImGui::TreeNode(label, "%s '%s', %d @ 0x%p", label, window->Name, (window->Active || window->WasActive), window);
if (ImGui::IsItemHovered() && window->WasActive)
ImGui::GetForegroundDrawList()->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
if (!open)
return;
ImGuiWindowFlags flags = window->Flags;
NodeDrawList(window, window->DrawList, "DrawList");
ImGui::BulletText("Pos: (%.1f,%.1f), Size: (%.1f,%.1f), ContentSize (%.1f,%.1f)", window->Pos.x, window->Pos.y, window->Size.x, window->Size.y, window->ContentSize.x, window->ContentSize.y);
ImGui::BulletText("Flags: 0x%08X (%s%s%s%s%s%s%s%s%s..)", flags,
(flags & ImGuiWindowFlags_ChildWindow) ? "Child " : "", (flags & ImGuiWindowFlags_Tooltip) ? "Tooltip " : "", (flags & ImGuiWindowFlags_Popup) ? "Popup " : "",
(flags & ImGuiWindowFlags_Modal) ? "Modal " : "", (flags & ImGuiWindowFlags_ChildMenu) ? "ChildMenu " : "", (flags & ImGuiWindowFlags_NoSavedSettings) ? "NoSavedSettings " : "",
(flags & ImGuiWindowFlags_NoMouseInputs)? "NoMouseInputs":"", (flags & ImGuiWindowFlags_NoNavInputs) ? "NoNavInputs" : "", (flags & ImGuiWindowFlags_AlwaysAutoResize) ? "AlwaysAutoResize" : "");
ImGui::BulletText("Scroll: (%.2f/%.2f,%.2f/%.2f) Scrollbar:%s%s", window->Scroll.x, window->ScrollMax.x, window->Scroll.y, window->ScrollMax.y, window->ScrollbarX ? "X" : "", window->ScrollbarY ? "Y" : "");
ImGui::BulletText("Active: %d/%d, WriteAccessed: %d, BeginOrderWithinContext: %d", window->Active, window->WasActive, window->WriteAccessed, (window->Active || window->WasActive) ? window->BeginOrderWithinContext : -1);
ImGui::BulletText("Appearing: %d, Hidden: %d (CanSkip %d Cannot %d), SkipItems: %d", window->Appearing, window->Hidden, window->HiddenFramesCanSkipItems, window->HiddenFramesCannotSkipItems, window->SkipItems);
ImGui::BulletText("NavLastIds: 0x%08X,0x%08X, NavLayerActiveMask: %X", window->NavLastIds[0], window->NavLastIds[1], window->DC.NavLayerActiveMask);
ImGui::BulletText("NavLastChildNavWindow: %s", window->NavLastChildNavWindow ? window->NavLastChildNavWindow->Name : "NULL");
if (!window->NavRectRel[0].IsInverted())
ImGui::BulletText("NavRectRel[0]: (%.1f,%.1f)(%.1f,%.1f)", window->NavRectRel[0].Min.x, window->NavRectRel[0].Min.y, window->NavRectRel[0].Max.x, window->NavRectRel[0].Max.y);
else
ImGui::BulletText("NavRectRel[0]: <None>");
if (window->RootWindow != window) NodeWindow(window->RootWindow, "RootWindow");
if (window->ParentWindow != NULL) NodeWindow(window->ParentWindow, "ParentWindow");
if (window->DC.ChildWindows.Size > 0) NodeWindows(window->DC.ChildWindows, "ChildWindows");
if (window->ColumnsStorage.Size > 0 && ImGui::TreeNode("Columns", "Columns sets (%d)", window->ColumnsStorage.Size))
{
for (int n = 0; n < window->ColumnsStorage.Size; n++)
NodeColumns(&window->ColumnsStorage[n]);
ImGui::TreePop();
}
NodeStorage(&window->StateStorage, "Storage");
ImGui::TreePop();
}
static void NodeTabBar(ImGuiTabBar* tab_bar)
{
// Standalone tab bars (not associated to docking/windows functionality) currently hold no discernible strings.
char buf[256];
char* p = buf;
const char* buf_end = buf + IM_ARRAYSIZE(buf);
p += ImFormatString(p, buf_end - p, "TabBar (%d tabs)%s", tab_bar->Tabs.Size, (tab_bar->PrevFrameVisible < ImGui::GetFrameCount() - 2) ? " *Inactive*" : "");
if (ImGui::TreeNode(tab_bar, "%s", buf))
{
for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
{
const ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
ImGui::PushID(tab);
if (ImGui::SmallButton("<")) { TabBarQueueChangeTabOrder(tab_bar, tab, -1); } ImGui::SameLine(0, 2);
if (ImGui::SmallButton(">")) { TabBarQueueChangeTabOrder(tab_bar, tab, +1); } ImGui::SameLine();
ImGui::Text("%02d%c Tab 0x%08X '%s'", tab_n, (tab->ID == tab_bar->SelectedTabId) ? '*' : ' ', tab->ID, (tab->NameOffset != -1) ? tab_bar->GetTabName(tab) : "");
ImGui::PopID();
}
ImGui::TreePop();
}
}
static void NodeStorage(ImGuiStorage* storage, const char* label)
{
if (!ImGui::TreeNode(label, "%s: %d entries, %d bytes", label, storage->Data.Size, storage->Data.size_in_bytes()))
return;
for (int n = 0; n < storage->Data.Size; n++)
{
const ImGuiStorage::ImGuiStoragePair& p = storage->Data[n];
ImGui::BulletText("Key 0x%08X Value { i: %d }", p.key, p.val_i); // Important: we currently don't store a type, real value may not be integer.
}
ImGui::TreePop();
}
};
Funcs::NodeWindows(g.Windows, "Windows");
//Funcs::NodeWindows(g.WindowsFocusOrder, "WindowsFocusOrder");
if (ImGui::TreeNode("DrawLists", "Active DrawLists (%d)", g.DrawDataBuilder.Layers[0].Size))
{
for (int i = 0; i < g.DrawDataBuilder.Layers[0].Size; i++)
Funcs::NodeDrawList(NULL, g.DrawDataBuilder.Layers[0][i], "DrawList");
ImGui::TreePop();
}
// Details for Popups
if (ImGui::TreeNode("Popups", "Popups (%d)", g.OpenPopupStack.Size))
{
for (int i = 0; i < g.OpenPopupStack.Size; i++)
{
ImGuiWindow* window = g.OpenPopupStack[i].Window;
ImGui::BulletText("PopupID: %08x, Window: '%s'%s%s", g.OpenPopupStack[i].PopupId, window ? window->Name : "NULL", window && (window->Flags & ImGuiWindowFlags_ChildWindow) ? " ChildWindow" : "", window && (window->Flags & ImGuiWindowFlags_ChildMenu) ? " ChildMenu" : "");
}
ImGui::TreePop();
}
// Details for TabBars
if (ImGui::TreeNode("TabBars", "Tab Bars (%d)", g.TabBars.GetSize()))
{
for (int n = 0; n < g.TabBars.GetSize(); n++)
Funcs::NodeTabBar(g.TabBars.GetByIndex(n));
ImGui::TreePop();
}
// Details for Tables
IM_UNUSED(trt_rects_names);
IM_UNUSED(show_tables_rects);
IM_UNUSED(show_tables_rect_type);
#ifdef IMGUI_HAS_TABLE
if (ImGui::TreeNode("Tables", "Tables (%d)", g.Tables.GetSize()))
{
for (int n = 0; n < g.Tables.GetSize(); n++)
Funcs::NodeTable(g.Tables.GetByIndex(n));
ImGui::TreePop();
}
#endif // #define IMGUI_HAS_TABLE
// Details for Docking
#ifdef IMGUI_HAS_DOCK
if (ImGui::TreeNode("Docking"))
{
ImGui::TreePop();
}
#endif // #define IMGUI_HAS_DOCK
// Misc Details
if (ImGui::TreeNode("Internal state"))
{
const char* input_source_names[] = { "None", "Mouse", "Nav", "NavKeyboard", "NavGamepad" }; IM_ASSERT(IM_ARRAYSIZE(input_source_names) == ImGuiInputSource_COUNT);
ImGui::Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL");
ImGui::Text("HoveredRootWindow: '%s'", g.HoveredRootWindow ? g.HoveredRootWindow->Name : "NULL");
ImGui::Text("HoveredId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d", g.HoveredId, g.HoveredIdPreviousFrame, g.HoveredIdTimer, g.HoveredIdAllowOverlap); // Data is "in-flight" so depending on when the Metrics window is called we may see current frame information or not
ImGui::Text("ActiveId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d, Source: %s", g.ActiveId, g.ActiveIdPreviousFrame, g.ActiveIdTimer, g.ActiveIdAllowOverlap, input_source_names[g.ActiveIdSource]);
ImGui::Text("ActiveIdWindow: '%s'", g.ActiveIdWindow ? g.ActiveIdWindow->Name : "NULL");
ImGui::Text("MovingWindow: '%s'", g.MovingWindow ? g.MovingWindow->Name : "NULL");
ImGui::Text("NavWindow: '%s'", g.NavWindow ? g.NavWindow->Name : "NULL");
ImGui::Text("NavId: 0x%08X, NavLayer: %d", g.NavId, g.NavLayer);
ImGui::Text("NavInputSource: %s", input_source_names[g.NavInputSource]);
ImGui::Text("NavActive: %d, NavVisible: %d", g.IO.NavActive, g.IO.NavVisible);
ImGui::Text("NavActivateId: 0x%08X, NavInputId: 0x%08X", g.NavActivateId, g.NavInputId);
ImGui::Text("NavDisableHighlight: %d, NavDisableMouseHover: %d", g.NavDisableHighlight, g.NavDisableMouseHover);
ImGui::Text("NavWindowingTarget: '%s'", g.NavWindowingTarget ? g.NavWindowingTarget->Name : "NULL");
ImGui::Text("DragDrop: %d, SourceId = 0x%08X, Payload \"%s\" (%d bytes)", g.DragDropActive, g.DragDropPayload.SourceId, g.DragDropPayload.DataType, g.DragDropPayload.DataSize);
ImGui::TreePop();
}
// Tools
if (ImGui::TreeNode("Tools"))
{
// The Item Picker tool is super useful to visually select an item and break into the call-stack of where it was submitted.
if (ImGui::Button("Item Picker.."))
ImGui::DebugStartItemPicker();
ImGui::SameLine();
MetricsHelpMarker("Will call the IM_DEBUG_BREAK() macro to break in debugger.\nWarning: If you don't have a debugger attached, this will probably crash.");
ImGui::Checkbox("Show windows begin order", &show_windows_begin_order);
ImGui::Checkbox("Show windows rectangles", &show_windows_rects);
ImGui::SameLine();
ImGui::SetNextItemWidth(ImGui::GetFontSize() * 12);
show_windows_rects |= ImGui::Combo("##show_windows_rect_type", &show_windows_rect_type, wrt_rects_names, WRT_Count, WRT_Count);
if (show_windows_rects && g.NavWindow)
{
ImGui::BulletText("'%s':", g.NavWindow->Name);
ImGui::Indent();
for (int rect_n = 0; rect_n < WRT_Count; rect_n++)
{
ImRect r = Funcs::GetWindowRect(g.NavWindow, rect_n);
ImGui::Text("(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), wrt_rects_names[rect_n]);
}
ImGui::Unindent();
}
ImGui::Checkbox("Show details when hovering ImDrawCmd node", &show_drawcmd_details);
ImGui::TreePop();
}
// Overlay: Display windows Rectangles and Begin Order
if (show_windows_rects || show_windows_begin_order)
{
for (int n = 0; n < g.Windows.Size; n++)
{
ImGuiWindow* window = g.Windows[n];
if (!window->WasActive)
continue;
ImDrawList* draw_list = GetForegroundDrawList(window);
if (show_windows_rects)
{
ImRect r = Funcs::GetWindowRect(window, show_windows_rect_type);
draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
}
if (show_windows_begin_order && !(window->Flags & ImGuiWindowFlags_ChildWindow))
{
char buf[32];
ImFormatString(buf, IM_ARRAYSIZE(buf), "%d", window->BeginOrderWithinContext);
float font_size = ImGui::GetFontSize();
draw_list->AddRectFilled(window->Pos, window->Pos + ImVec2(font_size, font_size), IM_COL32(200, 100, 100, 255));
draw_list->AddText(window->Pos, IM_COL32(255, 255, 255, 255), buf);
}
}
}
#ifdef IMGUI_HAS_TABLE
// Overlay: Display Tables Rectangles
if (show_tables_rects)
{
for (int table_n = 0; table_n < g.Tables.GetSize(); table_n++)
{
ImGuiTable* table = g.Tables.GetByIndex(table_n);
}
}
#endif // #define IMGUI_HAS_TABLE
#ifdef IMGUI_HAS_DOCK
// Overlay: Display Docking info
if (show_docking_nodes && g.IO.KeyCtrl)
{
}
#endif // #define IMGUI_HAS_DOCK
ImGui::End();
}
#else
void ImGui::ShowMetricsWindow(bool*) { }
#endif
//-----------------------------------------------------------------------------
// Include imgui_user.inl at the end of imgui.cpp to access private data/functions that aren't exposed.
// Prefer just including imgui_internal.h from your code rather than using this define. If a declaration is missing from imgui_internal.h add it or request it on the github.
#ifdef IMGUI_INCLUDE_IMGUI_USER_INL
#include "imgui_user.inl"
#endif
//-----------------------------------------------------------------------------
#endif // #ifndef IMGUI_DISABLE
|
// Copyright Microsoft Corporation
// Copyright GHI Electronics, LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "LPC24.h"
#define DACR (*(volatile unsigned long *)0xE006C000)
#define LPC24_DAC_PRECISION_BITS 10 // Number of Bits in the DAC Convertion
#define LPC24_DAC_MAX_VALUE (1<<LPC24_DAC_PRECISION_BITS)
///////////////////////////////////////////////////////////////////////////////
#define TOTAL_DAC_CONTROLLERS 1
static TinyCLR_Dac_Controller dacControllers[TOTAL_DAC_CONTROLLERS];
static TinyCLR_Api_Info dacApi[TOTAL_DAC_CONTROLLERS];
static const LPC24_Gpio_Pin dacPins[] = LPC24_DAC_PINS;
struct DacState {
bool isOpened[SIZEOF_ARRAY(dacPins)];
};
static DacState dacStates[TOTAL_DAC_CONTROLLERS];
const char* dacApiNames[TOTAL_DAC_CONTROLLERS] = {
"GHIElectronics.TinyCLR.NativeApis.LPC24.DacController\\0"
};
void LPC24_Dac_AddApi(const TinyCLR_Api_Manager* apiManager) {
for (int32_t i = 0; i < TOTAL_DAC_CONTROLLERS; i++) {
dacControllers[i].ApiInfo = &dacApi[i];
dacControllers[i].Acquire = &LPC24_Dac_Acquire;
dacControllers[i].Release = &LPC24_Dac_Release;
dacControllers[i].OpenChannel = &LPC24_Dac_OpenChannel;
dacControllers[i].CloseChannel = &LPC24_Dac_CloseChannel;
dacControllers[i].WriteValue = &LPC24_Dac_WriteValue;
dacControllers[i].GetMinValue = &LPC24_Dac_GetMinValue;
dacControllers[i].GetMaxValue = &LPC24_Dac_GetMaxValue;
dacControllers[i].GetResolutionInBits = &LPC24_Dac_GetResolutionInBits;
dacControllers[i].GetChannelCount = &LPC24_Dac_GetChannelCount;
dacApi[i].Author = "GHI Electronics, LLC";
dacApi[i].Name = dacApiNames[i];
dacApi[i].Type = TinyCLR_Api_Type::DacController;
dacApi[i].Version = 0;
dacApi[i].Implementation = &dacControllers[i];
dacApi[i].State = &dacStates[i];
apiManager->Add(apiManager, &dacApi[i]);
}
apiManager->SetDefaultName(apiManager, TinyCLR_Api_Type::DacController, dacApi[0].Name);
}
TinyCLR_Result LPC24_Dac_Acquire(const TinyCLR_Dac_Controller* self) {
if (self == nullptr)
return TinyCLR_Result::ArgumentNull;
return TinyCLR_Result::Success;
}
TinyCLR_Result LPC24_Dac_Release(const TinyCLR_Dac_Controller* self) {
if (self == nullptr)
return TinyCLR_Result::ArgumentNull;
return TinyCLR_Result::Success;
}
TinyCLR_Result LPC24_Dac_OpenChannel(const TinyCLR_Dac_Controller* self, uint32_t channel) {
if (channel >= LPC24_Dac_GetChannelCount(self))
return TinyCLR_Result::ArgumentOutOfRange;
if (!LPC24_GpioInternal_OpenPin(dacPins[channel].number))
return TinyCLR_Result::SharingViolation;
auto state = reinterpret_cast<DacState*>(self->ApiInfo->State);
LPC24_GpioInternal_ConfigurePin(dacPins[channel].number, LPC24_Gpio_Direction::Input, dacPins[channel].pinFunction, LPC24_Gpio_PinMode::Inactive);
DACR = (0 << 6); // This sets the initial starting voltage at 0
state->isOpened[channel] = true;
return TinyCLR_Result::Success;
}
TinyCLR_Result LPC24_Dac_CloseChannel(const TinyCLR_Dac_Controller* self, uint32_t channel) {
if (channel >= LPC24_Dac_GetChannelCount(self))
return TinyCLR_Result::ArgumentOutOfRange;
auto state = reinterpret_cast<DacState*>(self->ApiInfo->State);
if (state->isOpened[channel])
LPC24_GpioInternal_ClosePin(dacPins[channel].number);
state->isOpened[channel] = false;
return TinyCLR_Result::Success;
}
TinyCLR_Result LPC24_Dac_WriteValue(const TinyCLR_Dac_Controller* self, uint32_t channel, int32_t value) {
if (channel >= LPC24_Dac_GetChannelCount(self))
return TinyCLR_Result::ArgumentOutOfRange;
if (value > LPC24_DAC_MAX_VALUE) {
value = LPC24_DAC_MAX_VALUE;
}
if (value < 1) {
value = 1;
}
DACR = ((value - 1) << 6); // Sets voltage level between 0 and 1023.
return TinyCLR_Result::Success;
}
uint32_t LPC24_Dac_GetChannelCount(const TinyCLR_Dac_Controller* self) {
return SIZEOF_ARRAY(dacPins);
}
uint32_t LPC24_Dac_GetResolutionInBits(const TinyCLR_Dac_Controller* self) {
return LPC24_DAC_PRECISION_BITS;
}
int32_t LPC24_Dac_GetMinValue(const TinyCLR_Dac_Controller* self) {
return 0;
}
int32_t LPC24_Dac_GetMaxValue(const TinyCLR_Dac_Controller* self) {
return ((1 << LPC24_DAC_PRECISION_BITS) - 1);
}
void LPC24_Dac_Reset() {
for (auto c = 0; c < TOTAL_DAC_CONTROLLERS; c++) {
for (auto ch = 0; ch < LPC24_Dac_GetChannelCount(&dacControllers[c]); ch++) {
LPC24_Dac_CloseChannel(&dacControllers[c], ch);
dacStates[c].isOpened[ch] = false;
}
}
}
|
#include<bits/stdc++.h>
using namespace std;
// Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
class Solution {
public:
int length(ListNode* node){
int l = 0;
while(node){
node = node->next;
l++;
}
return l;
}
ListNode* reverse(ListNode* list){
ListNode *curr = list , *prev = NULL, *next_node = NULL;
while(curr){
next_node = curr->next;
curr->next = prev;
prev = curr;
curr = next_node;
}
return prev;
}
ListNode* addTwoNumbers(ListNode* node1, ListNode* node2) {
ListNode *l1 = node1 , *l2 = node2;
int len1 = length(l1) , len2 = length(l2);
if(len1<len2)
swap(l1,l2);
l1 = reverse(l1);
l2 = reverse(l2);
ListNode* li1 = l1;
int carry = 0;
ListNode* before = li1;
while(li1 && l2){
int sum = li1->val + l2->val + carry;
li1->val = (sum%10);
carry = sum/10;
before = li1;
li1 = li1->next;
l2 = l2->next;
}
while(li1) {
int sum = (li1->val+carry);
li1->val = sum%10;
carry = sum/10;
before = li1;
li1 = li1->next;
}
if(carry) {
ListNode* last = new ListNode(carry%10);
carry /= 10;
before->next = last;
before = before->next;
}
l1 = reverse(l1);
return l1;
}
};
|
//===- SemaChecking.cpp - Extra Semantic Checking -------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file implements extra semantic analysis beyond what is enforced
// by the C type system.
//
//===----------------------------------------------------------------------===//
#include "clang/AST/APValue.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Attr.h"
#include "clang/AST/AttrIterator.h"
#include "clang/AST/CharUnits.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclBase.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclObjC.h"
#include "clang/AST/DeclarationName.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/FormatString.h"
#include "clang/AST/NSAPI.h"
#include "clang/AST/NonTrivialTypeVisitor.h"
#include "clang/AST/OperationKinds.h"
#include "clang/AST/RecordLayout.h"
#include "clang/AST/Stmt.h"
#include "clang/AST/TemplateBase.h"
#include "clang/AST/Type.h"
#include "clang/AST/TypeLoc.h"
#include "clang/AST/UnresolvedSet.h"
#include "clang/Basic/AddressSpaces.h"
#include "clang/Basic/CharInfo.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/IdentifierTable.h"
#include "clang/Basic/LLVM.h"
#include "clang/Basic/LangOptions.h"
#include "clang/Basic/OpenCLOptions.h"
#include "clang/Basic/OperatorKinds.h"
#include "clang/Basic/PartialDiagnostic.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/Specifiers.h"
#include "clang/Basic/SyncScope.h"
#include "clang/Basic/TargetBuiltins.h"
#include "clang/Basic/TargetCXXABI.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Basic/TypeTraits.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/Ownership.h"
#include "clang/Sema/Scope.h"
#include "clang/Sema/ScopeInfo.h"
#include "clang/Sema/Sema.h"
#include "clang/Sema/SemaInternal.h"
#include "llvm/ADT/APFloat.h"
#include "llvm/ADT/APInt.h"
#include "llvm/ADT/APSInt.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/FoldingSet.h"
#include "llvm/ADT/None.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallBitVector.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/StringSet.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Support/AtomicOrdering.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/ConvertUTF.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/Locale.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/SaveAndRestore.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <limits>
#include <string>
#include <tuple>
#include <utility>
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->getEndLoc(), diag::err_typecheck_call_too_few_args)
<< 0 /*function call*/ << desiredArgCount << argCount
<< call->getSourceRange();
// Highlight all the excess arguments.
SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(),
call->getArg(argCount - 1)->getEndLoc());
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->getBeginLoc(), 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->getBeginLoc(), diag::err_builtin_annotation_second_arg)
<< StrArg->getSourceRange();
return true;
}
TheCall->setType(Ty);
return false;
}
static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
// We need at least one argument.
if (TheCall->getNumArgs() < 1) {
S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
<< 0 << 1 << TheCall->getNumArgs()
<< TheCall->getCallee()->getSourceRange();
return true;
}
// All arguments should be wide string literals.
for (Expr *Arg : TheCall->arguments()) {
auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
if (!Literal || !Literal->isWide()) {
S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
<< Arg->getSourceRange();
return true;
}
}
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->getBeginLoc());
if (ResultType.isNull())
return true;
TheCall->setArg(0, Arg.get());
TheCall->setType(ResultType);
return false;
}
/// Check the number of arguments and set the result type to
/// the argument type.
static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
if (checkArgCount(S, TheCall, 1))
return true;
TheCall->setType(TheCall->getArg(0)->getType());
return false;
}
/// Check that the value argument for __builtin_is_aligned(value, alignment) and
/// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
/// type (but not a function pointer) and that the alignment is a power-of-two.
static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
if (checkArgCount(S, TheCall, 2))
return true;
clang::Expr *Source = TheCall->getArg(0);
bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
auto IsValidIntegerType = [](QualType Ty) {
return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
};
QualType SrcTy = Source->getType();
// We should also be able to use it with arrays (but not functions!).
if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
SrcTy = S.Context.getDecayedType(SrcTy);
}
if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
SrcTy->isFunctionPointerType()) {
// FIXME: this is not quite the right error message since we don't allow
// floating point types, or member pointers.
S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
<< SrcTy;
return true;
}
clang::Expr *AlignOp = TheCall->getArg(1);
if (!IsValidIntegerType(AlignOp->getType())) {
S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)
<< AlignOp->getType();
return true;
}
Expr::EvalResult AlignResult;
unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;
// We can't check validity of alignment if it is value dependent.
if (!AlignOp->isValueDependent() &&
AlignOp->EvaluateAsInt(AlignResult, S.Context,
Expr::SE_AllowSideEffects)) {
llvm::APSInt AlignValue = AlignResult.Val.getInt();
llvm::APSInt MaxValue(
llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));
if (AlignValue < 1) {
S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;
return true;
}
if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {
S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)
<< MaxValue.toString(10);
return true;
}
if (!AlignValue.isPowerOf2()) {
S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
return true;
}
if (AlignValue == 1) {
S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
<< IsBooleanAlignBuiltin;
}
}
ExprResult SrcArg = S.PerformCopyInitialization(
InitializedEntity::InitializeParameter(S.Context, SrcTy, false),
SourceLocation(), Source);
if (SrcArg.isInvalid())
return true;
TheCall->setArg(0, SrcArg.get());
ExprResult AlignArg =
S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
S.Context, AlignOp->getType(), false),
SourceLocation(), AlignOp);
if (AlignArg.isInvalid())
return true;
TheCall->setArg(1, AlignArg.get());
// For align_up/align_down, the return type is the same as the (potentially
// decayed) argument type including qualifiers. For is_aligned(), the result
// is always bool.
TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
return false;
}
static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall,
unsigned BuiltinID) {
if (checkArgCount(S, TheCall, 3))
return true;
// First two arguments should be integers.
for (unsigned I = 0; I < 2; ++I) {
ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I));
if (Arg.isInvalid()) return true;
TheCall->setArg(I, Arg.get());
QualType Ty = Arg.get()->getType();
if (!Ty->isIntegerType()) {
S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
<< Ty << Arg.get()->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.
{
ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2));
if (Arg.isInvalid()) return true;
TheCall->setArg(2, Arg.get());
QualType Ty = Arg.get()->getType();
const auto *PtrTy = Ty->getAs<PointerType>();
if (!PtrTy ||
!PtrTy->getPointeeType()->isIntegerType() ||
PtrTy->getPointeeType().isConstQualified()) {
S.Diag(Arg.get()->getBeginLoc(),
diag::err_overflow_builtin_must_be_ptr_int)
<< Ty << Arg.get()->getSourceRange();
return true;
}
}
// Disallow signed ExtIntType args larger than 128 bits to mul function until
// we improve backend support.
if (BuiltinID == Builtin::BI__builtin_mul_overflow) {
for (unsigned I = 0; I < 3; ++I) {
const auto Arg = TheCall->getArg(I);
// Third argument will be a pointer.
auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType();
if (Ty->isExtIntType() && Ty->isSignedIntegerType() &&
S.getASTContext().getIntWidth(Ty) > 128)
return S.Diag(Arg->getBeginLoc(),
diag::err_overflow_builtin_ext_int_max_size)
<< 128;
}
}
return false;
}
static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
if (checkArgCount(S, BuiltinCall, 2))
return true;
SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
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;
}
namespace {
class EstimateSizeFormatHandler
: public analyze_format_string::FormatStringHandler {
size_t Size;
public:
EstimateSizeFormatHandler(StringRef Format)
: Size(std::min(Format.find(0), Format.size()) +
1 /* null byte always written by sprintf */) {}
bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
const char *, unsigned SpecifierLen) override {
const size_t FieldWidth = computeFieldWidth(FS);
const size_t Precision = computePrecision(FS);
// The actual format.
switch (FS.getConversionSpecifier().getKind()) {
// Just a char.
case analyze_format_string::ConversionSpecifier::cArg:
case analyze_format_string::ConversionSpecifier::CArg:
Size += std::max(FieldWidth, (size_t)1);
break;
// Just an integer.
case analyze_format_string::ConversionSpecifier::dArg:
case analyze_format_string::ConversionSpecifier::DArg:
case analyze_format_string::ConversionSpecifier::iArg:
case analyze_format_string::ConversionSpecifier::oArg:
case analyze_format_string::ConversionSpecifier::OArg:
case analyze_format_string::ConversionSpecifier::uArg:
case analyze_format_string::ConversionSpecifier::UArg:
case analyze_format_string::ConversionSpecifier::xArg:
case analyze_format_string::ConversionSpecifier::XArg:
Size += std::max(FieldWidth, Precision);
break;
// %g style conversion switches between %f or %e style dynamically.
// %f always takes less space, so default to it.
case analyze_format_string::ConversionSpecifier::gArg:
case analyze_format_string::ConversionSpecifier::GArg:
// Floating point number in the form '[+]ddd.ddd'.
case analyze_format_string::ConversionSpecifier::fArg:
case analyze_format_string::ConversionSpecifier::FArg:
Size += std::max(FieldWidth, 1 /* integer part */ +
(Precision ? 1 + Precision
: 0) /* period + decimal */);
break;
// Floating point number in the form '[-]d.ddde[+-]dd'.
case analyze_format_string::ConversionSpecifier::eArg:
case analyze_format_string::ConversionSpecifier::EArg:
Size +=
std::max(FieldWidth,
1 /* integer part */ +
(Precision ? 1 + Precision : 0) /* period + decimal */ +
1 /* e or E letter */ + 2 /* exponent */);
break;
// Floating point number in the form '[-]0xh.hhhhp±dd'.
case analyze_format_string::ConversionSpecifier::aArg:
case analyze_format_string::ConversionSpecifier::AArg:
Size +=
std::max(FieldWidth,
2 /* 0x */ + 1 /* integer part */ +
(Precision ? 1 + Precision : 0) /* period + decimal */ +
1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
break;
// Just a string.
case analyze_format_string::ConversionSpecifier::sArg:
case analyze_format_string::ConversionSpecifier::SArg:
Size += FieldWidth;
break;
// Just a pointer in the form '0xddd'.
case analyze_format_string::ConversionSpecifier::pArg:
Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
break;
// A plain percent.
case analyze_format_string::ConversionSpecifier::PercentArg:
Size += 1;
break;
default:
break;
}
Size += FS.hasPlusPrefix() || FS.hasSpacePrefix();
if (FS.hasAlternativeForm()) {
switch (FS.getConversionSpecifier().getKind()) {
default:
break;
// Force a leading '0'.
case analyze_format_string::ConversionSpecifier::oArg:
Size += 1;
break;
// Force a leading '0x'.
case analyze_format_string::ConversionSpecifier::xArg:
case analyze_format_string::ConversionSpecifier::XArg:
Size += 2;
break;
// Force a period '.' before decimal, even if precision is 0.
case analyze_format_string::ConversionSpecifier::aArg:
case analyze_format_string::ConversionSpecifier::AArg:
case analyze_format_string::ConversionSpecifier::eArg:
case analyze_format_string::ConversionSpecifier::EArg:
case analyze_format_string::ConversionSpecifier::fArg:
case analyze_format_string::ConversionSpecifier::FArg:
case analyze_format_string::ConversionSpecifier::gArg:
case analyze_format_string::ConversionSpecifier::GArg:
Size += (Precision ? 0 : 1);
break;
}
}
assert(SpecifierLen <= Size && "no underflow");
Size -= SpecifierLen;
return true;
}
size_t getSizeLowerBound() const { return Size; }
private:
static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
size_t FieldWidth = 0;
if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant)
FieldWidth = FW.getConstantAmount();
return FieldWidth;
}
static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
size_t Precision = 0;
// See man 3 printf for default precision value based on the specifier.
switch (FW.getHowSpecified()) {
case analyze_format_string::OptionalAmount::NotSpecified:
switch (FS.getConversionSpecifier().getKind()) {
default:
break;
case analyze_format_string::ConversionSpecifier::dArg: // %d
case analyze_format_string::ConversionSpecifier::DArg: // %D
case analyze_format_string::ConversionSpecifier::iArg: // %i
Precision = 1;
break;
case analyze_format_string::ConversionSpecifier::oArg: // %d
case analyze_format_string::ConversionSpecifier::OArg: // %D
case analyze_format_string::ConversionSpecifier::uArg: // %d
case analyze_format_string::ConversionSpecifier::UArg: // %D
case analyze_format_string::ConversionSpecifier::xArg: // %d
case analyze_format_string::ConversionSpecifier::XArg: // %D
Precision = 1;
break;
case analyze_format_string::ConversionSpecifier::fArg: // %f
case analyze_format_string::ConversionSpecifier::FArg: // %F
case analyze_format_string::ConversionSpecifier::eArg: // %e
case analyze_format_string::ConversionSpecifier::EArg: // %E
case analyze_format_string::ConversionSpecifier::gArg: // %g
case analyze_format_string::ConversionSpecifier::GArg: // %G
Precision = 6;
break;
case analyze_format_string::ConversionSpecifier::pArg: // %d
Precision = 1;
break;
}
break;
case analyze_format_string::OptionalAmount::Constant:
Precision = FW.getConstantAmount();
break;
default:
break;
}
return Precision;
}
};
} // namespace
/// Check a call to BuiltinID for buffer overflows. If BuiltinID is a
/// __builtin_*_chk function, then use the object size argument specified in the
/// source. Otherwise, infer the object size using __builtin_object_size.
void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
CallExpr *TheCall) {
// FIXME: There are some more useful checks we could be doing here:
// - Evaluate strlen of strcpy arguments, use as object size.
if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
isConstantEvaluated())
return;
unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true);
if (!BuiltinID)
return;
const TargetInfo &TI = getASTContext().getTargetInfo();
unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
unsigned DiagID = 0;
bool IsChkVariant = false;
Optional<llvm::APSInt> UsedSize;
unsigned SizeIndex, ObjectIndex;
switch (BuiltinID) {
default:
return;
case Builtin::BIsprintf:
case Builtin::BI__builtin___sprintf_chk: {
size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) {
if (!Format->isAscii() && !Format->isUTF8())
return;
StringRef FormatStrRef = Format->getString();
EstimateSizeFormatHandler H(FormatStrRef);
const char *FormatBytes = FormatStrRef.data();
const ConstantArrayType *T =
Context.getAsConstantArrayType(Format->getType());
assert(T && "String literal not of constant array type!");
size_t TypeSize = T->getSize().getZExtValue();
// In case there's a null byte somewhere.
size_t StrLen =
std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
if (!analyze_format_string::ParsePrintfString(
H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
Context.getTargetInfo(), false)) {
DiagID = diag::warn_fortify_source_format_overflow;
UsedSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
.extOrTrunc(SizeTypeWidth);
if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
IsChkVariant = true;
ObjectIndex = 2;
} else {
IsChkVariant = false;
ObjectIndex = 0;
}
break;
}
}
return;
}
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:
case Builtin::BI__builtin___memccpy_chk:
case Builtin::BI__builtin___mempcpy_chk: {
DiagID = diag::warn_builtin_chk_overflow;
IsChkVariant = true;
SizeIndex = TheCall->getNumArgs() - 2;
ObjectIndex = TheCall->getNumArgs() - 1;
break;
}
case Builtin::BI__builtin___snprintf_chk:
case Builtin::BI__builtin___vsnprintf_chk: {
DiagID = diag::warn_builtin_chk_overflow;
IsChkVariant = true;
SizeIndex = 1;
ObjectIndex = 3;
break;
}
case Builtin::BIstrncat:
case Builtin::BI__builtin_strncat:
case Builtin::BIstrncpy:
case Builtin::BI__builtin_strncpy:
case Builtin::BIstpncpy:
case Builtin::BI__builtin_stpncpy: {
// Whether these functions overflow depends on the runtime strlen of the
// string, not just the buffer size, so emitting the "always overflow"
// diagnostic isn't quite right. We should still diagnose passing a buffer
// size larger than the destination buffer though; this is a runtime abort
// in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
DiagID = diag::warn_fortify_source_size_mismatch;
SizeIndex = TheCall->getNumArgs() - 1;
ObjectIndex = 0;
break;
}
case Builtin::BImemcpy:
case Builtin::BI__builtin_memcpy:
case Builtin::BImemmove:
case Builtin::BI__builtin_memmove:
case Builtin::BImemset:
case Builtin::BI__builtin_memset:
case Builtin::BImempcpy:
case Builtin::BI__builtin_mempcpy: {
DiagID = diag::warn_fortify_source_overflow;
SizeIndex = TheCall->getNumArgs() - 1;
ObjectIndex = 0;
break;
}
case Builtin::BIsnprintf:
case Builtin::BI__builtin_snprintf:
case Builtin::BIvsnprintf:
case Builtin::BI__builtin_vsnprintf: {
DiagID = diag::warn_fortify_source_size_mismatch;
SizeIndex = 1;
ObjectIndex = 0;
break;
}
}
llvm::APSInt ObjectSize;
// For __builtin___*_chk, the object size is explicitly provided by the caller
// (usually using __builtin_object_size). Use that value to check this call.
if (IsChkVariant) {
Expr::EvalResult Result;
Expr *SizeArg = TheCall->getArg(ObjectIndex);
if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
return;
ObjectSize = Result.Val.getInt();
// Otherwise, try to evaluate an imaginary call to __builtin_object_size.
} else {
// If the parameter has a pass_object_size attribute, then we should use its
// (potentially) more strict checking mode. Otherwise, conservatively assume
// type 0.
int BOSType = 0;
if (const auto *POS =
FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>())
BOSType = POS->getType();
Expr *ObjArg = TheCall->getArg(ObjectIndex);
uint64_t Result;
if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
return;
// Get the object size in the target's size_t width.
ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
}
// Evaluate the number of bytes of the object that this call will use.
if (!UsedSize) {
Expr::EvalResult Result;
Expr *UsedSizeArg = TheCall->getArg(SizeIndex);
if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext()))
return;
UsedSize = Result.Val.getInt().extOrTrunc(SizeTypeWidth);
}
if (UsedSize.getValue().ule(ObjectSize))
return;
StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
// Skim off the details of whichever builtin was called to produce a better
// diagnostic, as it's unlikley that the user wrote the __builtin explicitly.
if (IsChkVariant) {
FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
FunctionName = FunctionName.drop_back(std::strlen("_chk"));
} else if (FunctionName.startswith("__builtin_")) {
FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
}
DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
PDiag(DiagID)
<< FunctionName << ObjectSize.toString(/*Radix=*/10)
<< UsedSize.getValue().toString(/*Radix=*/10));
}
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.inTemplateInstantiation())
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;
}
static inline bool isBlockPointer(Expr *Arg) {
return Arg->getType()->isBlockPointerType();
}
/// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
/// void*, which is a requirement of device side enqueue.
static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
const BlockPointerType *BPT =
cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
ArrayRef<QualType> Params =
BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes();
unsigned ArgCounter = 0;
bool IllegalParams = false;
// Iterate through the block parameters until either one is found that is not
// a local void*, or the block is valid.
for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
I != E; ++I, ++ArgCounter) {
if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
(*I)->getPointeeType().getQualifiers().getAddressSpace() !=
LangAS::opencl_local) {
// Get the location of the error. If a block literal has been passed
// (BlockExpr) then we can point straight to the offending argument,
// else we just point to the variable reference.
SourceLocation ErrorLoc;
if (isa<BlockExpr>(BlockArg)) {
BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
} else if (isa<DeclRefExpr>(BlockArg)) {
ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
}
S.Diag(ErrorLoc,
diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
IllegalParams = true;
}
}
return IllegalParams;
}
static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
<< 1 << Call->getDirectCallee() << "cl_khr_subgroups";
return true;
}
return false;
}
static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
if (checkArgCount(S, TheCall, 2))
return true;
if (checkOpenCLSubgroupExt(S, TheCall))
return true;
// First argument is an ndrange_t type.
Expr *NDRangeArg = TheCall->getArg(0);
if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
<< TheCall->getDirectCallee() << "'ndrange_t'";
return true;
}
Expr *BlockArg = TheCall->getArg(1);
if (!isBlockPointer(BlockArg)) {
S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
<< TheCall->getDirectCallee() << "block";
return true;
}
return checkOpenCLBlockArgs(S, BlockArg);
}
/// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
/// get_kernel_work_group_size
/// and get_kernel_preferred_work_group_size_multiple builtin functions.
static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
if (checkArgCount(S, TheCall, 1))
return true;
Expr *BlockArg = TheCall->getArg(0);
if (!isBlockPointer(BlockArg)) {
S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
<< TheCall->getDirectCallee() << "block";
return true;
}
return checkOpenCLBlockArgs(S, BlockArg);
}
/// Diagnose integer type and any valid implicit conversion to it.
static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
const QualType &IntType);
static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
unsigned Start, unsigned End) {
bool IllegalParams = false;
for (unsigned I = Start; I <= End; ++I)
IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
S.Context.getSizeType());
return IllegalParams;
}
/// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
/// 'local void*' parameter of passed block.
static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
Expr *BlockArg,
unsigned NumNonVarArgs) {
const BlockPointerType *BPT =
cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
unsigned NumBlockParams =
BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams();
unsigned TotalNumArgs = TheCall->getNumArgs();
// For each argument passed to the block, a corresponding uint needs to
// be passed to describe the size of the local memory.
if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
S.Diag(TheCall->getBeginLoc(),
diag::err_opencl_enqueue_kernel_local_size_args);
return true;
}
// Check that the sizes of the local memory are specified by integers.
return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
TotalNumArgs - 1);
}
/// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
/// overload formats specified in Table 6.13.17.1.
/// int enqueue_kernel(queue_t queue,
/// kernel_enqueue_flags_t flags,
/// const ndrange_t ndrange,
/// void (^block)(void))
/// int enqueue_kernel(queue_t queue,
/// kernel_enqueue_flags_t flags,
/// const ndrange_t ndrange,
/// uint num_events_in_wait_list,
/// clk_event_t *event_wait_list,
/// clk_event_t *event_ret,
/// void (^block)(void))
/// int enqueue_kernel(queue_t queue,
/// kernel_enqueue_flags_t flags,
/// const ndrange_t ndrange,
/// void (^block)(local void*, ...),
/// uint size0, ...)
/// int enqueue_kernel(queue_t queue,
/// kernel_enqueue_flags_t flags,
/// const ndrange_t ndrange,
/// uint num_events_in_wait_list,
/// clk_event_t *event_wait_list,
/// clk_event_t *event_ret,
/// void (^block)(local void*, ...),
/// uint size0, ...)
static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
unsigned NumArgs = TheCall->getNumArgs();
if (NumArgs < 4) {
S.Diag(TheCall->getBeginLoc(),
diag::err_typecheck_call_too_few_args_at_least)
<< 0 << 4 << NumArgs;
return true;
}
Expr *Arg0 = TheCall->getArg(0);
Expr *Arg1 = TheCall->getArg(1);
Expr *Arg2 = TheCall->getArg(2);
Expr *Arg3 = TheCall->getArg(3);
// First argument always needs to be a queue_t type.
if (!Arg0->getType()->isQueueT()) {
S.Diag(TheCall->getArg(0)->getBeginLoc(),
diag::err_opencl_builtin_expected_type)
<< TheCall->getDirectCallee() << S.Context.OCLQueueTy;
return true;
}
// Second argument always needs to be a kernel_enqueue_flags_t enum value.
if (!Arg1->getType()->isIntegerType()) {
S.Diag(TheCall->getArg(1)->getBeginLoc(),
diag::err_opencl_builtin_expected_type)
<< TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
return true;
}
// Third argument is always an ndrange_t type.
if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
S.Diag(TheCall->getArg(2)->getBeginLoc(),
diag::err_opencl_builtin_expected_type)
<< TheCall->getDirectCallee() << "'ndrange_t'";
return true;
}
// With four arguments, there is only one form that the function could be
// called in: no events and no variable arguments.
if (NumArgs == 4) {
// check that the last argument is the right block type.
if (!isBlockPointer(Arg3)) {
S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
<< TheCall->getDirectCallee() << "block";
return true;
}
// we have a block type, check the prototype
const BlockPointerType *BPT =
cast<BlockPointerType>(Arg3->getType().getCanonicalType());
if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) {
S.Diag(Arg3->getBeginLoc(),
diag::err_opencl_enqueue_kernel_blocks_no_args);
return true;
}
return false;
}
// we can have block + varargs.
if (isBlockPointer(Arg3))
return (checkOpenCLBlockArgs(S, Arg3) ||
checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
// last two cases with either exactly 7 args or 7 args and varargs.
if (NumArgs >= 7) {
// check common block argument.
Expr *Arg6 = TheCall->getArg(6);
if (!isBlockPointer(Arg6)) {
S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
<< TheCall->getDirectCallee() << "block";
return true;
}
if (checkOpenCLBlockArgs(S, Arg6))
return true;
// Forth argument has to be any integer type.
if (!Arg3->getType()->isIntegerType()) {
S.Diag(TheCall->getArg(3)->getBeginLoc(),
diag::err_opencl_builtin_expected_type)
<< TheCall->getDirectCallee() << "integer";
return true;
}
// check remaining common arguments.
Expr *Arg4 = TheCall->getArg(4);
Expr *Arg5 = TheCall->getArg(5);
// Fifth argument is always passed as a pointer to clk_event_t.
if (!Arg4->isNullPointerConstant(S.Context,
Expr::NPC_ValueDependentIsNotNull) &&
!Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
S.Diag(TheCall->getArg(4)->getBeginLoc(),
diag::err_opencl_builtin_expected_type)
<< TheCall->getDirectCallee()
<< S.Context.getPointerType(S.Context.OCLClkEventTy);
return true;
}
// Sixth argument is always passed as a pointer to clk_event_t.
if (!Arg5->isNullPointerConstant(S.Context,
Expr::NPC_ValueDependentIsNotNull) &&
!(Arg5->getType()->isPointerType() &&
Arg5->getType()->getPointeeType()->isClkEventT())) {
S.Diag(TheCall->getArg(5)->getBeginLoc(),
diag::err_opencl_builtin_expected_type)
<< TheCall->getDirectCallee()
<< S.Context.getPointerType(S.Context.OCLClkEventTy);
return true;
}
if (NumArgs == 7)
return false;
return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
}
// None of the specific case has been detected, give generic error
S.Diag(TheCall->getBeginLoc(),
diag::err_opencl_enqueue_kernel_incorrect_args);
return true;
}
/// 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->getBeginLoc(), 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->getBeginLoc(),
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->getBeginLoc(),
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->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
<< Call->getDirectCallee() << S.Context.getPointerType(EltTy)
<< ArgIdx->getType() << ArgIdx->getSourceRange();
return true;
}
return false;
}
// 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->getBeginLoc(), 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->getBeginLoc(), 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->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
<< Call->getDirectCallee() << Call->getSourceRange();
return true;
}
return false;
}
// 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->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
<< Call->getDirectCallee() << S.Context.UnsignedIntTy
<< Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
return true;
}
// 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.
Call->setType(S.Context.OCLReserveIDTy);
return false;
}
// 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->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
<< Call->getDirectCallee() << S.Context.OCLReserveIDTy
<< Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
return true;
}
return false;
}
// 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->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
<< Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
return true;
}
return false;
}
// OpenCL v2.0 s6.13.9 - Address space qualifier functions.
// Performs semantic analysis for the to_global/local/private call.
// \param S Reference to the semantic analyzer.
// \param BuiltinID ID of the builtin function.
// \param Call A pointer to the builtin call.
// \return True if a semantic error has been found, false otherwise.
static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
CallExpr *Call) {
if (checkArgCount(S, Call, 1))
return true;
auto RT = Call->getArg(0)->getType();
if (!RT->isPointerType() || RT->getPointeeType()
.getAddressSpace() == LangAS::opencl_constant) {
S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
<< Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
return true;
}
if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
S.Diag(Call->getArg(0)->getBeginLoc(),
diag::warn_opencl_generic_address_space_arg)
<< Call->getDirectCallee()->getNameInfo().getAsString()
<< Call->getArg(0)->getSourceRange();
}
RT = RT->getPointeeType();
auto Qual = RT.getQualifiers();
switch (BuiltinID) {
case Builtin::BIto_global:
Qual.setAddressSpace(LangAS::opencl_global);
break;
case Builtin::BIto_local:
Qual.setAddressSpace(LangAS::opencl_local);
break;
case Builtin::BIto_private:
Qual.setAddressSpace(LangAS::opencl_private);
break;
default:
llvm_unreachable("Invalid builtin function");
}
Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
RT.getUnqualifiedType(), Qual)));
return false;
}
static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
if (checkArgCount(S, TheCall, 1))
return ExprError();
// Compute __builtin_launder's parameter type from the argument.
// The parameter type is:
// * The type of the argument if it's not an array or function type,
// Otherwise,
// * The decayed argument type.
QualType ParamTy = [&]() {
QualType ArgTy = TheCall->getArg(0)->getType();
if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
return S.Context.getPointerType(Ty->getElementType());
if (ArgTy->isFunctionType()) {
return S.Context.getPointerType(ArgTy);
}
return ArgTy;
}();
TheCall->setType(ParamTy);
auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
if (!ParamTy->isPointerType())
return 0;
if (ParamTy->isFunctionPointerType())
return 1;
if (ParamTy->isVoidPointerType())
return 2;
return llvm::Optional<unsigned>{};
}();
if (DiagSelect.hasValue()) {
S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
<< DiagSelect.getValue() << TheCall->getSourceRange();
return ExprError();
}
// We either have an incomplete class type, or we have a class template
// whose instantiation has not been forced. Example:
//
// template <class T> struct Foo { T value; };
// Foo<int> *p = nullptr;
// auto *d = __builtin_launder(p);
if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
diag::err_incomplete_type))
return ExprError();
assert(ParamTy->getPointeeType()->isObjectType() &&
"Unhandled non-object pointer case");
InitializedEntity Entity =
InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
ExprResult Arg =
S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
if (Arg.isInvalid())
return ExprError();
TheCall->setArg(0, Arg.get());
return TheCall;
}
// Emit an error and return true if the current architecture is not in the list
// of supported architectures.
static bool
CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
llvm::Triple::ArchType CurArch =
S.getASTContext().getTargetInfo().getTriple().getArch();
if (llvm::is_contained(SupportedArchs, CurArch))
return false;
S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
<< TheCall->getSourceRange();
return true;
}
static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
SourceLocation CallSiteLoc);
bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
CallExpr *TheCall) {
switch (TI.getTriple().getArch()) {
default:
// Some builtins don't require additional checking, so just consider these
// acceptable.
return false;
case llvm::Triple::arm:
case llvm::Triple::armeb:
case llvm::Triple::thumb:
case llvm::Triple::thumbeb:
return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
case llvm::Triple::aarch64:
case llvm::Triple::aarch64_32:
case llvm::Triple::aarch64_be:
return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
case llvm::Triple::bpfeb:
case llvm::Triple::bpfel:
return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
case llvm::Triple::hexagon:
return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
case llvm::Triple::mips:
case llvm::Triple::mipsel:
case llvm::Triple::mips64:
case llvm::Triple::mips64el:
return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
case llvm::Triple::systemz:
return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
case llvm::Triple::x86:
case llvm::Triple::x86_64:
return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall);
case llvm::Triple::ppc:
case llvm::Triple::ppcle:
case llvm::Triple::ppc64:
case llvm::Triple::ppc64le:
return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
case llvm::Triple::amdgcn:
return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
}
}
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_ms_va_start:
case Builtin::BI__builtin_stdarg_start:
case Builtin::BI__builtin_va_start:
if (SemaBuiltinVAStart(BuiltinID, TheCall))
return ExprError();
break;
case Builtin::BI__va_start: {
switch (Context.getTargetInfo().getTriple().getArch()) {
case llvm::Triple::aarch64:
case llvm::Triple::arm:
case llvm::Triple::thumb:
if (SemaBuiltinVAStartARMMicrosoft(TheCall))
return ExprError();
break;
default:
if (SemaBuiltinVAStart(BuiltinID, TheCall))
return ExprError();
break;
}
break;
}
// The acquire, release, and no fence variants are ARM and AArch64 only.
case Builtin::BI_interlockedbittestandset_acq:
case Builtin::BI_interlockedbittestandset_rel:
case Builtin::BI_interlockedbittestandset_nf:
case Builtin::BI_interlockedbittestandreset_acq:
case Builtin::BI_interlockedbittestandreset_rel:
case Builtin::BI_interlockedbittestandreset_nf:
if (CheckBuiltinTargetSupport(
*this, BuiltinID, TheCall,
{llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
return ExprError();
break;
// The 64-bit bittest variants are x64, ARM, and AArch64 only.
case Builtin::BI_bittest64:
case Builtin::BI_bittestandcomplement64:
case Builtin::BI_bittestandreset64:
case Builtin::BI_bittestandset64:
case Builtin::BI_interlockedbittestandreset64:
case Builtin::BI_interlockedbittestandset64:
if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
{llvm::Triple::x86_64, llvm::Triple::arm,
llvm::Triple::thumb, llvm::Triple::aarch64}))
return ExprError();
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:
case Builtin::BI__builtin_signbit:
case Builtin::BI__builtin_signbitf:
case Builtin::BI__builtin_signbitl:
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__builtin_alloca_with_align:
if (SemaBuiltinAllocaWithAlign(TheCall))
return ExprError();
LLVM_FALLTHROUGH;
case Builtin::BI__builtin_alloca:
Diag(TheCall->getBeginLoc(), diag::warn_alloca)
<< TheCall->getDirectCallee();
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_dynamic_object_size:
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__builtin_classify_type:
if (checkArgCount(*this, TheCall, 1)) return true;
TheCall->setType(Context.IntTy);
break;
case Builtin::BI__builtin_complex:
if (SemaBuiltinComplex(TheCall))
return ExprError();
break;
case Builtin::BI__builtin_constant_p: {
if (checkArgCount(*this, TheCall, 1)) return true;
ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
if (Arg.isInvalid()) return true;
TheCall->setArg(0, Arg.get());
TheCall->setType(Context.IntTy);
break;
}
case Builtin::BI__builtin_launder:
return SemaBuiltinLaunder(*this, TheCall);
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__sync_synchronize:
Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
<< TheCall->getCallee()->getSourceRange();
break;
case Builtin::BI__builtin_nontemporal_load:
case Builtin::BI__builtin_nontemporal_store:
return SemaBuiltinNontemporalOverloaded(TheCallResult);
case Builtin::BI__builtin_memcpy_inline: {
clang::Expr *SizeOp = TheCall->getArg(2);
// We warn about copying to or from `nullptr` pointers when `size` is
// greater than 0. When `size` is value dependent we cannot evaluate its
// value so we bail out.
if (SizeOp->isValueDependent())
break;
if (!SizeOp->EvaluateKnownConstInt(Context).isNullValue()) {
CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
}
break;
}
#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__annotation:
if (SemaBuiltinMSVCAnnotation(*this, TheCall))
return ExprError();
break;
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_is_aligned:
case Builtin::BI__builtin_align_up:
case Builtin::BI__builtin_align_down:
if (SemaBuiltinAlignment(*this, TheCall, BuiltinID))
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, BuiltinID))
return ExprError();
break;
case Builtin::BI__builtin_operator_new:
case Builtin::BI__builtin_operator_delete: {
bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
ExprResult Res =
SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
if (Res.isInvalid())
CorrectDelayedTyposInExpr(TheCallResult.get());
return Res;
}
case Builtin::BI__builtin_dump_struct: {
// We first want to ensure we are called with 2 arguments
if (checkArgCount(*this, TheCall, 2))
return ExprError();
// Ensure that the first argument is of type 'struct XX *'
const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
const QualType PtrArgType = PtrArg->getType();
if (!PtrArgType->isPointerType() ||
!PtrArgType->getPointeeType()->isRecordType()) {
Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
<< PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
<< "structure pointer";
return ExprError();
}
// Ensure that the second argument is of type 'FunctionType'
const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
const QualType FnPtrArgType = FnPtrArg->getType();
if (!FnPtrArgType->isPointerType()) {
Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
<< FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
<< FnPtrArgType << "'int (*)(const char *, ...)'";
return ExprError();
}
const auto *FuncType =
FnPtrArgType->getPointeeType()->getAs<FunctionType>();
if (!FuncType) {
Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
<< FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
<< FnPtrArgType << "'int (*)(const char *, ...)'";
return ExprError();
}
if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
if (!FT->getNumParams()) {
Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
<< FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
<< 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
return ExprError();
}
QualType PT = FT->getParamType(0);
if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
!PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
!PT->getPointeeType().isConstQualified()) {
Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
<< FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
<< 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
return ExprError();
}
}
TheCall->setType(Context.IntTy);
break;
}
case Builtin::BI__builtin_expect_with_probability: {
// We first want to ensure we are called with 3 arguments
if (checkArgCount(*this, TheCall, 3))
return ExprError();
// then check probability is constant float in range [0.0, 1.0]
const Expr *ProbArg = TheCall->getArg(2);
SmallVector<PartialDiagnosticAt, 8> Notes;
Expr::EvalResult Eval;
Eval.Diag = &Notes;
if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
!Eval.Val.isFloat()) {
Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
<< ProbArg->getSourceRange();
for (const PartialDiagnosticAt &PDiag : Notes)
Diag(PDiag.first, PDiag.second);
return ExprError();
}
llvm::APFloat Probability = Eval.Val.getFloat();
bool LoseInfo = false;
Probability.convert(llvm::APFloat::IEEEdouble(),
llvm::RoundingMode::Dynamic, &LoseInfo);
if (!(Probability >= llvm::APFloat(0.0) &&
Probability <= llvm::APFloat(1.0))) {
Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
<< ProbArg->getSourceRange();
return ExprError();
}
break;
}
case Builtin::BI__builtin_preserve_access_index:
if (SemaBuiltinPreserveAI(*this, TheCall))
return ExprError();
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->getBeginLoc(),
Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
TheCall))
return ExprError();
TheCall->setType(Context.VoidPtrTy);
break;
// OpenCL v2.0, s6.13.16 - Pipe functions
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:
if (SemaBuiltinReserveRWPipe(*this, TheCall))
return ExprError();
break;
case Builtin::BIsub_group_reserve_read_pipe:
case Builtin::BIsub_group_reserve_write_pipe:
if (checkOpenCLSubgroupExt(*this, TheCall) ||
SemaBuiltinReserveRWPipe(*this, TheCall))
return ExprError();
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:
if (SemaBuiltinCommitRWPipe(*this, TheCall))
return ExprError();
break;
case Builtin::BIsub_group_commit_read_pipe:
case Builtin::BIsub_group_commit_write_pipe:
if (checkOpenCLSubgroupExt(*this, TheCall) ||
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;
case Builtin::BIto_global:
case Builtin::BIto_local:
case Builtin::BIto_private:
if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
return ExprError();
break;
// OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
case Builtin::BIenqueue_kernel:
if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
return ExprError();
break;
case Builtin::BIget_kernel_work_group_size:
case Builtin::BIget_kernel_preferred_work_group_size_multiple:
if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
return ExprError();
break;
case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
case Builtin::BIget_kernel_sub_group_count_for_ndrange:
if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
return ExprError();
break;
case Builtin::BI__builtin_os_log_format:
Cleanup.setExprNeedsCleanups(true);
LLVM_FALLTHROUGH;
case Builtin::BI__builtin_os_log_format_buffer_size:
if (SemaBuiltinOSLogFormat(TheCall))
return ExprError();
break;
case Builtin::BI__builtin_frame_address:
case Builtin::BI__builtin_return_address: {
if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
return ExprError();
// -Wframe-address warning if non-zero passed to builtin
// return/frame address.
Expr::EvalResult Result;
if (!TheCall->getArg(0)->isValueDependent() &&
TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
Result.Val.getInt() != 0)
Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
<< ((BuiltinID == Builtin::BI__builtin_return_address)
? "__builtin_return_address"
: "__builtin_frame_address")
<< TheCall->getSourceRange();
break;
}
case Builtin::BI__builtin_matrix_transpose:
return SemaBuiltinMatrixTranspose(TheCall, TheCallResult);
case Builtin::BI__builtin_matrix_column_major_load:
return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
case Builtin::BI__builtin_matrix_column_major_store:
return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
case Builtin::BI_Dynamic_check: {
// This disables any semantic analysis (in particular, errors or warnings)
// if Checked C is not enabled
if (!getLangOpts().CheckedC)
break;
Expr *Conditional = TheCall->getArg(0);
if (!CheckIsNonModifying(Conditional, NMC_Dynamic_Check))
return ExprError();
WarnDynamicCheckAlwaysFails(Conditional);
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)) {
if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
assert(Context.getAuxTargetInfo() &&
"Aux Target Builtin, but not an aux target?");
if (CheckTSBuiltinFunctionCall(
*Context.getAuxTargetInfo(),
Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
return ExprError();
} else {
if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
TheCall))
return ExprError();
}
}
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;
case NeonTypeFlags::BFloat16:
assert(!shift && "cannot shift float types!");
return (4 << 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;
case NeonTypeFlags::BFloat16:
return Context.BFloat16Ty;
}
llvm_unreachable("Invalid NeonTypeFlag!");
}
bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
// Range check SVE intrinsics that take immediate values.
SmallVector<std::tuple<int,int,int>, 3> ImmChecks;
switch (BuiltinID) {
default:
return false;
#define GET_SVE_IMMEDIATE_CHECK
#include "clang/Basic/arm_sve_sema_rangechecks.inc"
#undef GET_SVE_IMMEDIATE_CHECK
}
// Perform all the immediate checks for this builtin call.
bool HasError = false;
for (auto &I : ImmChecks) {
int ArgNum, CheckTy, ElementSizeInBits;
std::tie(ArgNum, CheckTy, ElementSizeInBits) = I;
typedef bool(*OptionSetCheckFnTy)(int64_t Value);
// Function that checks whether the operand (ArgNum) is an immediate
// that is one of the predefined values.
auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm,
int ErrDiag) -> bool {
// 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.
llvm::APSInt Imm;
if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm))
return true;
if (!CheckImm(Imm.getSExtValue()))
return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange();
return false;
};
switch ((SVETypeFlags::ImmCheckType)CheckTy) {
case SVETypeFlags::ImmCheck0_31:
if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31))
HasError = true;
break;
case SVETypeFlags::ImmCheck0_13:
if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13))
HasError = true;
break;
case SVETypeFlags::ImmCheck1_16:
if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16))
HasError = true;
break;
case SVETypeFlags::ImmCheck0_7:
if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7))
HasError = true;
break;
case SVETypeFlags::ImmCheckExtract:
if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
(2048 / ElementSizeInBits) - 1))
HasError = true;
break;
case SVETypeFlags::ImmCheckShiftRight:
if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits))
HasError = true;
break;
case SVETypeFlags::ImmCheckShiftRightNarrow:
if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1,
ElementSizeInBits / 2))
HasError = true;
break;
case SVETypeFlags::ImmCheckShiftLeft:
if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
ElementSizeInBits - 1))
HasError = true;
break;
case SVETypeFlags::ImmCheckLaneIndex:
if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
(128 / (1 * ElementSizeInBits)) - 1))
HasError = true;
break;
case SVETypeFlags::ImmCheckLaneIndexCompRotate:
if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
(128 / (2 * ElementSizeInBits)) - 1))
HasError = true;
break;
case SVETypeFlags::ImmCheckLaneIndexDot:
if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
(128 / (4 * ElementSizeInBits)) - 1))
HasError = true;
break;
case SVETypeFlags::ImmCheckComplexRot90_270:
if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; },
diag::err_rotation_argument_to_cadd))
HasError = true;
break;
case SVETypeFlags::ImmCheckComplexRotAll90:
if (CheckImmediateInSet(
[](int64_t V) {
return V == 0 || V == 90 || V == 180 || V == 270;
},
diag::err_rotation_argument_to_cmla))
HasError = true;
break;
case SVETypeFlags::ImmCheck0_1:
if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1))
HasError = true;
break;
case SVETypeFlags::ImmCheck0_2:
if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2))
HasError = true;
break;
case SVETypeFlags::ImmCheck0_3:
if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3))
HasError = true;
break;
}
}
return HasError;
}
bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI,
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"
#include "clang/Basic/arm_fp16.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->getBeginLoc(), 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 = TI.getTriple().getArch();
bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
Arch == llvm::Triple::aarch64_32 ||
Arch == llvm::Triple::aarch64_be;
bool IsInt64Long = TI.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->getBeginLoc(), 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"
#include "clang/Basic/arm_fp16.inc"
#undef GET_NEON_IMMEDIATE_CHECK
}
return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
}
bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
switch (BuiltinID) {
default:
return false;
#include "clang/Basic/arm_mve_builtin_sema.inc"
}
}
bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
CallExpr *TheCall) {
bool Err = false;
switch (BuiltinID) {
default:
return false;
#include "clang/Basic/arm_cde_builtin_sema.inc"
}
if (Err)
return true;
return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true);
}
bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI,
const Expr *CoprocArg, bool WantCDE) {
if (isConstantEvaluated())
return false;
// We can't check the value of a dependent argument.
if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent())
return false;
llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context);
int64_t CoprocNo = CoprocNoAP.getExtValue();
assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative");
uint32_t CDECoprocMask = TI.getARMCDECoprocMask();
bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo));
if (IsCDECoproc != WantCDE)
return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc)
<< (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange();
return false;
}
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->getBeginLoc(), 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->getBeginLoc(), 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->getBeginLoc(), 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->getBeginLoc(), 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->getBeginLoc(), 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(const TargetInfo &TI, unsigned BuiltinID,
CallExpr *TheCall) {
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(TI, BuiltinID, TheCall))
return true;
if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
return true;
if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall))
return true;
// For intrinsics which take an immediate value as part of the instruction,
// range check them here.
// FIXME: VFP Intrinsics should error if VFP not present.
switch (BuiltinID) {
default: return false;
case ARM::BI__builtin_arm_ssat:
return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
case ARM::BI__builtin_arm_usat:
return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
case ARM::BI__builtin_arm_ssat16:
return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
case ARM::BI__builtin_arm_usat16:
return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
case ARM::BI__builtin_arm_vcvtr_f:
case ARM::BI__builtin_arm_vcvtr_d:
return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
case ARM::BI__builtin_arm_dmb:
case ARM::BI__builtin_arm_dsb:
case ARM::BI__builtin_arm_isb:
case ARM::BI__builtin_arm_dbg:
return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
case ARM::BI__builtin_arm_cdp:
case ARM::BI__builtin_arm_cdp2:
case ARM::BI__builtin_arm_mcr:
case ARM::BI__builtin_arm_mcr2:
case ARM::BI__builtin_arm_mrc:
case ARM::BI__builtin_arm_mrc2:
case ARM::BI__builtin_arm_mcrr:
case ARM::BI__builtin_arm_mcrr2:
case ARM::BI__builtin_arm_mrrc:
case ARM::BI__builtin_arm_mrrc2:
case ARM::BI__builtin_arm_ldc:
case ARM::BI__builtin_arm_ldcl:
case ARM::BI__builtin_arm_ldc2:
case ARM::BI__builtin_arm_ldc2l:
case ARM::BI__builtin_arm_stc:
case ARM::BI__builtin_arm_stcl:
case ARM::BI__builtin_arm_stc2:
case ARM::BI__builtin_arm_stc2l:
return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) ||
CheckARMCoprocessorImmediate(TI, TheCall->getArg(0),
/*WantCDE*/ false);
}
}
bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI,
unsigned BuiltinID,
CallExpr *TheCall) {
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);
// Memory Tagging Extensions (MTE) Intrinsics
if (BuiltinID == AArch64::BI__builtin_arm_irg ||
BuiltinID == AArch64::BI__builtin_arm_addg ||
BuiltinID == AArch64::BI__builtin_arm_gmi ||
BuiltinID == AArch64::BI__builtin_arm_ldg ||
BuiltinID == AArch64::BI__builtin_arm_stg ||
BuiltinID == AArch64::BI__builtin_arm_subp) {
return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
}
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);
// Only check the valid encoding range. Any constant in this range would be
// converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
// an exception for incorrect registers. This matches MSVC behavior.
if (BuiltinID == AArch64::BI_ReadStatusReg ||
BuiltinID == AArch64::BI_WriteStatusReg)
return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
if (BuiltinID == AArch64::BI__getReg)
return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
return true;
if (CheckSVEBuiltinFunctionCall(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;
case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
}
return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
}
static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) {
if (Arg->getType()->getAsPlaceholderType())
return false;
// The first argument needs to be a record field access.
// If it is an array element access, we delay decision
// to BPF backend to check whether the access is a
// field access or not.
return (Arg->IgnoreParens()->getObjectKind() == OK_BitField ||
dyn_cast<MemberExpr>(Arg->IgnoreParens()) ||
dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens()));
}
static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S,
QualType VectorTy, QualType EltTy) {
QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType();
if (!Context.hasSameType(VectorEltTy, EltTy)) {
S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types)
<< Call->getSourceRange() << VectorEltTy << EltTy;
return false;
}
return true;
}
static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) {
QualType ArgType = Arg->getType();
if (ArgType->getAsPlaceholderType())
return false;
// for TYPE_EXISTENCE/TYPE_SIZEOF reloc type
// format:
// 1. __builtin_preserve_type_info(*(<type> *)0, flag);
// 2. <type> var;
// __builtin_preserve_type_info(var, flag);
if (!dyn_cast<DeclRefExpr>(Arg->IgnoreParens()) &&
!dyn_cast<UnaryOperator>(Arg->IgnoreParens()))
return false;
// Typedef type.
if (ArgType->getAs<TypedefType>())
return true;
// Record type or Enum type.
const Type *Ty = ArgType->getUnqualifiedDesugaredType();
if (const auto *RT = Ty->getAs<RecordType>()) {
if (!RT->getDecl()->getDeclName().isEmpty())
return true;
} else if (const auto *ET = Ty->getAs<EnumType>()) {
if (!ET->getDecl()->getDeclName().isEmpty())
return true;
}
return false;
}
static bool isValidBPFPreserveEnumValueArg(Expr *Arg) {
QualType ArgType = Arg->getType();
if (ArgType->getAsPlaceholderType())
return false;
// for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type
// format:
// __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>,
// flag);
const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens());
if (!UO)
return false;
const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr());
if (!CE || CE->getCastKind() != CK_IntegralToPointer)
return false;
// The integer must be from an EnumConstantDecl.
const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr());
if (!DR)
return false;
const EnumConstantDecl *Enumerator =
dyn_cast<EnumConstantDecl>(DR->getDecl());
if (!Enumerator)
return false;
// The type must be EnumType.
const Type *Ty = ArgType->getUnqualifiedDesugaredType();
const auto *ET = Ty->getAs<EnumType>();
if (!ET)
return false;
// The enum value must be supported.
for (auto *EDI : ET->getDecl()->enumerators()) {
if (EDI == Enumerator)
return true;
}
return false;
}
bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
CallExpr *TheCall) {
assert((BuiltinID == BPF::BI__builtin_preserve_field_info ||
BuiltinID == BPF::BI__builtin_btf_type_id ||
BuiltinID == BPF::BI__builtin_preserve_type_info ||
BuiltinID == BPF::BI__builtin_preserve_enum_value) &&
"unexpected BPF builtin");
if (checkArgCount(*this, TheCall, 2))
return true;
// The second argument needs to be a constant int
Expr *Arg = TheCall->getArg(1);
Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context);
diag::kind kind;
if (!Value) {
if (BuiltinID == BPF::BI__builtin_preserve_field_info)
kind = diag::err_preserve_field_info_not_const;
else if (BuiltinID == BPF::BI__builtin_btf_type_id)
kind = diag::err_btf_type_id_not_const;
else if (BuiltinID == BPF::BI__builtin_preserve_type_info)
kind = diag::err_preserve_type_info_not_const;
else
kind = diag::err_preserve_enum_value_not_const;
Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange();
return true;
}
// The first argument
Arg = TheCall->getArg(0);
bool InvalidArg = false;
bool ReturnUnsignedInt = true;
if (BuiltinID == BPF::BI__builtin_preserve_field_info) {
if (!isValidBPFPreserveFieldInfoArg(Arg)) {
InvalidArg = true;
kind = diag::err_preserve_field_info_not_field;
}
} else if (BuiltinID == BPF::BI__builtin_preserve_type_info) {
if (!isValidBPFPreserveTypeInfoArg(Arg)) {
InvalidArg = true;
kind = diag::err_preserve_type_info_invalid;
}
} else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) {
if (!isValidBPFPreserveEnumValueArg(Arg)) {
InvalidArg = true;
kind = diag::err_preserve_enum_value_invalid;
}
ReturnUnsignedInt = false;
} else if (BuiltinID == BPF::BI__builtin_btf_type_id) {
ReturnUnsignedInt = false;
}
if (InvalidArg) {
Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange();
return true;
}
if (ReturnUnsignedInt)
TheCall->setType(Context.UnsignedIntTy);
else
TheCall->setType(Context.UnsignedLongTy);
return false;
}
bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
struct ArgInfo {
uint8_t OpNum;
bool IsSigned;
uint8_t BitWidth;
uint8_t Align;
};
struct BuiltinInfo {
unsigned BuiltinID;
ArgInfo Infos[2];
};
static BuiltinInfo Infos[] = {
{ Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} },
{ Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} },
{ Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} },
{ Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 1 }} },
{ Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} },
{ Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} },
{ Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} },
{ Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} },
{ Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} },
{ Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} },
{ Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} },
{ Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} },
{ Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} },
{ Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} },
{ Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} },
{ Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} },
{ Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} },
{ Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} },
{ Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} },
{ Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
{{ 1, false, 6, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
{{ 1, false, 5, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 },
{ 2, false, 5, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 },
{ 2, false, 6, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 },
{ 3, false, 5, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 },
{ 3, false, 6, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
{{ 2, false, 4, 0 },
{ 3, false, 5, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
{{ 2, false, 4, 0 },
{ 3, false, 5, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
{{ 2, false, 4, 0 },
{ 3, false, 5, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
{{ 2, false, 4, 0 },
{ 3, false, 5, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 },
{ 2, false, 5, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 },
{ 2, false, 6, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
{{ 1, false, 4, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
{{ 1, false, 4, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
{{ 3, false, 1, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
{{ 3, false, 1, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} },
{ Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
{{ 3, false, 1, 0 }} },
};
// Use a dynamically initialized static to sort the table exactly once on
// first run.
static const bool SortOnce =
(llvm::sort(Infos,
[](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
return LHS.BuiltinID < RHS.BuiltinID;
}),
true);
(void)SortOnce;
const BuiltinInfo *F = llvm::partition_point(
Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
return false;
bool Error = false;
for (const ArgInfo &A : F->Infos) {
// Ignore empty ArgInfo elements.
if (A.BitWidth == 0)
continue;
int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
if (!A.Align) {
Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
} else {
unsigned M = 1 << A.Align;
Min *= M;
Max *= M;
Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
}
}
return Error;
}
bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
CallExpr *TheCall) {
return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
}
bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI,
unsigned BuiltinID, CallExpr *TheCall) {
return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) ||
CheckMipsBuiltinArgument(BuiltinID, TheCall);
}
bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
CallExpr *TheCall) {
if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
BuiltinID <= Mips::BI__builtin_mips_lwx) {
if (!TI.hasFeature("dsp"))
return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
}
if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
if (!TI.hasFeature("dspr2"))
return Diag(TheCall->getBeginLoc(),
diag::err_mips_builtin_requires_dspr2);
}
if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
BuiltinID <= Mips::BI__builtin_msa_xori_b) {
if (!TI.hasFeature("msa"))
return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
}
return false;
}
// CheckMipsBuiltinArgument - Checks the constant value passed to the
// intrinsic is correct. The switch statement is ordered by DSP, MSA. The
// ordering for DSP is unspecified. MSA is ordered by the data format used
// by the underlying instruction i.e., df/m, df/n and then by size.
//
// FIXME: The size tests here should instead be tablegen'd along with the
// definitions from include/clang/Basic/BuiltinsMips.def.
// FIXME: GCC is strict on signedness for some of these intrinsics, we should
// be too.
bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
unsigned i = 0, l = 0, u = 0, m = 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;
// MSA intrinsics. Instructions (which the intrinsics maps to) which use the
// df/m field.
// These intrinsics take an unsigned 3 bit immediate.
case Mips::BI__builtin_msa_bclri_b:
case Mips::BI__builtin_msa_bnegi_b:
case Mips::BI__builtin_msa_bseti_b:
case Mips::BI__builtin_msa_sat_s_b:
case Mips::BI__builtin_msa_sat_u_b:
case Mips::BI__builtin_msa_slli_b:
case Mips::BI__builtin_msa_srai_b:
case Mips::BI__builtin_msa_srari_b:
case Mips::BI__builtin_msa_srli_b:
case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
case Mips::BI__builtin_msa_binsli_b:
case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
// These intrinsics take an unsigned 4 bit immediate.
case Mips::BI__builtin_msa_bclri_h:
case Mips::BI__builtin_msa_bnegi_h:
case Mips::BI__builtin_msa_bseti_h:
case Mips::BI__builtin_msa_sat_s_h:
case Mips::BI__builtin_msa_sat_u_h:
case Mips::BI__builtin_msa_slli_h:
case Mips::BI__builtin_msa_srai_h:
case Mips::BI__builtin_msa_srari_h:
case Mips::BI__builtin_msa_srli_h:
case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
case Mips::BI__builtin_msa_binsli_h:
case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
// These intrinsics take an unsigned 5 bit immediate.
// The first block of intrinsics actually have an unsigned 5 bit field,
// not a df/n field.
case Mips::BI__builtin_msa_cfcmsa:
case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
case Mips::BI__builtin_msa_clei_u_b:
case Mips::BI__builtin_msa_clei_u_h:
case Mips::BI__builtin_msa_clei_u_w:
case Mips::BI__builtin_msa_clei_u_d:
case Mips::BI__builtin_msa_clti_u_b:
case Mips::BI__builtin_msa_clti_u_h:
case Mips::BI__builtin_msa_clti_u_w:
case Mips::BI__builtin_msa_clti_u_d:
case Mips::BI__builtin_msa_maxi_u_b:
case Mips::BI__builtin_msa_maxi_u_h:
case Mips::BI__builtin_msa_maxi_u_w:
case Mips::BI__builtin_msa_maxi_u_d:
case Mips::BI__builtin_msa_mini_u_b:
case Mips::BI__builtin_msa_mini_u_h:
case Mips::BI__builtin_msa_mini_u_w:
case Mips::BI__builtin_msa_mini_u_d:
case Mips::BI__builtin_msa_addvi_b:
case Mips::BI__builtin_msa_addvi_h:
case Mips::BI__builtin_msa_addvi_w:
case Mips::BI__builtin_msa_addvi_d:
case Mips::BI__builtin_msa_bclri_w:
case Mips::BI__builtin_msa_bnegi_w:
case Mips::BI__builtin_msa_bseti_w:
case Mips::BI__builtin_msa_sat_s_w:
case Mips::BI__builtin_msa_sat_u_w:
case Mips::BI__builtin_msa_slli_w:
case Mips::BI__builtin_msa_srai_w:
case Mips::BI__builtin_msa_srari_w:
case Mips::BI__builtin_msa_srli_w:
case Mips::BI__builtin_msa_srlri_w:
case Mips::BI__builtin_msa_subvi_b:
case Mips::BI__builtin_msa_subvi_h:
case Mips::BI__builtin_msa_subvi_w:
case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
case Mips::BI__builtin_msa_binsli_w:
case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
// These intrinsics take an unsigned 6 bit immediate.
case Mips::BI__builtin_msa_bclri_d:
case Mips::BI__builtin_msa_bnegi_d:
case Mips::BI__builtin_msa_bseti_d:
case Mips::BI__builtin_msa_sat_s_d:
case Mips::BI__builtin_msa_sat_u_d:
case Mips::BI__builtin_msa_slli_d:
case Mips::BI__builtin_msa_srai_d:
case Mips::BI__builtin_msa_srari_d:
case Mips::BI__builtin_msa_srli_d:
case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
case Mips::BI__builtin_msa_binsli_d:
case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
// These intrinsics take a signed 5 bit immediate.
case Mips::BI__builtin_msa_ceqi_b:
case Mips::BI__builtin_msa_ceqi_h:
case Mips::BI__builtin_msa_ceqi_w:
case Mips::BI__builtin_msa_ceqi_d:
case Mips::BI__builtin_msa_clti_s_b:
case Mips::BI__builtin_msa_clti_s_h:
case Mips::BI__builtin_msa_clti_s_w:
case Mips::BI__builtin_msa_clti_s_d:
case Mips::BI__builtin_msa_clei_s_b:
case Mips::BI__builtin_msa_clei_s_h:
case Mips::BI__builtin_msa_clei_s_w:
case Mips::BI__builtin_msa_clei_s_d:
case Mips::BI__builtin_msa_maxi_s_b:
case Mips::BI__builtin_msa_maxi_s_h:
case Mips::BI__builtin_msa_maxi_s_w:
case Mips::BI__builtin_msa_maxi_s_d:
case Mips::BI__builtin_msa_mini_s_b:
case Mips::BI__builtin_msa_mini_s_h:
case Mips::BI__builtin_msa_mini_s_w:
case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
// These intrinsics take an unsigned 8 bit immediate.
case Mips::BI__builtin_msa_andi_b:
case Mips::BI__builtin_msa_nori_b:
case Mips::BI__builtin_msa_ori_b:
case Mips::BI__builtin_msa_shf_b:
case Mips::BI__builtin_msa_shf_h:
case Mips::BI__builtin_msa_shf_w:
case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
case Mips::BI__builtin_msa_bseli_b:
case Mips::BI__builtin_msa_bmnzi_b:
case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
// df/n format
// These intrinsics take an unsigned 4 bit immediate.
case Mips::BI__builtin_msa_copy_s_b:
case Mips::BI__builtin_msa_copy_u_b:
case Mips::BI__builtin_msa_insve_b:
case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
// These intrinsics take an unsigned 3 bit immediate.
case Mips::BI__builtin_msa_copy_s_h:
case Mips::BI__builtin_msa_copy_u_h:
case Mips::BI__builtin_msa_insve_h:
case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
// These intrinsics take an unsigned 2 bit immediate.
case Mips::BI__builtin_msa_copy_s_w:
case Mips::BI__builtin_msa_copy_u_w:
case Mips::BI__builtin_msa_insve_w:
case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
// These intrinsics take an unsigned 1 bit immediate.
case Mips::BI__builtin_msa_copy_s_d:
case Mips::BI__builtin_msa_copy_u_d:
case Mips::BI__builtin_msa_insve_d:
case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
// Memory offsets and immediate loads.
// These intrinsics take a signed 10 bit immediate.
case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
case Mips::BI__builtin_msa_ldi_h:
case Mips::BI__builtin_msa_ldi_w:
case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break;
case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break;
case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break;
case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break;
}
if (!m)
return SemaBuiltinConstantArgRange(TheCall, i, l, u);
return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
SemaBuiltinConstantArgMultiple(TheCall, i, m);
}
/// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str,
/// advancing the pointer over the consumed characters. The decoded type is
/// returned. If the decoded type represents a constant integer with a
/// constraint on its value then Mask is set to that value. The type descriptors
/// used in Str are specific to PPC MMA builtins and are documented in the file
/// defining the PPC builtins.
static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str,
unsigned &Mask) {
bool RequireICE = false;
ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
switch (*Str++) {
case 'V':
return Context.getVectorType(Context.UnsignedCharTy, 16,
VectorType::VectorKind::AltiVecVector);
case 'i': {
char *End;
unsigned size = strtoul(Str, &End, 10);
assert(End != Str && "Missing constant parameter constraint");
Str = End;
Mask = size;
return Context.IntTy;
}
case 'W': {
char *End;
unsigned size = strtoul(Str, &End, 10);
assert(End != Str && "Missing PowerPC MMA type size");
Str = End;
QualType Type;
switch (size) {
#define PPC_VECTOR_TYPE(typeName, Id, size) \
case size: Type = Context.Id##Ty; break;
#include "clang/Basic/PPCTypes.def"
default: llvm_unreachable("Invalid PowerPC MMA vector type");
}
bool CheckVectorArgs = false;
while (!CheckVectorArgs) {
switch (*Str++) {
case '*':
Type = Context.getPointerType(Type);
break;
case 'C':
Type = Type.withConst();
break;
default:
CheckVectorArgs = true;
--Str;
break;
}
}
return Type;
}
default:
return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true);
}
}
bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, 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 = TI.getTypeWidth(TI.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->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
<< TheCall->getSourceRange();
if ((IsBltinExtDiv && !TI.hasFeature("extdiv")) ||
(BuiltinID == PPC::BI__builtin_bpermd && !TI.hasFeature("bpermd")))
return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
<< TheCall->getSourceRange();
auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool {
if (!TI.hasFeature("vsx"))
return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
<< TheCall->getSourceRange();
return false;
};
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_altivec_dss:
return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
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);
case PPC::BI__builtin_altivec_dst:
case PPC::BI__builtin_altivec_dstt:
case PPC::BI__builtin_altivec_dstst:
case PPC::BI__builtin_altivec_dststt:
return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
case PPC::BI__builtin_vsx_xxpermdi:
case PPC::BI__builtin_vsx_xxsldwi:
return SemaBuiltinVSX(TheCall);
case PPC::BI__builtin_unpack_vector_int128:
return SemaVSXCheck(TheCall) ||
SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
case PPC::BI__builtin_pack_vector_int128:
return SemaVSXCheck(TheCall);
case PPC::BI__builtin_altivec_vgnb:
return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7);
case PPC::BI__builtin_altivec_vec_replace_elt:
case PPC::BI__builtin_altivec_vec_replace_unaligned: {
QualType VecTy = TheCall->getArg(0)->getType();
QualType EltTy = TheCall->getArg(1)->getType();
unsigned Width = Context.getIntWidth(EltTy);
return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) ||
!isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy);
}
case PPC::BI__builtin_vsx_xxeval:
return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255);
case PPC::BI__builtin_altivec_vsldbi:
return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
case PPC::BI__builtin_altivec_vsrdbi:
return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
case PPC::BI__builtin_vsx_xxpermx:
return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7);
#define CUSTOM_BUILTIN(Name, Types, Acc) \
case PPC::BI__builtin_##Name: \
return SemaBuiltinPPCMMACall(TheCall, Types);
#include "clang/Basic/BuiltinsPPC.def"
}
return SemaBuiltinConstantArgRange(TheCall, i, l, u);
}
// Check if the given type is a non-pointer PPC MMA type. This function is used
// in Sema to prevent invalid uses of restricted PPC MMA types.
bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) {
if (Type->isPointerType() || Type->isArrayType())
return false;
QualType CoreType = Type.getCanonicalType().getUnqualifiedType();
#define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty
if (false
#include "clang/Basic/PPCTypes.def"
) {
Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type);
return true;
}
return false;
}
bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,
CallExpr *TheCall) {
// position of memory order and scope arguments in the builtin
unsigned OrderIndex, ScopeIndex;
switch (BuiltinID) {
case AMDGPU::BI__builtin_amdgcn_atomic_inc32:
case AMDGPU::BI__builtin_amdgcn_atomic_inc64:
case AMDGPU::BI__builtin_amdgcn_atomic_dec32:
case AMDGPU::BI__builtin_amdgcn_atomic_dec64:
OrderIndex = 2;
ScopeIndex = 3;
break;
case AMDGPU::BI__builtin_amdgcn_fence:
OrderIndex = 0;
ScopeIndex = 1;
break;
default:
return false;
}
ExprResult Arg = TheCall->getArg(OrderIndex);
auto ArgExpr = Arg.get();
Expr::EvalResult ArgResult;
if (!ArgExpr->EvaluateAsInt(ArgResult, Context))
return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int)
<< ArgExpr->getType();
int ord = ArgResult.Val.getInt().getZExtValue();
// Check valididty of memory ordering as per C11 / C++11's memody model.
switch (static_cast<llvm::AtomicOrderingCABI>(ord)) {
case llvm::AtomicOrderingCABI::acquire:
case llvm::AtomicOrderingCABI::release:
case llvm::AtomicOrderingCABI::acq_rel:
case llvm::AtomicOrderingCABI::seq_cst:
break;
default: {
return Diag(ArgExpr->getBeginLoc(),
diag::warn_atomic_op_has_invalid_memory_order)
<< ArgExpr->getSourceRange();
}
}
Arg = TheCall->getArg(ScopeIndex);
ArgExpr = Arg.get();
Expr::EvalResult ArgResult1;
// Check that sync scope is a constant literal
if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context))
return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal)
<< ArgExpr->getType();
return false;
}
bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
CallExpr *TheCall) {
if (BuiltinID == SystemZ::BI__builtin_tabort) {
Expr *Arg = TheCall->getArg(0);
if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context))
if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256)
return Diag(Arg->getBeginLoc(), 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_vfisb:
case SystemZ::BI__builtin_s390_vfidb:
return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
case SystemZ::BI__builtin_s390_vftcisb:
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;
case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
case SystemZ::BI__builtin_s390_vfminsb:
case SystemZ::BI__builtin_s390_vfmaxsb:
case SystemZ::BI__builtin_s390_vfmindb:
case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; 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, const TargetInfo &TI,
CallExpr *TheCall) {
Expr *Arg = TheCall->getArg(0);
// Check if the argument is a string literal.
if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
<< Arg->getSourceRange();
// Check the contents of the string.
StringRef Feature =
cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
if (!TI.validateCpuSupports(Feature))
return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
<< Arg->getSourceRange();
return false;
}
/// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
/// This checks that the target supports __builtin_cpu_is and
/// that the string argument is constant and valid.
static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) {
Expr *Arg = TheCall->getArg(0);
// Check if the argument is a string literal.
if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
<< Arg->getSourceRange();
// Check the contents of the string.
StringRef Feature =
cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
if (!TI.validateCpuIs(Feature))
return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
<< Arg->getSourceRange();
return false;
}
// Check if the rounding mode is legal.
bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
// Indicates if this instruction has rounding control or just SAE.
bool HasRC = false;
unsigned ArgNum = 0;
switch (BuiltinID) {
default:
return false;
case X86::BI__builtin_ia32_vcvttsd2si32:
case X86::BI__builtin_ia32_vcvttsd2si64:
case X86::BI__builtin_ia32_vcvttsd2usi32:
case X86::BI__builtin_ia32_vcvttsd2usi64:
case X86::BI__builtin_ia32_vcvttss2si32:
case X86::BI__builtin_ia32_vcvttss2si64:
case X86::BI__builtin_ia32_vcvttss2usi32:
case X86::BI__builtin_ia32_vcvttss2usi64:
ArgNum = 1;
break;
case X86::BI__builtin_ia32_maxpd512:
case X86::BI__builtin_ia32_maxps512:
case X86::BI__builtin_ia32_minpd512:
case X86::BI__builtin_ia32_minps512:
ArgNum = 2;
break;
case X86::BI__builtin_ia32_cvtps2pd512_mask:
case X86::BI__builtin_ia32_cvttpd2dq512_mask:
case X86::BI__builtin_ia32_cvttpd2qq512_mask:
case X86::BI__builtin_ia32_cvttpd2udq512_mask:
case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
case X86::BI__builtin_ia32_cvttps2dq512_mask:
case X86::BI__builtin_ia32_cvttps2qq512_mask:
case X86::BI__builtin_ia32_cvttps2udq512_mask:
case X86::BI__builtin_ia32_cvttps2uqq512_mask:
case X86::BI__builtin_ia32_exp2pd_mask:
case X86::BI__builtin_ia32_exp2ps_mask:
case X86::BI__builtin_ia32_getexppd512_mask:
case X86::BI__builtin_ia32_getexpps512_mask:
case X86::BI__builtin_ia32_rcp28pd_mask:
case X86::BI__builtin_ia32_rcp28ps_mask:
case X86::BI__builtin_ia32_rsqrt28pd_mask:
case X86::BI__builtin_ia32_rsqrt28ps_mask:
case X86::BI__builtin_ia32_vcomisd:
case X86::BI__builtin_ia32_vcomiss:
case X86::BI__builtin_ia32_vcvtph2ps512_mask:
ArgNum = 3;
break;
case X86::BI__builtin_ia32_cmppd512_mask:
case X86::BI__builtin_ia32_cmpps512_mask:
case X86::BI__builtin_ia32_cmpsd_mask:
case X86::BI__builtin_ia32_cmpss_mask:
case X86::BI__builtin_ia32_cvtss2sd_round_mask:
case X86::BI__builtin_ia32_getexpsd128_round_mask:
case X86::BI__builtin_ia32_getexpss128_round_mask:
case X86::BI__builtin_ia32_getmantpd512_mask:
case X86::BI__builtin_ia32_getmantps512_mask:
case X86::BI__builtin_ia32_maxsd_round_mask:
case X86::BI__builtin_ia32_maxss_round_mask:
case X86::BI__builtin_ia32_minsd_round_mask:
case X86::BI__builtin_ia32_minss_round_mask:
case X86::BI__builtin_ia32_rcp28sd_round_mask:
case X86::BI__builtin_ia32_rcp28ss_round_mask:
case X86::BI__builtin_ia32_reducepd512_mask:
case X86::BI__builtin_ia32_reduceps512_mask:
case X86::BI__builtin_ia32_rndscalepd_mask:
case X86::BI__builtin_ia32_rndscaleps_mask:
case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
ArgNum = 4;
break;
case X86::BI__builtin_ia32_fixupimmpd512_mask:
case X86::BI__builtin_ia32_fixupimmpd512_maskz:
case X86::BI__builtin_ia32_fixupimmps512_mask:
case X86::BI__builtin_ia32_fixupimmps512_maskz:
case X86::BI__builtin_ia32_fixupimmsd_mask:
case X86::BI__builtin_ia32_fixupimmsd_maskz:
case X86::BI__builtin_ia32_fixupimmss_mask:
case X86::BI__builtin_ia32_fixupimmss_maskz:
case X86::BI__builtin_ia32_getmantsd_round_mask:
case X86::BI__builtin_ia32_getmantss_round_mask:
case X86::BI__builtin_ia32_rangepd512_mask:
case X86::BI__builtin_ia32_rangeps512_mask:
case X86::BI__builtin_ia32_rangesd128_round_mask:
case X86::BI__builtin_ia32_rangess128_round_mask:
case X86::BI__builtin_ia32_reducesd_mask:
case X86::BI__builtin_ia32_reducess_mask:
case X86::BI__builtin_ia32_rndscalesd_round_mask:
case X86::BI__builtin_ia32_rndscaless_round_mask:
ArgNum = 5;
break;
case X86::BI__builtin_ia32_vcvtsd2si64:
case X86::BI__builtin_ia32_vcvtsd2si32:
case X86::BI__builtin_ia32_vcvtsd2usi32:
case X86::BI__builtin_ia32_vcvtsd2usi64:
case X86::BI__builtin_ia32_vcvtss2si32:
case X86::BI__builtin_ia32_vcvtss2si64:
case X86::BI__builtin_ia32_vcvtss2usi32:
case X86::BI__builtin_ia32_vcvtss2usi64:
case X86::BI__builtin_ia32_sqrtpd512:
case X86::BI__builtin_ia32_sqrtps512:
ArgNum = 1;
HasRC = true;
break;
case X86::BI__builtin_ia32_addpd512:
case X86::BI__builtin_ia32_addps512:
case X86::BI__builtin_ia32_divpd512:
case X86::BI__builtin_ia32_divps512:
case X86::BI__builtin_ia32_mulpd512:
case X86::BI__builtin_ia32_mulps512:
case X86::BI__builtin_ia32_subpd512:
case X86::BI__builtin_ia32_subps512:
case X86::BI__builtin_ia32_cvtsi2sd64:
case X86::BI__builtin_ia32_cvtsi2ss32:
case X86::BI__builtin_ia32_cvtsi2ss64:
case X86::BI__builtin_ia32_cvtusi2sd64:
case X86::BI__builtin_ia32_cvtusi2ss32:
case X86::BI__builtin_ia32_cvtusi2ss64:
ArgNum = 2;
HasRC = true;
break;
case X86::BI__builtin_ia32_cvtdq2ps512_mask:
case X86::BI__builtin_ia32_cvtudq2ps512_mask:
case X86::BI__builtin_ia32_cvtpd2ps512_mask:
case X86::BI__builtin_ia32_cvtpd2dq512_mask:
case X86::BI__builtin_ia32_cvtpd2qq512_mask:
case X86::BI__builtin_ia32_cvtpd2udq512_mask:
case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
case X86::BI__builtin_ia32_cvtps2dq512_mask:
case X86::BI__builtin_ia32_cvtps2qq512_mask:
case X86::BI__builtin_ia32_cvtps2udq512_mask:
case X86::BI__builtin_ia32_cvtps2uqq512_mask:
case X86::BI__builtin_ia32_cvtqq2pd512_mask:
case X86::BI__builtin_ia32_cvtqq2ps512_mask:
case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
ArgNum = 3;
HasRC = true;
break;
case X86::BI__builtin_ia32_addss_round_mask:
case X86::BI__builtin_ia32_addsd_round_mask:
case X86::BI__builtin_ia32_divss_round_mask:
case X86::BI__builtin_ia32_divsd_round_mask:
case X86::BI__builtin_ia32_mulss_round_mask:
case X86::BI__builtin_ia32_mulsd_round_mask:
case X86::BI__builtin_ia32_subss_round_mask:
case X86::BI__builtin_ia32_subsd_round_mask:
case X86::BI__builtin_ia32_scalefpd512_mask:
case X86::BI__builtin_ia32_scalefps512_mask:
case X86::BI__builtin_ia32_scalefsd_round_mask:
case X86::BI__builtin_ia32_scalefss_round_mask:
case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
case X86::BI__builtin_ia32_sqrtsd_round_mask:
case X86::BI__builtin_ia32_sqrtss_round_mask:
case X86::BI__builtin_ia32_vfmaddsd3_mask:
case X86::BI__builtin_ia32_vfmaddsd3_maskz:
case X86::BI__builtin_ia32_vfmaddsd3_mask3:
case X86::BI__builtin_ia32_vfmaddss3_mask:
case X86::BI__builtin_ia32_vfmaddss3_maskz:
case X86::BI__builtin_ia32_vfmaddss3_mask3:
case X86::BI__builtin_ia32_vfmaddpd512_mask:
case X86::BI__builtin_ia32_vfmaddpd512_maskz:
case X86::BI__builtin_ia32_vfmaddpd512_mask3:
case X86::BI__builtin_ia32_vfmsubpd512_mask3:
case X86::BI__builtin_ia32_vfmaddps512_mask:
case X86::BI__builtin_ia32_vfmaddps512_maskz:
case X86::BI__builtin_ia32_vfmaddps512_mask3:
case X86::BI__builtin_ia32_vfmsubps512_mask3:
case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
case X86::BI__builtin_ia32_vfmaddsubps512_mask:
case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
ArgNum = 4;
HasRC = true;
break;
}
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;
// Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
// is set. If the intrinsic has rounding control(bits 1:0), make sure its only
// combined with ROUND_NO_EXC. If the intrinsic does not have rounding
// control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
Result == 8/*ROUND_NO_EXC*/ ||
(!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
(HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
return false;
return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
<< Arg->getSourceRange();
}
// Check if the gather/scatter scale is legal.
bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
CallExpr *TheCall) {
unsigned ArgNum = 0;
switch (BuiltinID) {
default:
return false;
case X86::BI__builtin_ia32_gatherpfdpd:
case X86::BI__builtin_ia32_gatherpfdps:
case X86::BI__builtin_ia32_gatherpfqpd:
case X86::BI__builtin_ia32_gatherpfqps:
case X86::BI__builtin_ia32_scatterpfdpd:
case X86::BI__builtin_ia32_scatterpfdps:
case X86::BI__builtin_ia32_scatterpfqpd:
case X86::BI__builtin_ia32_scatterpfqps:
ArgNum = 3;
break;
case X86::BI__builtin_ia32_gatherd_pd:
case X86::BI__builtin_ia32_gatherd_pd256:
case X86::BI__builtin_ia32_gatherq_pd:
case X86::BI__builtin_ia32_gatherq_pd256:
case X86::BI__builtin_ia32_gatherd_ps:
case X86::BI__builtin_ia32_gatherd_ps256:
case X86::BI__builtin_ia32_gatherq_ps:
case X86::BI__builtin_ia32_gatherq_ps256:
case X86::BI__builtin_ia32_gatherd_q:
case X86::BI__builtin_ia32_gatherd_q256:
case X86::BI__builtin_ia32_gatherq_q:
case X86::BI__builtin_ia32_gatherq_q256:
case X86::BI__builtin_ia32_gatherd_d:
case X86::BI__builtin_ia32_gatherd_d256:
case X86::BI__builtin_ia32_gatherq_d:
case X86::BI__builtin_ia32_gatherq_d256:
case X86::BI__builtin_ia32_gather3div2df:
case X86::BI__builtin_ia32_gather3div2di:
case X86::BI__builtin_ia32_gather3div4df:
case X86::BI__builtin_ia32_gather3div4di:
case X86::BI__builtin_ia32_gather3div4sf:
case X86::BI__builtin_ia32_gather3div4si:
case X86::BI__builtin_ia32_gather3div8sf:
case X86::BI__builtin_ia32_gather3div8si:
case X86::BI__builtin_ia32_gather3siv2df:
case X86::BI__builtin_ia32_gather3siv2di:
case X86::BI__builtin_ia32_gather3siv4df:
case X86::BI__builtin_ia32_gather3siv4di:
case X86::BI__builtin_ia32_gather3siv4sf:
case X86::BI__builtin_ia32_gather3siv4si:
case X86::BI__builtin_ia32_gather3siv8sf:
case X86::BI__builtin_ia32_gather3siv8si:
case X86::BI__builtin_ia32_gathersiv8df:
case X86::BI__builtin_ia32_gathersiv16sf:
case X86::BI__builtin_ia32_gatherdiv8df:
case X86::BI__builtin_ia32_gatherdiv16sf:
case X86::BI__builtin_ia32_gathersiv8di:
case X86::BI__builtin_ia32_gathersiv16si:
case X86::BI__builtin_ia32_gatherdiv8di:
case X86::BI__builtin_ia32_gatherdiv16si:
case X86::BI__builtin_ia32_scatterdiv2df:
case X86::BI__builtin_ia32_scatterdiv2di:
case X86::BI__builtin_ia32_scatterdiv4df:
case X86::BI__builtin_ia32_scatterdiv4di:
case X86::BI__builtin_ia32_scatterdiv4sf:
case X86::BI__builtin_ia32_scatterdiv4si:
case X86::BI__builtin_ia32_scatterdiv8sf:
case X86::BI__builtin_ia32_scatterdiv8si:
case X86::BI__builtin_ia32_scattersiv2df:
case X86::BI__builtin_ia32_scattersiv2di:
case X86::BI__builtin_ia32_scattersiv4df:
case X86::BI__builtin_ia32_scattersiv4di:
case X86::BI__builtin_ia32_scattersiv4sf:
case X86::BI__builtin_ia32_scattersiv4si:
case X86::BI__builtin_ia32_scattersiv8sf:
case X86::BI__builtin_ia32_scattersiv8si:
case X86::BI__builtin_ia32_scattersiv8df:
case X86::BI__builtin_ia32_scattersiv16sf:
case X86::BI__builtin_ia32_scatterdiv8df:
case X86::BI__builtin_ia32_scatterdiv16sf:
case X86::BI__builtin_ia32_scattersiv8di:
case X86::BI__builtin_ia32_scattersiv16si:
case X86::BI__builtin_ia32_scatterdiv8di:
case X86::BI__builtin_ia32_scatterdiv16si:
ArgNum = 4;
break;
}
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 == 1 || Result == 2 || Result == 4 || Result == 8)
return false;
return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
<< Arg->getSourceRange();
}
enum { TileRegLow = 0, TileRegHigh = 7 };
bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
ArrayRef<int> ArgNums) {
for (int ArgNum : ArgNums) {
if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh))
return true;
}
return false;
}
bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall,
ArrayRef<int> ArgNums) {
// Because the max number of tile register is TileRegHigh + 1, so here we use
// each bit to represent the usage of them in bitset.
std::bitset<TileRegHigh + 1> ArgValues;
for (int ArgNum : ArgNums) {
Expr *Arg = TheCall->getArg(ArgNum);
if (Arg->isTypeDependent() || Arg->isValueDependent())
continue;
llvm::APSInt Result;
if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
return true;
int ArgExtValue = Result.getExtValue();
assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) &&
"Incorrect tile register num.");
if (ArgValues.test(ArgExtValue))
return Diag(TheCall->getBeginLoc(),
diag::err_x86_builtin_tile_arg_duplicate)
<< TheCall->getArg(ArgNum)->getSourceRange();
ArgValues.set(ArgExtValue);
}
return false;
}
bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
ArrayRef<int> ArgNums) {
return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) ||
CheckX86BuiltinTileDuplicate(TheCall, ArgNums);
}
bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) {
switch (BuiltinID) {
default:
return false;
case X86::BI__builtin_ia32_tileloadd64:
case X86::BI__builtin_ia32_tileloaddt164:
case X86::BI__builtin_ia32_tilestored64:
case X86::BI__builtin_ia32_tilezero:
return CheckX86BuiltinTileArgumentsRange(TheCall, 0);
case X86::BI__builtin_ia32_tdpbssd:
case X86::BI__builtin_ia32_tdpbsud:
case X86::BI__builtin_ia32_tdpbusd:
case X86::BI__builtin_ia32_tdpbuud:
case X86::BI__builtin_ia32_tdpbf16ps:
return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2});
}
}
static bool isX86_32Builtin(unsigned BuiltinID) {
// These builtins only work on x86-32 targets.
switch (BuiltinID) {
case X86::BI__builtin_ia32_readeflags_u32:
case X86::BI__builtin_ia32_writeeflags_u32:
return true;
}
return false;
}
bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
CallExpr *TheCall) {
if (BuiltinID == X86::BI__builtin_cpu_supports)
return SemaBuiltinCpuSupports(*this, TI, TheCall);
if (BuiltinID == X86::BI__builtin_cpu_is)
return SemaBuiltinCpuIs(*this, TI, TheCall);
// Check for 32-bit only builtins on a 64-bit target.
const llvm::Triple &TT = TI.getTriple();
if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
return Diag(TheCall->getCallee()->getBeginLoc(),
diag::err_32_bit_builtin_64_bit_tgt);
// If the intrinsic has rounding or SAE make sure its valid.
if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
return true;
// If the intrinsic has a gather/scatter scale immediate make sure its valid.
if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
return true;
// If the intrinsic has a tile arguments, make sure they are valid.
if (CheckX86BuiltinTileArguments(BuiltinID, TheCall))
return true;
// For intrinsics which take an immediate value as part of the instruction,
// range check them here.
int i = 0, l = 0, u = 0;
switch (BuiltinID) {
default:
return false;
case X86::BI__builtin_ia32_vec_ext_v2si:
case X86::BI__builtin_ia32_vec_ext_v2di:
case X86::BI__builtin_ia32_vextractf128_pd256:
case X86::BI__builtin_ia32_vextractf128_ps256:
case X86::BI__builtin_ia32_vextractf128_si256:
case X86::BI__builtin_ia32_extract128i256:
case X86::BI__builtin_ia32_extractf64x4_mask:
case X86::BI__builtin_ia32_extracti64x4_mask:
case X86::BI__builtin_ia32_extractf32x8_mask:
case X86::BI__builtin_ia32_extracti32x8_mask:
case X86::BI__builtin_ia32_extractf64x2_256_mask:
case X86::BI__builtin_ia32_extracti64x2_256_mask:
case X86::BI__builtin_ia32_extractf32x4_256_mask:
case X86::BI__builtin_ia32_extracti32x4_256_mask:
i = 1; l = 0; u = 1;
break;
case X86::BI__builtin_ia32_vec_set_v2di:
case X86::BI__builtin_ia32_vinsertf128_pd256:
case X86::BI__builtin_ia32_vinsertf128_ps256:
case X86::BI__builtin_ia32_vinsertf128_si256:
case X86::BI__builtin_ia32_insert128i256:
case X86::BI__builtin_ia32_insertf32x8:
case X86::BI__builtin_ia32_inserti32x8:
case X86::BI__builtin_ia32_insertf64x4:
case X86::BI__builtin_ia32_inserti64x4:
case X86::BI__builtin_ia32_insertf64x2_256:
case X86::BI__builtin_ia32_inserti64x2_256:
case X86::BI__builtin_ia32_insertf32x4_256:
case X86::BI__builtin_ia32_inserti32x4_256:
i = 2; l = 0; u = 1;
break;
case X86::BI__builtin_ia32_vpermilpd:
case X86::BI__builtin_ia32_vec_ext_v4hi:
case X86::BI__builtin_ia32_vec_ext_v4si:
case X86::BI__builtin_ia32_vec_ext_v4sf:
case X86::BI__builtin_ia32_vec_ext_v4di:
case X86::BI__builtin_ia32_extractf32x4_mask:
case X86::BI__builtin_ia32_extracti32x4_mask:
case X86::BI__builtin_ia32_extractf64x2_512_mask:
case X86::BI__builtin_ia32_extracti64x2_512_mask:
i = 1; l = 0; u = 3;
break;
case X86::BI_mm_prefetch:
case X86::BI__builtin_ia32_vec_ext_v8hi:
case X86::BI__builtin_ia32_vec_ext_v8si:
i = 1; l = 0; u = 7;
break;
case X86::BI__builtin_ia32_sha1rnds4:
case X86::BI__builtin_ia32_blendpd:
case X86::BI__builtin_ia32_shufpd:
case X86::BI__builtin_ia32_vec_set_v4hi:
case X86::BI__builtin_ia32_vec_set_v4si:
case X86::BI__builtin_ia32_vec_set_v4di:
case X86::BI__builtin_ia32_shuf_f32x4_256:
case X86::BI__builtin_ia32_shuf_f64x2_256:
case X86::BI__builtin_ia32_shuf_i32x4_256:
case X86::BI__builtin_ia32_shuf_i64x2_256:
case X86::BI__builtin_ia32_insertf64x2_512:
case X86::BI__builtin_ia32_inserti64x2_512:
case X86::BI__builtin_ia32_insertf32x4:
case X86::BI__builtin_ia32_inserti32x4:
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:
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:
case X86::BI__builtin_ia32_vec_set_v8hi:
case X86::BI__builtin_ia32_vec_set_v8si:
i = 2; l = 0; u = 7;
break;
case X86::BI__builtin_ia32_vpermilpd256:
case X86::BI__builtin_ia32_roundps:
case X86::BI__builtin_ia32_roundpd:
case X86::BI__builtin_ia32_roundps256:
case X86::BI__builtin_ia32_roundpd256:
case X86::BI__builtin_ia32_getmantpd128_mask:
case X86::BI__builtin_ia32_getmantpd256_mask:
case X86::BI__builtin_ia32_getmantps128_mask:
case X86::BI__builtin_ia32_getmantps256_mask:
case X86::BI__builtin_ia32_getmantpd512_mask:
case X86::BI__builtin_ia32_getmantps512_mask:
case X86::BI__builtin_ia32_vec_ext_v16qi:
case X86::BI__builtin_ia32_vec_ext_v16hi:
i = 1; l = 0; u = 15;
break;
case X86::BI__builtin_ia32_pblendd128:
case X86::BI__builtin_ia32_blendps:
case X86::BI__builtin_ia32_blendpd256:
case X86::BI__builtin_ia32_shufpd256:
case X86::BI__builtin_ia32_roundss:
case X86::BI__builtin_ia32_roundsd:
case X86::BI__builtin_ia32_rangepd128_mask:
case X86::BI__builtin_ia32_rangepd256_mask:
case X86::BI__builtin_ia32_rangepd512_mask:
case X86::BI__builtin_ia32_rangeps128_mask:
case X86::BI__builtin_ia32_rangeps256_mask:
case X86::BI__builtin_ia32_rangeps512_mask:
case X86::BI__builtin_ia32_getmantsd_round_mask:
case X86::BI__builtin_ia32_getmantss_round_mask:
case X86::BI__builtin_ia32_vec_set_v16qi:
case X86::BI__builtin_ia32_vec_set_v16hi:
i = 2; l = 0; u = 15;
break;
case X86::BI__builtin_ia32_vec_ext_v32qi:
i = 1; l = 0; u = 31;
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_cmpps128_mask:
case X86::BI__builtin_ia32_cmppd128_mask:
case X86::BI__builtin_ia32_cmpps256_mask:
case X86::BI__builtin_ia32_cmppd256_mask:
case X86::BI__builtin_ia32_cmpps512_mask:
case X86::BI__builtin_ia32_cmppd512_mask:
case X86::BI__builtin_ia32_cmpsd_mask:
case X86::BI__builtin_ia32_cmpss_mask:
case X86::BI__builtin_ia32_vec_set_v32qi:
i = 2; l = 0; u = 31;
break;
case X86::BI__builtin_ia32_permdf256:
case X86::BI__builtin_ia32_permdi256:
case X86::BI__builtin_ia32_permdf512:
case X86::BI__builtin_ia32_permdi512:
case X86::BI__builtin_ia32_vpermilps:
case X86::BI__builtin_ia32_vpermilps256:
case X86::BI__builtin_ia32_vpermilpd512:
case X86::BI__builtin_ia32_vpermilps512:
case X86::BI__builtin_ia32_pshufd:
case X86::BI__builtin_ia32_pshufd256:
case X86::BI__builtin_ia32_pshufd512:
case X86::BI__builtin_ia32_pshufhw:
case X86::BI__builtin_ia32_pshufhw256:
case X86::BI__builtin_ia32_pshufhw512:
case X86::BI__builtin_ia32_pshuflw:
case X86::BI__builtin_ia32_pshuflw256:
case X86::BI__builtin_ia32_pshuflw512:
case X86::BI__builtin_ia32_vcvtps2ph:
case X86::BI__builtin_ia32_vcvtps2ph_mask:
case X86::BI__builtin_ia32_vcvtps2ph256:
case X86::BI__builtin_ia32_vcvtps2ph256_mask:
case X86::BI__builtin_ia32_vcvtps2ph512_mask:
case X86::BI__builtin_ia32_rndscaleps_128_mask:
case X86::BI__builtin_ia32_rndscalepd_128_mask:
case X86::BI__builtin_ia32_rndscaleps_256_mask:
case X86::BI__builtin_ia32_rndscalepd_256_mask:
case X86::BI__builtin_ia32_rndscaleps_mask:
case X86::BI__builtin_ia32_rndscalepd_mask:
case X86::BI__builtin_ia32_reducepd128_mask:
case X86::BI__builtin_ia32_reducepd256_mask:
case X86::BI__builtin_ia32_reducepd512_mask:
case X86::BI__builtin_ia32_reduceps128_mask:
case X86::BI__builtin_ia32_reduceps256_mask:
case X86::BI__builtin_ia32_reduceps512_mask:
case X86::BI__builtin_ia32_prold512:
case X86::BI__builtin_ia32_prolq512:
case X86::BI__builtin_ia32_prold128:
case X86::BI__builtin_ia32_prold256:
case X86::BI__builtin_ia32_prolq128:
case X86::BI__builtin_ia32_prolq256:
case X86::BI__builtin_ia32_prord512:
case X86::BI__builtin_ia32_prorq512:
case X86::BI__builtin_ia32_prord128:
case X86::BI__builtin_ia32_prord256:
case X86::BI__builtin_ia32_prorq128:
case X86::BI__builtin_ia32_prorq256:
case X86::BI__builtin_ia32_fpclasspd128_mask:
case X86::BI__builtin_ia32_fpclasspd256_mask:
case X86::BI__builtin_ia32_fpclassps128_mask:
case X86::BI__builtin_ia32_fpclassps256_mask:
case X86::BI__builtin_ia32_fpclassps512_mask:
case X86::BI__builtin_ia32_fpclasspd512_mask:
case X86::BI__builtin_ia32_fpclasssd_mask:
case X86::BI__builtin_ia32_fpclassss_mask:
case X86::BI__builtin_ia32_pslldqi128_byteshift:
case X86::BI__builtin_ia32_pslldqi256_byteshift:
case X86::BI__builtin_ia32_pslldqi512_byteshift:
case X86::BI__builtin_ia32_psrldqi128_byteshift:
case X86::BI__builtin_ia32_psrldqi256_byteshift:
case X86::BI__builtin_ia32_psrldqi512_byteshift:
case X86::BI__builtin_ia32_kshiftliqi:
case X86::BI__builtin_ia32_kshiftlihi:
case X86::BI__builtin_ia32_kshiftlisi:
case X86::BI__builtin_ia32_kshiftlidi:
case X86::BI__builtin_ia32_kshiftriqi:
case X86::BI__builtin_ia32_kshiftrihi:
case X86::BI__builtin_ia32_kshiftrisi:
case X86::BI__builtin_ia32_kshiftridi:
i = 1; l = 0; u = 255;
break;
case X86::BI__builtin_ia32_vperm2f128_pd256:
case X86::BI__builtin_ia32_vperm2f128_ps256:
case X86::BI__builtin_ia32_vperm2f128_si256:
case X86::BI__builtin_ia32_permti256:
case X86::BI__builtin_ia32_pblendw128:
case X86::BI__builtin_ia32_pblendw256:
case X86::BI__builtin_ia32_blendps256:
case X86::BI__builtin_ia32_pblendd256:
case X86::BI__builtin_ia32_palignr128:
case X86::BI__builtin_ia32_palignr256:
case X86::BI__builtin_ia32_palignr512:
case X86::BI__builtin_ia32_alignq512:
case X86::BI__builtin_ia32_alignd512:
case X86::BI__builtin_ia32_alignd128:
case X86::BI__builtin_ia32_alignd256:
case X86::BI__builtin_ia32_alignq128:
case X86::BI__builtin_ia32_alignq256:
case X86::BI__builtin_ia32_vcomisd:
case X86::BI__builtin_ia32_vcomiss:
case X86::BI__builtin_ia32_shuf_f32x4:
case X86::BI__builtin_ia32_shuf_f64x2:
case X86::BI__builtin_ia32_shuf_i32x4:
case X86::BI__builtin_ia32_shuf_i64x2:
case X86::BI__builtin_ia32_shufpd512:
case X86::BI__builtin_ia32_shufps:
case X86::BI__builtin_ia32_shufps256:
case X86::BI__builtin_ia32_shufps512:
case X86::BI__builtin_ia32_dbpsadbw128:
case X86::BI__builtin_ia32_dbpsadbw256:
case X86::BI__builtin_ia32_dbpsadbw512:
case X86::BI__builtin_ia32_vpshldd128:
case X86::BI__builtin_ia32_vpshldd256:
case X86::BI__builtin_ia32_vpshldd512:
case X86::BI__builtin_ia32_vpshldq128:
case X86::BI__builtin_ia32_vpshldq256:
case X86::BI__builtin_ia32_vpshldq512:
case X86::BI__builtin_ia32_vpshldw128:
case X86::BI__builtin_ia32_vpshldw256:
case X86::BI__builtin_ia32_vpshldw512:
case X86::BI__builtin_ia32_vpshrdd128:
case X86::BI__builtin_ia32_vpshrdd256:
case X86::BI__builtin_ia32_vpshrdd512:
case X86::BI__builtin_ia32_vpshrdq128:
case X86::BI__builtin_ia32_vpshrdq256:
case X86::BI__builtin_ia32_vpshrdq512:
case X86::BI__builtin_ia32_vpshrdw128:
case X86::BI__builtin_ia32_vpshrdw256:
case X86::BI__builtin_ia32_vpshrdw512:
i = 2; l = 0; u = 255;
break;
case X86::BI__builtin_ia32_fixupimmpd512_mask:
case X86::BI__builtin_ia32_fixupimmpd512_maskz:
case X86::BI__builtin_ia32_fixupimmps512_mask:
case X86::BI__builtin_ia32_fixupimmps512_maskz:
case X86::BI__builtin_ia32_fixupimmsd_mask:
case X86::BI__builtin_ia32_fixupimmsd_maskz:
case X86::BI__builtin_ia32_fixupimmss_mask:
case X86::BI__builtin_ia32_fixupimmss_maskz:
case X86::BI__builtin_ia32_fixupimmpd128_mask:
case X86::BI__builtin_ia32_fixupimmpd128_maskz:
case X86::BI__builtin_ia32_fixupimmpd256_mask:
case X86::BI__builtin_ia32_fixupimmpd256_maskz:
case X86::BI__builtin_ia32_fixupimmps128_mask:
case X86::BI__builtin_ia32_fixupimmps128_maskz:
case X86::BI__builtin_ia32_fixupimmps256_mask:
case X86::BI__builtin_ia32_fixupimmps256_maskz:
case X86::BI__builtin_ia32_pternlogd512_mask:
case X86::BI__builtin_ia32_pternlogd512_maskz:
case X86::BI__builtin_ia32_pternlogq512_mask:
case X86::BI__builtin_ia32_pternlogq512_maskz:
case X86::BI__builtin_ia32_pternlogd128_mask:
case X86::BI__builtin_ia32_pternlogd128_maskz:
case X86::BI__builtin_ia32_pternlogd256_mask:
case X86::BI__builtin_ia32_pternlogd256_maskz:
case X86::BI__builtin_ia32_pternlogq128_mask:
case X86::BI__builtin_ia32_pternlogq128_maskz:
case X86::BI__builtin_ia32_pternlogq256_mask:
case X86::BI__builtin_ia32_pternlogq256_maskz:
i = 3; l = 0; u = 255;
break;
case X86::BI__builtin_ia32_gatherpfdpd:
case X86::BI__builtin_ia32_gatherpfdps:
case X86::BI__builtin_ia32_gatherpfqpd:
case X86::BI__builtin_ia32_gatherpfqps:
case X86::BI__builtin_ia32_scatterpfdpd:
case X86::BI__builtin_ia32_scatterpfdps:
case X86::BI__builtin_ia32_scatterpfqpd:
case X86::BI__builtin_ia32_scatterpfqps:
i = 4; l = 2; u = 3;
break;
case X86::BI__builtin_ia32_reducesd_mask:
case X86::BI__builtin_ia32_reducess_mask:
case X86::BI__builtin_ia32_rndscalesd_round_mask:
case X86::BI__builtin_ia32_rndscaless_round_mask:
i = 4; l = 0; u = 255;
break;
}
// Note that we don't force a hard error on the range check here, allowing
// template-generated or macro-generated dead code to potentially have out-of-
// range values. These need to code generate, but don't need to necessarily
// make any sense. We use a warning that defaults to an error.
return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
}
/// 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.
///
/// 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;
}
/// 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");
// Already checked by by constant evaluator.
if (S.isConstantEvaluated())
return;
// 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 (const ParamIdx &Idx : NonNull->args()) {
unsigned IdxAST = Idx.getASTIndex();
if (IdxAST >= Args.size())
continue;
if (NonNullArgs.empty())
NonNullArgs.resize(Args.size());
NonNullArgs.set(IdxAST);
}
}
}
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, NULL arguments passed to non-NULL parameters, and diagnose_if
/// attributes.
void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
const Expr *ThisArg, 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.
auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
if (CallType != VariadicDoesNotApply &&
(!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
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, Loc);
}
}
if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
auto *AA = FDecl->getAttr<AllocAlignAttr>();
const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
if (!Arg->isValueDependent()) {
Expr::EvalResult Align;
if (Arg->EvaluateAsInt(Align, Context)) {
const llvm::APSInt &I = Align.Val.getInt();
if (!I.isPowerOf2())
Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
<< Arg->getSourceRange();
if (I > Sema::MaximumAlignment)
Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
<< Arg->getSourceRange() << Sema::MaximumAlignment;
}
}
}
if (FD)
diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
}
/// 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, /*ThisArg=*/nullptr, 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();
Expr *ImplicitThis = nullptr;
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.
ImplicitThis = Args[0];
++Args;
--NumArgs;
} else if (IsMemberFunction)
ImplicitThis =
cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
checkCall(FDecl, Proto, ImplicitThis, 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;
CheckTCBEnforcement(TheCall, FDecl);
CheckAbsoluteValueFunction(TheCall, FDecl);
CheckMaxUnsignedZero(TheCall, FDecl);
if (getLangOpts().ObjC)
DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
unsigned CMId = FDecl->getMemoryFunctionKind();
// Handle memory setting and copying functions.
switch (CMId) {
case 0:
return false;
case Builtin::BIstrlcpy: // fallthrough
case Builtin::BIstrlcat:
CheckStrlcpycatArguments(TheCall, FnInfo);
break;
case Builtin::BIstrncat:
CheckStrncatArguments(TheCall, FnInfo);
break;
case Builtin::BIfree:
CheckFreeArguments(TheCall);
break;
default:
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, /*ThisArg=*/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, /*ThisArg=*/nullptr,
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, /*ThisArg=*/nullptr,
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:
case AtomicExpr::AO__opencl_atomic_init:
llvm_unreachable("There is no ordering argument for an init");
case AtomicExpr::AO__c11_atomic_load:
case AtomicExpr::AO__opencl_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__opencl_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());
MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
Op);
}
ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
SourceLocation RParenLoc, MultiExprArg Args,
AtomicExpr::AtomicOp Op,
AtomicArgumentOrder ArgOrder) {
// All the non-OpenCL operations take one of the following forms.
// The OpenCL operations take the __c11 forms with one extra argument for
// synchronization scope.
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 NumForm = GNUCmpXchg + 1;
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(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
&& sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
"need to update code for modified forms");
static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
AtomicExpr::AO__atomic_load,
"need to update code for modified C11 atomics");
bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
IsOpenCL;
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:
case AtomicExpr::AO__opencl_atomic_init:
Form = Init;
break;
case AtomicExpr::AO__c11_atomic_load:
case AtomicExpr::AO__opencl_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__opencl_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__opencl_atomic_fetch_add:
case AtomicExpr::AO__opencl_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;
LLVM_FALLTHROUGH;
case AtomicExpr::AO__c11_atomic_fetch_and:
case AtomicExpr::AO__c11_atomic_fetch_or:
case AtomicExpr::AO__c11_atomic_fetch_xor:
case AtomicExpr::AO__opencl_atomic_fetch_and:
case AtomicExpr::AO__opencl_atomic_fetch_or:
case AtomicExpr::AO__opencl_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:
case AtomicExpr::AO__c11_atomic_fetch_min:
case AtomicExpr::AO__c11_atomic_fetch_max:
case AtomicExpr::AO__opencl_atomic_fetch_min:
case AtomicExpr::AO__opencl_atomic_fetch_max:
case AtomicExpr::AO__atomic_min_fetch:
case AtomicExpr::AO__atomic_max_fetch:
case AtomicExpr::AO__atomic_fetch_min:
case AtomicExpr::AO__atomic_fetch_max:
Form = Arithmetic;
break;
case AtomicExpr::AO__c11_atomic_exchange:
case AtomicExpr::AO__opencl_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:
case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
Form = C11CmpXchg;
break;
case AtomicExpr::AO__atomic_compare_exchange:
case AtomicExpr::AO__atomic_compare_exchange_n:
Form = GNUCmpXchg;
break;
}
unsigned AdjustedNumArgs = NumArgs[Form];
if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
++AdjustedNumArgs;
// Check we have the right number of arguments.
if (Args.size() < AdjustedNumArgs) {
Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
<< 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
<< ExprRange;
return ExprError();
} else if (Args.size() > AdjustedNumArgs) {
Diag(Args[AdjustedNumArgs]->getBeginLoc(),
diag::err_typecheck_call_too_many_args)
<< 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
<< ExprRange;
return ExprError();
}
// Inspect the first argument of the atomic operation.
Expr *Ptr = Args[0];
ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
if (ConvertedPtr.isInvalid())
return ExprError();
Ptr = ConvertedPtr.get();
const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
if (!pointerType) {
Diag(ExprRange.getBegin(), 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(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
<< Ptr->getType() << Ptr->getSourceRange();
return ExprError();
}
if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
AtomTy.getAddressSpace() == LangAS::opencl_constant) {
Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
<< (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
<< Ptr->getSourceRange();
return ExprError();
}
ValType = AtomTy->castAs<AtomicType>()->getValueType();
} else if (Form != Load && Form != LoadCopy) {
if (ValType.isConstQualified()) {
Diag(ExprRange.getBegin(), 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(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
<< IsC11 << Ptr->getType() << Ptr->getSourceRange();
return ExprError();
}
if (!IsAddSub && !ValType->isIntegerType()) {
Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
<< IsC11 << Ptr->getType() << Ptr->getSourceRange();
return ExprError();
}
if (IsC11 && ValType->isPointerType() &&
RequireCompleteType(Ptr->getBeginLoc(), 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(ExprRange.getBegin(), 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(ExprRange.getBegin(), 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(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
<< ValType << Ptr->getSourceRange();
return ExprError();
}
// All atomic operations have an overload which 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 takes 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'
bool IsPassedByAddress = false;
if (!IsC11 && !IsN) {
ByValType = Ptr->getType();
IsPassedByAddress = true;
}
SmallVector<Expr *, 5> APIOrderedArgs;
if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
APIOrderedArgs.push_back(Args[0]);
switch (Form) {
case Init:
case Load:
APIOrderedArgs.push_back(Args[1]); // Val1/Order
break;
case LoadCopy:
case Copy:
case Arithmetic:
case Xchg:
APIOrderedArgs.push_back(Args[2]); // Val1
APIOrderedArgs.push_back(Args[1]); // Order
break;
case GNUXchg:
APIOrderedArgs.push_back(Args[2]); // Val1
APIOrderedArgs.push_back(Args[3]); // Val2
APIOrderedArgs.push_back(Args[1]); // Order
break;
case C11CmpXchg:
APIOrderedArgs.push_back(Args[2]); // Val1
APIOrderedArgs.push_back(Args[4]); // Val2
APIOrderedArgs.push_back(Args[1]); // Order
APIOrderedArgs.push_back(Args[3]); // OrderFail
break;
case GNUCmpXchg:
APIOrderedArgs.push_back(Args[2]); // Val1
APIOrderedArgs.push_back(Args[4]); // Val2
APIOrderedArgs.push_back(Args[5]); // Weak
APIOrderedArgs.push_back(Args[1]); // Order
APIOrderedArgs.push_back(Args[3]); // OrderFail
break;
}
} else
APIOrderedArgs.append(Args.begin(), Args.end());
// The first argument's non-CV pointer type is used to deduce the type of
// subsequent arguments, except for:
// - weak flag (always converted to bool)
// - memory order (always converted to int)
// - scope (always converted to int)
for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
QualType Ty;
if (i < NumVals[Form] + 1) {
switch (i) {
case 0:
// The first argument is always a pointer. It has a fixed type.
// It is always dereferenced, a nullptr is undefined.
CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
// Nothing else to do: we already know all we want about this pointer.
continue;
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) {
if (IsPassedByAddress) {
// The value pointer is always dereferenced, a nullptr is undefined.
CheckNonNullArgument(*this, APIOrderedArgs[i],
ExprRange.getBegin());
}
Ty = ByValType;
} else if (Form == Arithmetic)
Ty = Context.getPointerDiffType();
else {
Expr *ValArg = APIOrderedArgs[i];
// The value pointer is always dereferenced, a nullptr is undefined.
CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
LangAS AS = LangAS::Default;
// 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 the desired
// value, either by-value (for the C11 and *_n variant) or as a pointer.
if (IsPassedByAddress)
CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
Ty = ByValType;
break;
case 3:
// The fourth argument to GNU compare_exchange is a 'weak' flag.
Ty = Context.BoolTy;
break;
}
} else {
// The order(s) and scope are always converted to int.
Ty = Context.IntTy;
}
InitializedEntity Entity =
InitializedEntity::InitializeParameter(Context, Ty, false);
ExprResult Arg = APIOrderedArgs[i];
Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
if (Arg.isInvalid())
return true;
APIOrderedArgs[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(APIOrderedArgs[1]); // Val1
break;
case Load:
SubExprs.push_back(APIOrderedArgs[1]); // Order
break;
case LoadCopy:
case Copy:
case Arithmetic:
case Xchg:
SubExprs.push_back(APIOrderedArgs[2]); // Order
SubExprs.push_back(APIOrderedArgs[1]); // Val1
break;
case GNUXchg:
// Note, AtomicExpr::getVal2() has a special case for this atomic.
SubExprs.push_back(APIOrderedArgs[3]); // Order
SubExprs.push_back(APIOrderedArgs[1]); // Val1
SubExprs.push_back(APIOrderedArgs[2]); // Val2
break;
case C11CmpXchg:
SubExprs.push_back(APIOrderedArgs[3]); // Order
SubExprs.push_back(APIOrderedArgs[1]); // Val1
SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
SubExprs.push_back(APIOrderedArgs[2]); // Val2
break;
case GNUCmpXchg:
SubExprs.push_back(APIOrderedArgs[4]); // Order
SubExprs.push_back(APIOrderedArgs[1]); // Val1
SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
SubExprs.push_back(APIOrderedArgs[2]); // Val2
SubExprs.push_back(APIOrderedArgs[3]); // Weak
break;
}
if (SubExprs.size() >= 2 && Form != Init) {
if (Optional<llvm::APSInt> Result =
SubExprs[1]->getIntegerConstantExpr(Context))
if (!isValidOrderingForOp(Result->getSExtValue(), Op))
Diag(SubExprs[1]->getBeginLoc(),
diag::warn_atomic_op_has_invalid_memory_order)
<< SubExprs[1]->getSourceRange();
}
if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
auto *Scope = Args[Args.size() - 1];
if (Optional<llvm::APSInt> Result =
Scope->getIntegerConstantExpr(Context)) {
if (!ScopeModel->isValid(Result->getZExtValue()))
Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
<< Scope->getSourceRange();
}
SubExprs.push_back(Scope);
}
AtomicExpr *AE = new (Context)
AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
if ((Op == AtomicExpr::AO__c11_atomic_load ||
Op == AtomicExpr::AO__c11_atomic_store ||
Op == AtomicExpr::AO__opencl_atomic_load ||
Op == AtomicExpr::AO__opencl_atomic_store ) &&
Context.AtomicUsesUnsupportedLibcall(AE))
Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
<< ((Op == AtomicExpr::AO__c11_atomic_load ||
Op == AtomicExpr::AO__opencl_atomic_load)
? 0
: 1);
if (ValType->isExtIntType()) {
Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_ext_int_prohibit);
return ExprError();
}
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;
}
/// 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 BuildCallExpr 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, as well as generating any warnings.
ExprResult
Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
Expr *Callee = TheCall->getCallee();
DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->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->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
<< 0 << 1 << TheCall->getNumArgs() << Callee->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->getBeginLoc(), 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->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
<< FirstArg->getType() << FirstArg->getSourceRange();
return ExprError();
}
if (ValType.isConstQualified()) {
Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
<< 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->getBeginLoc(), 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->getBeginLoc(), 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->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
<< 0 << 1 + NumFixed << TheCall->getNumArgs()
<< Callee->getSourceRange();
return ExprError();
}
Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
<< Callee->getSourceRange();
if (WarnAboutSemanticsChange) {
Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
<< Callee->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->getBeginLoc(), 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());
}
// 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(), nullptr, nullptr, DRE->isNonOdrUse());
// 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);
// Prohibit use of _ExtInt with atomic builtins.
// The arguments would have already been converted to the first argument's
// type, so only need to check the first argument.
const auto *ExtIntValType = ValType->getAs<ExtIntType>();
if (ExtIntValType && !llvm::isPowerOf2_64(ExtIntValType->getNumBits())) {
Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
return ExprError();
}
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->getBeginLoc(), 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->getBeginLoc(),
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->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
<< Arg->getSourceRange();
return true;
}
if (Literal->containsNonAsciiOrNull()) {
StringRef String = Literal->getString();
unsigned NumBytes = String.size();
SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
llvm::UTF16 *ToPtr = &ToBuf[0];
llvm::ConversionResult Result =
llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
ToPtr + NumBytes, llvm::strictConversion);
// Check for conversion failure.
if (Result != llvm::conversionOK)
Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
<< Arg->getSourceRange();
}
return false;
}
/// CheckObjCString - Checks that the format string argument to the os_log()
/// and os_trace() functions is correct, and converts it to const char *.
ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
Arg = Arg->IgnoreParenCasts();
auto *Literal = dyn_cast<StringLiteral>(Arg);
if (!Literal) {
if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
Literal = ObjcLiteral->getString();
}
}
if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
return ExprError(
Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
<< Arg->getSourceRange());
}
ExprResult Result(Literal);
QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
InitializedEntity Entity =
InitializedEntity::InitializeParameter(Context, ResultTy, false);
Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
return Result;
}
/// Check that the user is calling the appropriate va_start builtin for the
/// target and calling convention.
static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
TT.getArch() == llvm::Triple::aarch64_32);
bool IsWindows = TT.isOSWindows();
bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
if (IsX64 || IsAArch64) {
CallingConv CC = CC_C;
if (const FunctionDecl *FD = S.getCurFunctionDecl())
CC = FD->getType()->castAs<FunctionType>()->getCallConv();
if (IsMSVAStart) {
// Don't allow this in System V ABI functions.
if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
return S.Diag(Fn->getBeginLoc(),
diag::err_ms_va_start_used_in_sysv_function);
} else {
// On x86-64/AArch64 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 ((IsWindows && CC == CC_X86_64SysV) ||
(!IsWindows && CC == CC_Win64))
return S.Diag(Fn->getBeginLoc(),
diag::err_va_start_used_in_wrong_abi_function)
<< !IsWindows;
}
return false;
}
if (IsMSVAStart)
return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
return false;
}
static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
ParmVarDecl **LastParam = nullptr) {
// Determine whether the current function, block, or obj-c method is variadic
// and get its parameter list.
bool IsVariadic = false;
ArrayRef<ParmVarDecl *> Params;
DeclContext *Caller = S.CurContext;
if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
IsVariadic = Block->isVariadic();
Params = Block->parameters();
} else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
IsVariadic = FD->isVariadic();
Params = FD->parameters();
} else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
IsVariadic = MD->isVariadic();
// FIXME: This isn't correct for methods (results in bogus warning).
Params = MD->parameters();
} else if (isa<CapturedDecl>(Caller)) {
// We don't support va_start in a CapturedDecl.
S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
return true;
} else {
// This must be some other declcontext that parses exprs.
S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
return true;
}
if (!IsVariadic) {
S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
return true;
}
if (LastParam)
*LastParam = Params.empty() ? nullptr : Params.back();
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::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
Expr *Fn = TheCall->getCallee();
if (checkVAStartABI(*this, BuiltinID, Fn))
return true;
if (checkArgCount(*this, TheCall, 2))
return true;
// Type-check the first argument normally.
if (checkBuiltinArgument(*this, TheCall, 0))
return true;
// Check that the current function is variadic, and get its last parameter.
ParmVarDecl *LastParam;
if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
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())) {
SecondArgIsLastNamedArgument = PV == LastParam;
Type = PV->getType();
ParamLoc = PV->getLocation();
IsCRegister =
PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
}
}
if (!SecondArgIsLastNamedArgument)
Diag(TheCall->getArg(1)->getBeginLoc(),
diag::warn_second_arg_of_va_start_not_last_named_param);
else if (IsCRegister || Type->isReferenceType() ||
Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
// Promotable integers are UB, but enumerations need a bit of
// extra checking to see what their promotable type actually is.
if (!Type->isPromotableIntegerType())
return false;
if (!Type->isEnumeralType())
return true;
const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
return !(ED &&
Context.typesAreCompatible(ED->getPromotionType(), Type));
}()) {
unsigned Reason = 0;
if (Type->isReferenceType()) Reason = 1;
else if (IsCRegister) Reason = 2;
Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
Diag(ParamLoc, diag::note_parameter_type) << Type;
}
TheCall->setType(Context.VoidTy);
return false;
}
bool Sema::SemaBuiltinVAStartARMMicrosoft(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->getEndLoc(),
diag::err_typecheck_call_too_few_args_at_least)
<< 0 /*function call*/ << 3 << Call->getNumArgs();
// Type-check the first argument normally.
if (checkBuiltinArgument(*this, Call, 0))
return true;
// Check that the current function is variadic.
if (checkVAStartIsInVariadicFunction(*this, Func))
return true;
// __va_start on Windows does not validate the parameter qualifiers
const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
const QualType &ConstCharPtrTy =
Context.getPointerType(Context.CharTy.withConst());
if (!Arg1Ty->isPointerType() ||
Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
<< Arg1->getType() << ConstCharPtrTy << 1 /* different class */
<< 0 /* qualifier difference */
<< 3 /* parameter mismatch */
<< 2 << Arg1->getType() << ConstCharPtrTy;
const QualType SizeTy = Context.getSizeType();
if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
<< Arg2->getType() << SizeTy << 1 /* different class */
<< 0 /* qualifier difference */
<< 3 /* parameter mismatch */
<< 3 << Arg2->getType() << SizeTy;
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 (checkArgCount(*this, TheCall, 2))
return true;
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, TheCall->getExprLoc(), ACK_Comparison);
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()->getBeginLoc(),
diag::err_typecheck_call_invalid_ordered_compare)
<< OrigArg0.get()->getType() << OrigArg1.get()->getType()
<< SourceRange(OrigArg0.get()->getBeginLoc(),
OrigArg1.get()->getEndLoc());
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 (checkArgCount(*this, TheCall, NumArgs))
return true;
// __builtin_fpclassify is the only case where NumArgs != 1, so we can count
// on all preceding parameters just being int. Try all of those.
for (unsigned i = 0; i < NumArgs - 1; ++i) {
Expr *Arg = TheCall->getArg(i);
if (Arg->isTypeDependent())
return false;
ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
if (Res.isInvalid())
return true;
TheCall->setArg(i, Res.get());
}
Expr *OrigArg = TheCall->getArg(NumArgs-1);
if (OrigArg->isTypeDependent())
return false;
// Usual Unary Conversions will convert half to float, which we want for
// machines that use fp16 conversion intrinsics. Else, we wnat to leave the
// type how it is, but do normal L->Rvalue conversions.
if (Context.getTargetInfo().useFP16ConversionIntrinsics())
OrigArg = UsualUnaryConversions(OrigArg).get();
else
OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
TheCall->setArg(NumArgs - 1, OrigArg);
// This operation requires a non-_Complex floating-point number.
if (!OrigArg->getType()->isRealFloatingType())
return Diag(OrigArg->getBeginLoc(),
diag::err_typecheck_call_invalid_unary_fp)
<< OrigArg->getType() << OrigArg->getSourceRange();
return false;
}
/// Perform semantic analysis for a call to __builtin_complex.
bool Sema::SemaBuiltinComplex(CallExpr *TheCall) {
if (checkArgCount(*this, TheCall, 2))
return true;
bool Dependent = false;
for (unsigned I = 0; I != 2; ++I) {
Expr *Arg = TheCall->getArg(I);
QualType T = Arg->getType();
if (T->isDependentType()) {
Dependent = true;
continue;
}
// Despite supporting _Complex int, GCC requires a real floating point type
// for the operands of __builtin_complex.
if (!T->isRealFloatingType()) {
return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
<< Arg->getType() << Arg->getSourceRange();
}
ExprResult Converted = DefaultLvalueConversion(Arg);
if (Converted.isInvalid())
return true;
TheCall->setArg(I, Converted.get());
}
if (Dependent) {
TheCall->setType(Context.DependentTy);
return false;
}
Expr *Real = TheCall->getArg(0);
Expr *Imag = TheCall->getArg(1);
if (!Context.hasSameType(Real->getType(), Imag->getType())) {
return Diag(Real->getBeginLoc(),
diag::err_typecheck_call_different_arg_types)
<< Real->getType() << Imag->getType()
<< Real->getSourceRange() << Imag->getSourceRange();
}
// We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers;
// don't allow this builtin to form those types either.
// FIXME: Should we allow these types?
if (Real->getType()->isFloat16Type())
return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
<< "_Float16";
if (Real->getType()->isHalfType())
return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
<< "half";
TheCall->setType(Context.getComplexType(Real->getType()));
return false;
}
// Customized Sema Checking for VSX builtins that have the following signature:
// vector [...] builtinName(vector [...], vector [...], const int);
// Which takes the same type of vectors (any legal vector type) for the first
// two arguments and takes compile time constant for the third argument.
// Example builtins are :
// vector double vec_xxpermdi(vector double, vector double, int);
// vector short vec_xxsldwi(vector short, vector short, int);
bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
unsigned ExpectedNumArgs = 3;
if (checkArgCount(*this, TheCall, ExpectedNumArgs))
return true;
// Check the third argument is a compile time constant
if (!TheCall->getArg(2)->isIntegerConstantExpr(Context))
return Diag(TheCall->getBeginLoc(),
diag::err_vsx_builtin_nonconstant_argument)
<< 3 /* argument index */ << TheCall->getDirectCallee()
<< SourceRange(TheCall->getArg(2)->getBeginLoc(),
TheCall->getArg(2)->getEndLoc());
QualType Arg1Ty = TheCall->getArg(0)->getType();
QualType Arg2Ty = TheCall->getArg(1)->getType();
// Check the type of argument 1 and argument 2 are vectors.
SourceLocation BuiltinLoc = TheCall->getBeginLoc();
if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
(!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
<< TheCall->getDirectCallee()
<< SourceRange(TheCall->getArg(0)->getBeginLoc(),
TheCall->getArg(1)->getEndLoc());
}
// Check the first two arguments are the same type.
if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
<< TheCall->getDirectCallee()
<< SourceRange(TheCall->getArg(0)->getBeginLoc(),
TheCall->getArg(1)->getEndLoc());
}
// When default clang type checking is turned off and the customized type
// checking is used, the returning type of the function must be explicitly
// set. Otherwise it is _Bool by default.
TheCall->setType(Arg1Ty);
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->getEndLoc(),
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, 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->getBeginLoc(), diag::err_vec_builtin_non_vector)
<< TheCall->getDirectCallee()
<< SourceRange(TheCall->getArg(0)->getBeginLoc(),
TheCall->getArg(1)->getEndLoc()));
numElements = LHSType->castAs<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->castAs<VectorType>()->getNumElements() != numElements)
return ExprError(Diag(TheCall->getBeginLoc(),
diag::err_vec_builtin_incompatible_vector)
<< TheCall->getDirectCallee()
<< SourceRange(TheCall->getArg(1)->getBeginLoc(),
TheCall->getArg(1)->getEndLoc()));
} else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
return ExprError(Diag(TheCall->getBeginLoc(),
diag::err_vec_builtin_incompatible_vector)
<< TheCall->getDirectCallee()
<< SourceRange(TheCall->getArg(0)->getBeginLoc(),
TheCall->getArg(1)->getEndLoc()));
} else if (numElements != numResElements) {
QualType eltType = LHSType->castAs<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;
Optional<llvm::APSInt> Result;
if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context)))
return ExprError(Diag(TheCall->getBeginLoc(),
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->getBeginLoc(),
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()->getBeginLoc(),
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->castAs<VectorType>()->getNumElements();
unsigned DstElts = DstTy->castAs<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->getEndLoc(),
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->getBeginLoc(), diag::warn_assume_side_effects)
<< Arg->getSourceRange()
<< cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
return false;
}
/// Handle __builtin_alloca_with_align. This is declared
/// as (size_t, size_t) where the second size_t must be a power of 2 greater
/// than 8.
bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
// 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()) {
if (const auto *UE =
dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
if (UE->getKind() == UETT_AlignOf ||
UE->getKind() == UETT_PreferredAlignOf)
Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
<< Arg->getSourceRange();
llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
if (!Result.isPowerOf2())
return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
<< Arg->getSourceRange();
if (Result < Context.getCharWidth())
return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
<< (unsigned)Context.getCharWidth() << Arg->getSourceRange();
if (Result > std::numeric_limits<int32_t>::max())
return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
<< std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
}
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->getEndLoc(),
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->getBeginLoc(), diag::err_alignment_not_power_of_two)
<< Arg->getSourceRange();
if (Result > Sema::MaximumAlignment)
Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
<< Arg->getSourceRange() << Sema::MaximumAlignment;
}
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;
}
bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
unsigned BuiltinID =
cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
unsigned NumArgs = TheCall->getNumArgs();
unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
if (NumArgs < NumRequiredArgs) {
return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
<< 0 /* function call */ << NumRequiredArgs << NumArgs
<< TheCall->getSourceRange();
}
if (NumArgs >= NumRequiredArgs + 0x100) {
return Diag(TheCall->getEndLoc(),
diag::err_typecheck_call_too_many_args_at_most)
<< 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
<< TheCall->getSourceRange();
}
unsigned i = 0;
// For formatting call, check buffer arg.
if (!IsSizeCall) {
ExprResult Arg(TheCall->getArg(i));
InitializedEntity Entity = InitializedEntity::InitializeParameter(
Context, Context.VoidPtrTy, false);
Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
if (Arg.isInvalid())
return true;
TheCall->setArg(i, Arg.get());
i++;
}
// Check string literal arg.
unsigned FormatIdx = i;
{
ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
if (Arg.isInvalid())
return true;
TheCall->setArg(i, Arg.get());
i++;
}
// Make sure variadic args are scalar.
unsigned FirstDataArg = i;
while (i < NumArgs) {
ExprResult Arg = DefaultVariadicArgumentPromotion(
TheCall->getArg(i), VariadicFunction, nullptr);
if (Arg.isInvalid())
return true;
CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
if (ArgSize.getQuantity() >= 0x100) {
return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
<< i << (int)ArgSize.getQuantity() << 0xff
<< TheCall->getSourceRange();
}
TheCall->setArg(i, Arg.get());
i++;
}
// Check formatting specifiers. NOTE: We're only doing this for the non-size
// call to avoid duplicate diagnostics.
if (!IsSizeCall) {
llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
bool Success = CheckFormatArguments(
Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
CheckedVarArgs);
if (!Success)
return true;
}
if (IsSizeCall) {
TheCall->setType(Context.getSizeType());
} else {
TheCall->setType(Context.VoidPtrTy);
}
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;
Optional<llvm::APSInt> R;
if (!(R = Arg->getIntegerConstantExpr(Context)))
return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
<< FDecl->getDeclName() << Arg->getSourceRange();
Result = *R;
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, bool RangeIsError) {
if (isConstantEvaluated())
return false;
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) {
if (RangeIsError)
return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
<< Result.toString(10) << Low << High << Arg->getSourceRange();
else
// Defer the warning until we know if the code will be emitted so that
// dead code can ignore this.
DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
PDiag(diag::warn_argument_invalid_range)
<< Result.toString(10) << Low << High
<< Arg->getSourceRange());
}
return false;
}
/// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
/// TheCall is a constant expression is a multiple of Num..
bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
unsigned Num) {
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() % Num != 0)
return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
<< Num << Arg->getSourceRange();
return false;
}
/// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
/// constant expression representing a power of 2.
bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
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;
// Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
// and only if x is a power of 2.
if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
return false;
return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
<< Arg->getSourceRange();
}
static bool IsShiftedByte(llvm::APSInt Value) {
if (Value.isNegative())
return false;
// Check if it's a shifted byte, by shifting it down
while (true) {
// If the value fits in the bottom byte, the check passes.
if (Value < 0x100)
return true;
// Otherwise, if the value has _any_ bits in the bottom byte, the check
// fails.
if ((Value & 0xFF) != 0)
return false;
// If the bottom 8 bits are all 0, but something above that is nonzero,
// then shifting the value right by 8 bits won't affect whether it's a
// shifted byte or not. So do that, and go round again.
Value >>= 8;
}
}
/// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
/// a constant expression representing an arbitrary byte value shifted left by
/// a multiple of 8 bits.
bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
unsigned ArgBits) {
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;
// Truncate to the given size.
Result = Result.getLoBits(ArgBits);
Result.setIsUnsigned(true);
if (IsShiftedByte(Result))
return false;
return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
<< Arg->getSourceRange();
}
/// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
/// TheCall is a constant expression representing either a shifted byte value,
/// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
/// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
/// Arm MVE intrinsics.
bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
int ArgNum,
unsigned ArgBits) {
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;
// Truncate to the given size.
Result = Result.getLoBits(ArgBits);
Result.setIsUnsigned(true);
// Check to see if it's in either of the required forms.
if (IsShiftedByte(Result) ||
(Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
return false;
return Diag(TheCall->getBeginLoc(),
diag::err_argument_not_shifted_byte_or_xxff)
<< Arg->getSourceRange();
}
/// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
if (BuiltinID == AArch64::BI__builtin_arm_irg) {
if (checkArgCount(*this, TheCall, 2))
return true;
Expr *Arg0 = TheCall->getArg(0);
Expr *Arg1 = TheCall->getArg(1);
ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
if (FirstArg.isInvalid())
return true;
QualType FirstArgType = FirstArg.get()->getType();
if (!FirstArgType->isAnyPointerType())
return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
<< "first" << FirstArgType << Arg0->getSourceRange();
TheCall->setArg(0, FirstArg.get());
ExprResult SecArg = DefaultLvalueConversion(Arg1);
if (SecArg.isInvalid())
return true;
QualType SecArgType = SecArg.get()->getType();
if (!SecArgType->isIntegerType())
return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
<< "second" << SecArgType << Arg1->getSourceRange();
// Derive the return type from the pointer argument.
TheCall->setType(FirstArgType);
return false;
}
if (BuiltinID == AArch64::BI__builtin_arm_addg) {
if (checkArgCount(*this, TheCall, 2))
return true;
Expr *Arg0 = TheCall->getArg(0);
ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
if (FirstArg.isInvalid())
return true;
QualType FirstArgType = FirstArg.get()->getType();
if (!FirstArgType->isAnyPointerType())
return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
<< "first" << FirstArgType << Arg0->getSourceRange();
TheCall->setArg(0, FirstArg.get());
// Derive the return type from the pointer argument.
TheCall->setType(FirstArgType);
// Second arg must be an constant in range [0,15]
return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
}
if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
if (checkArgCount(*this, TheCall, 2))
return true;
Expr *Arg0 = TheCall->getArg(0);
Expr *Arg1 = TheCall->getArg(1);
ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
if (FirstArg.isInvalid())
return true;
QualType FirstArgType = FirstArg.get()->getType();
if (!FirstArgType->isAnyPointerType())
return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
<< "first" << FirstArgType << Arg0->getSourceRange();
QualType SecArgType = Arg1->getType();
if (!SecArgType->isIntegerType())
return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
<< "second" << SecArgType << Arg1->getSourceRange();
TheCall->setType(Context.IntTy);
return false;
}
if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
BuiltinID == AArch64::BI__builtin_arm_stg) {
if (checkArgCount(*this, TheCall, 1))
return true;
Expr *Arg0 = TheCall->getArg(0);
ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
if (FirstArg.isInvalid())
return true;
QualType FirstArgType = FirstArg.get()->getType();
if (!FirstArgType->isAnyPointerType())
return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
<< "first" << FirstArgType << Arg0->getSourceRange();
TheCall->setArg(0, FirstArg.get());
// Derive the return type from the pointer argument.
if (BuiltinID == AArch64::BI__builtin_arm_ldg)
TheCall->setType(FirstArgType);
return false;
}
if (BuiltinID == AArch64::BI__builtin_arm_subp) {
Expr *ArgA = TheCall->getArg(0);
Expr *ArgB = TheCall->getArg(1);
ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
return true;
QualType ArgTypeA = ArgExprA.get()->getType();
QualType ArgTypeB = ArgExprB.get()->getType();
auto isNull = [&] (Expr *E) -> bool {
return E->isNullPointerConstant(
Context, Expr::NPC_ValueDependentIsNotNull); };
// argument should be either a pointer or null
if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
<< "first" << ArgTypeA << ArgA->getSourceRange();
if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
<< "second" << ArgTypeB << ArgB->getSourceRange();
// Ensure Pointee types are compatible
if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
QualType pointeeA = ArgTypeA->getPointeeType();
QualType pointeeB = ArgTypeB->getPointeeType();
if (!Context.typesAreCompatible(
Context.getCanonicalType(pointeeA).getUnqualifiedType(),
Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
<< ArgTypeA << ArgTypeB << ArgA->getSourceRange()
<< ArgB->getSourceRange();
}
}
// at least one argument should be pointer type
if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
<< ArgTypeA << ArgTypeB << ArgA->getSourceRange();
if (isNull(ArgA)) // adopt type of the other pointer
ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
if (isNull(ArgB))
ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
TheCall->setArg(0, ArgExprA.get());
TheCall->setArg(1, ArgExprB.get());
TheCall->setType(Context.LongLongTy);
return false;
}
assert(false && "Unhandled ARM MTE intrinsic");
return true;
}
/// 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->getBeginLoc(), 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->getBeginLoc(), 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, 15, 15, 7});
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->getBeginLoc(), 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;
}
/// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity.
/// Emit an error and return true on failure; return false on success.
/// TypeStr is a string containing the type descriptor of the value returned by
/// the builtin and the descriptors of the expected type of the arguments.
bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, const char *TypeStr) {
assert((TypeStr[0] != '\0') &&
"Invalid types in PPC MMA builtin declaration");
unsigned Mask = 0;
unsigned ArgNum = 0;
// The first type in TypeStr is the type of the value returned by the
// builtin. So we first read that type and change the type of TheCall.
QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
TheCall->setType(type);
while (*TypeStr != '\0') {
Mask = 0;
QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
if (ArgNum >= TheCall->getNumArgs()) {
ArgNum++;
break;
}
Expr *Arg = TheCall->getArg(ArgNum);
QualType ArgType = Arg->getType();
if ((ExpectedType->isVoidPointerType() && !ArgType->isPointerType()) ||
(!ExpectedType->isVoidPointerType() &&
ArgType.getCanonicalType() != ExpectedType))
return Diag(Arg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
<< ArgType << ExpectedType << 1 << 0 << 0;
// If the value of the Mask is not 0, we have a constraint in the size of
// the integer argument so here we ensure the argument is a constant that
// is in the valid range.
if (Mask != 0 &&
SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true))
return true;
ArgNum++;
}
// In case we exited early from the previous loop, there are other types to
// read from TypeStr. So we need to read them all to ensure we have the right
// number of arguments in TheCall and if it is not the case, to display a
// better error message.
while (*TypeStr != '\0') {
(void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
ArgNum++;
}
if (checkArgCount(*this, TheCall, ArgNum))
return true;
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->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
<< SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
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->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
<< SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
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->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
<< SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
return false;
}
namespace {
class UncoveredArgHandler {
enum { Unknown = -1, AllCovered = -2 };
signed FirstUncoveredArg = Unknown;
SmallVector<const Expr *, 4> DiagnosticExprs;
public:
UncoveredArgHandler() = default;
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
};
} // namespace
static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
BinaryOperatorKind BinOpKind,
bool AddendIsRight) {
unsigned BitWidth = Offset.getBitWidth();
unsigned AddendBitWidth = Addend.getBitWidth();
// There might be negative interim results.
if (Addend.isUnsigned()) {
Addend = Addend.zext(++AddendBitWidth);
Addend.setIsSigned(true);
}
// Adjust the bit width of the APSInts.
if (AddendBitWidth > BitWidth) {
Offset = Offset.sext(AddendBitWidth);
BitWidth = AddendBitWidth;
} else if (BitWidth > AddendBitWidth) {
Addend = Addend.sext(BitWidth);
}
bool Ov = false;
llvm::APSInt ResOffset = Offset;
if (BinOpKind == BO_Add)
ResOffset = Offset.sadd_ov(Addend, Ov);
else {
assert(AddendIsRight && BinOpKind == BO_Sub &&
"operator must be add or sub with addend on the right");
ResOffset = Offset.ssub_ov(Addend, Ov);
}
// We add an offset to a pointer here so we should support an offset as big as
// possible.
if (Ov) {
assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
"index (intermediate) result too big");
Offset = Offset.sext(2 * BitWidth);
sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
return;
}
Offset = ResOffset;
}
namespace {
// This is a wrapper class around StringLiteral to support offsetted string
// literals as format strings. It takes the offset into account when returning
// the string and its length or the source locations to display notes correctly.
class FormatStringLiteral {
const StringLiteral *FExpr;
int64_t Offset;
public:
FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
: FExpr(fexpr), Offset(Offset) {}
StringRef getString() const {
return FExpr->getString().drop_front(Offset);
}
unsigned getByteLength() const {
return FExpr->getByteLength() - getCharByteWidth() * Offset;
}
unsigned getLength() const { return FExpr->getLength() - Offset; }
unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
QualType getType() const { return FExpr->getType(); }
bool isAscii() const { return FExpr->isAscii(); }
bool isWide() const { return FExpr->isWide(); }
bool isUTF8() const { return FExpr->isUTF8(); }
bool isUTF16() const { return FExpr->isUTF16(); }
bool isUTF32() const { return FExpr->isUTF32(); }
bool isPascal() const { return FExpr->isPascal(); }
SourceLocation getLocationOfByte(
unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
const TargetInfo &Target, unsigned *StartToken = nullptr,
unsigned *StartTokenByteOffset = nullptr) const {
return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
StartToken, StartTokenByteOffset);
}
SourceLocation getBeginLoc() const LLVM_READONLY {
return FExpr->getBeginLoc().getLocWithOffset(Offset);
}
SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
};
} // namespace
static void CheckFormatString(Sema &S, const FormatStringLiteral *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,
bool IgnoreStringsWithoutSpecifiers);
// 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,
llvm::APSInt Offset,
bool IgnoreStringsWithoutSpecifiers = false) {
if (S.isConstantEvaluated())
return SLCT_NotALiteral;
tryAgain:
assert(Offset.isSigned() && "invalid offset");
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(),
S.isConstantEvaluated())) {
if (Cond)
CheckRight = false;
else
CheckLeft = false;
}
// We need to maintain the offsets for the right and the left hand side
// separately to check if every possible indexed expression is a valid
// string literal. They might have different offsets for different string
// literals in the end.
StringLiteralCheckType Left;
if (!CheckLeft)
Left = SLCT_UncheckedLiteral;
else {
Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
HasVAListArg, format_idx, firstDataArg,
Type, CallType, InFunctionCall,
CheckedVarArgs, UncoveredArg, Offset,
IgnoreStringsWithoutSpecifiers);
if (Left == SLCT_NotALiteral || !CheckRight) {
return Left;
}
}
StringLiteralCheckType Right = checkFormatStringExpr(
S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
IgnoreStringsWithoutSpecifiers);
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, Offset);
}
}
// 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())) {
bool IsFirst = true;
StringLiteralCheckType CommonResult;
for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
StringLiteralCheckType Result = checkFormatStringExpr(
S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
IgnoreStringsWithoutSpecifiers);
if (IsFirst) {
CommonResult = Result;
IsFirst = false;
}
}
if (!IsFirst)
return CommonResult;
if (const auto *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, Offset,
IgnoreStringsWithoutSpecifiers);
}
}
}
return SLCT_NotALiteral;
}
case Stmt::ObjCMessageExprClass: {
const auto *ME = cast<ObjCMessageExpr>(E);
if (const auto *MD = ME->getMethodDecl()) {
if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
// As a special case heuristic, if we're using the method -[NSBundle
// localizedStringForKey:value:table:], ignore any key strings that lack
// format specifiers. The idea is that if the key doesn't have any
// format specifiers then its probably just a key to map to the
// localized strings. If it does have format specifiers though, then its
// likely that the text of the key is the format string in the
// programmer's language, and should be checked.
const ObjCInterfaceDecl *IFace;
if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
IFace->getIdentifier()->isStr("NSBundle") &&
MD->getSelector().isKeywordSelector(
{"localizedStringForKey", "value", "table"})) {
IgnoreStringsWithoutSpecifiers = true;
}
const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
return checkFormatStringExpr(
S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
IgnoreStringsWithoutSpecifiers);
}
}
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) {
if (Offset.isNegative() || Offset > StrE->getLength()) {
// TODO: It would be better to have an explicit warning for out of
// bounds literals.
return SLCT_NotALiteral;
}
FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
firstDataArg, Type, InFunctionCall, CallType,
CheckedVarArgs, UncoveredArg,
IgnoreStringsWithoutSpecifiers);
return SLCT_CheckedLiteral;
}
return SLCT_NotALiteral;
}
case Stmt::BinaryOperatorClass: {
const BinaryOperator *BinOp = cast<BinaryOperator>(E);
// A string literal + an int offset is still a string literal.
if (BinOp->isAdditiveOp()) {
Expr::EvalResult LResult, RResult;
bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
if (LIsInt != RIsInt) {
BinaryOperatorKind BinOpKind = BinOp->getOpcode();
if (LIsInt) {
if (BinOpKind == BO_Add) {
sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
E = BinOp->getRHS();
goto tryAgain;
}
} else {
sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
E = BinOp->getLHS();
goto tryAgain;
}
}
}
return SLCT_NotALiteral;
}
case Stmt::UnaryOperatorClass: {
const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
Expr::EvalResult IndexResult;
if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
Expr::SE_NoSideEffects,
S.isConstantEvaluated())) {
sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
/*RHS is int*/ true);
E = ASE->getBase();
goto tryAgain;
}
}
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_OSLog)
.Case("os_log", FST_OSLog)
.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()) {
(IsCheckedScope() ?
Diag(Loc, diag::err_missing_format_string) :
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,
/*no string offset*/ llvm::APSInt(64, false) = 0);
// 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]->getBeginLoc();
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) {
(IsCheckedScope() ?
Diag(FormatLoc, diag::err_format_nonliteral_noargs) :
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 {
(IsCheckedScope() ?
Diag(FormatLoc, diag::err_format_nonliteral) :
Diag(FormatLoc, diag::warn_format_nonliteral))
<< OrigFormatExpr->getSourceRange();
}
return false;
}
namespace {
class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
protected:
Sema &S;
const FormatStringLiteral *FExpr;
const Expr *OrigFormatExpr;
const Sema::FormatStringType FSType;
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 = false;
bool atFirstArg = true;
bool inFunctionCall;
Sema::VariadicCallType CallType;
llvm::SmallBitVector &CheckedVarArgs;
UncoveredArgHandler &UncoveredArg;
public:
CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
const Expr *origFormatExpr,
const Sema::FormatStringType type, 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), FSType(type),
FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
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;
// Note: IsFuncScanfLike = true means that the variadic function being called
// is scanf-like. IsFuncScanfLike = false means that the function is
// printf-like.
void CheckVarargsInCheckedScope(
const analyze_format_string::ConversionSpecifier &CS,
const char *StartSpecifier, unsigned SpecifierLen, const Expr *E,
SmallString<128> FSString, bool IsFuncScanfLike = false);
template <typename Range>
static void
EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
const 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);
};
} // 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 FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
S.getLangOpts(), S.Context.getTargetInfo());
}
void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
unsigned specifierLen){
EmitFormatDiagnostic((S.IsCheckedScope() ?
S.PDiag(diag::err_printf_incomplete_specifier) :
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 ||
DiagID == diag::err_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.IsCheckedScope() ?
S.PDiag(diag::err_format_non_standard) :
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.IsCheckedScope() ?
S.PDiag(diag::err_format_non_standard) :
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.IsCheckedScope() ?
S.PDiag(diag::err_format_non_standard) :
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.IsCheckedScope() ?
S.PDiag(diag::err_format_non_standard) :
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.IsCheckedScope() ?
S.PDiag(diag::err_format_non_standard_positional_arg) :
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.IsCheckedScope() ?
S.PDiag(diag::err_format_invalid_positional_specifier) :
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.IsCheckedScope() ?
S.PDiag(diag::err_printf_format_string_contains_null_char) :
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->getBeginLoc();
if (S.getSourceManager().isInSystemMacro(Loc))
return;
PartialDiagnostic PDiag = S.IsCheckedScope() ?
S.PDiag(diag::err_printf_data_arg_not_used) :
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)) {
llvm::UTF32 CodePoint;
const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
const llvm::UTF8 *E =
reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
llvm::ConversionResult Result =
llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
if (Result != llvm::conversionOK) {
unsigned char FirstChar = *csStart;
CodePoint = (llvm::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.IsCheckedScope() ?
S.PDiag(diag::err_format_invalid_conversion) :
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.IsCheckedScope() ?
S.PDiag(diag::err_format_mix_positional_nonpositional_args) :
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.IsCheckedScope() ?
S.PDiag(diag::err_printf_positional_arg_exceeds_data_args)
<< (argIndex+1) << NumDataArgs :
S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
<< (argIndex+1) << NumDataArgs)
: (S.IsCheckedScope() ?
S.PDiag(diag::err_printf_insufficient_data_args) :
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;
}
void CheckFormatHandler::CheckVarargsInCheckedScope(
const analyze_format_string::ConversionSpecifier &CS,
const char *StartSpecifier, unsigned SpecifierLen, const Expr *E,
SmallString<128> FSString, bool IsFuncScanfLike) {
// Check arguments to variadic functions like printf/scanf, etc in checked
// scope. This function is called per argument. E is current argument that
// needs checking.
using ConversionSpecifier = analyze_format_string::ConversionSpecifier;
// Do not proceed with the checking if we are not in a checked scope.
if (!S.IsCheckedScope())
return;
QualType ArgTy = E->getType();
switch (CS.getKind()) {
default:
// In scanf-like functions, only allow _Ptr type arguments.
if (IsFuncScanfLike) {
if (ArgTy->isCheckedPointerNtArrayType() ||
ArgTy->isNtCheckedArrayType() ||
ArgTy->isCheckedPointerArrayType() ||
ArgTy->isCheckedArrayType()) {
EmitFormatDiagnostic(
S.PDiag(diag::err_checked_scope_invalid_format_specifier_argument)
<< FSString << "_Ptr",
E->getExprLoc(), /*IsStringLocation*/false,
getSpecifierRange(StartSpecifier, SpecifierLen));
}
// In printf-like functions, only allow scalar type arguments with format
// specifiers other than %s.
// TODO: Currently, we do not handle the case where an out-of-bounds
// null-terminated array is passed as an argument to %s. The following code
// is allowed even though it might be a safety hole.
// _Checked {
// _Nt_array_ptr<char> p : count(5);
// printf("%s", p + 1234);
// }
// Issue https://github.com/microsoft/checkedc-clang/issues/1178 tracks this.
} else {
if (ArgTy->isCheckedPointerType()) {
EmitFormatDiagnostic(
S.PDiag(diag::err_checked_scope_invalid_format_specifier_argument)
<< FSString << "scalar",
E->getExprLoc(), /*IsStringLocation*/false,
getSpecifierRange(StartSpecifier, SpecifierLen));
}
}
break;
// Check if the argument corresponding to the %s format specifier is either
// _Nt_array_ptr or _Nt_checked.
case ConversionSpecifier::sArg:
if (IsFuncScanfLike) {
EmitFormatDiagnostic(
S.PDiag(diag::err_checked_scope_disallowed_format_specifier)
<< FSString << "in scanf",
E->getExprLoc(), /*IsStringLocation*/false,
getSpecifierRange(StartSpecifier, SpecifierLen));
} else if (!ArgTy->isCheckedPointerNtArrayType() &&
!ArgTy->isNtCheckedArrayType()) {
EmitFormatDiagnostic(
S.PDiag(diag::err_checked_scope_invalid_format_specifier_argument)
<< FSString << "null-terminated",
E->getExprLoc(), /*IsStringLocation*/false,
getSpecifierRange(StartSpecifier, SpecifierLen));
}
break;
// Disallow %p format specifier with scanf-like functions.
case ConversionSpecifier::pArg:
if (IsFuncScanfLike) {
EmitFormatDiagnostic(
S.PDiag(diag::err_checked_scope_disallowed_format_specifier)
<< FSString << "with scanf",
E->getExprLoc(), /*IsStringLocation*/false,
getSpecifierRange(StartSpecifier, SpecifierLen));
}
break;
// Disallow %n specifier in checked scope.
case ConversionSpecifier::nArg:
EmitFormatDiagnostic(
S.PDiag(diag::err_checked_scope_disallowed_format_specifier)
<< FSString << "",
E->getExprLoc(), /*IsStringLocation*/false,
getSpecifierRange(StartSpecifier, SpecifierLen));
break;
}
}
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);
}
/// If the format string is not within the function 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,
const 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 {
public:
CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
const Expr *origFormatExpr,
const Sema::FormatStringType type, 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, type, firstDataArg,
numDataArgs, beg, hasVAListArg, Args, formatIdx,
inFunctionCall, CallType, CheckedVarArgs,
UncoveredArg) {}
bool isObjCContext() const { return FSType == Sema::FST_NSString; }
/// Returns true if '%@' specifiers are allowed in the format string.
bool allowsObjCArg() const {
return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
FSType == Sema::FST_OSTrace;
}
bool HandleInvalidPrintfConversionSpecifier(
const analyze_printf::PrintfSpecifier &FS,
const char *startSpecifier,
unsigned specifierLen) override;
void handleInvalidMaskType(StringRef MaskType) 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;
};
} // 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());
}
void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
}
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.IsCheckedScope() ?
S.PDiag(diag::err_printf_asterisk_missing_arg) :
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.IsCheckedScope() ?
S.PDiag(diag::err_printf_asterisk_wrong_type) :
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.IsCheckedScope() ?
S.PDiag(diag::err_printf_nonsensical_optional_amount) :
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.IsCheckedScope() ?
S.PDiag(diag::err_printf_nonsensical_flag) :
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.IsCheckedScope() ?
S.PDiag(diag::err_printf_ignored_flag) :
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 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) {
using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
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) {
using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
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->getEndLoc());
S.Diag(E->getBeginLoc(), 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.IsCheckedScope() ?
S.PDiag(diag::err_format_conversion_argument_type_mismatch) :
S.PDiag(diag::warn_format_conversion_argument_type_mismatch))
<< AT.getRepresentativeTypeName(S.Context) << Ex->getType()
<< false << Ex->getSourceRange(),
Ex->getBeginLoc(), /*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.IsCheckedScope() ?
S.PDiag(diag::err_format_conversion_argument_type_mismatch) :
S.PDiag(diag::warn_format_conversion_argument_type_mismatch))
<< AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
<< false << Ex->getSourceRange(),
Ex->getBeginLoc(), /*IsStringLocation*/ false,
getSpecifierRange(startSpecifier, specifierLen));
return true;
}
// Check for using an Objective-C specific conversion specifier
// in a non-ObjC literal.
if (!allowsObjCArg() && CS.isObjCArg()) {
return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
specifierLen);
}
// %P can only be used with os_log.
if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
specifierLen);
}
// %n is not allowed with os_log.
if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
getLocationOfByte(CS.getStart()),
/*IsStringLocation*/ false,
getSpecifierRange(startSpecifier, specifierLen));
return true;
}
// Only scalars are allowed for os_trace.
if (FSType == Sema::FST_OSTrace &&
(CS.getKind() == ConversionSpecifier::PArg ||
CS.getKind() == ConversionSpecifier::sArg ||
CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
specifierLen);
}
// Check for use of public/private annotation outside of os_log().
if (FSType != Sema::FST_OSLog) {
if (FS.isPublic().isSet()) {
EmitFormatDiagnostic((S.IsCheckedScope() ?
S.PDiag(diag::err_format_invalid_annotation) :
S.PDiag(diag::warn_format_invalid_annotation))
<< "public",
getLocationOfByte(FS.isPublic().getPosition()),
/*IsStringLocation*/ false,
getSpecifierRange(startSpecifier, specifierLen));
}
if (FS.isPrivate().isSet()) {
EmitFormatDiagnostic((S.IsCheckedScope() ?
S.PDiag(diag::err_format_invalid_annotation) :
S.PDiag(diag::warn_format_invalid_annotation))
<< "private",
getLocationOfByte(FS.isPrivate().getPosition()),
/*IsStringLocation*/ false,
getSpecifierRange(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);
}
// Precision is mandatory for %P specifier.
if (CS.getKind() == ConversionSpecifier::PArg &&
FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
EmitFormatDiagnostic((S.IsCheckedScope() ?
S.PDiag(diag::err_format_P_no_precision) :
S.PDiag(diag::warn_format_P_no_precision)),
getLocationOfByte(startSpecifier),
/*IsStringLocation*/ false,
getSpecifierRange(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(),
S.getLangOpts()))
HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
(S.IsCheckedScope() ?
diag::err_format_nonsensical_length :
diag::warn_format_nonsensical_length));
else if (!FS.hasStandardLengthModifier())
HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
else if (!FS.hasStandardLengthConversionCombination())
HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
(S.IsCheckedScope() ?
diag::err_format_non_standard_conversion_spec :
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;
if (!checkFormatExpr(FS, startSpecifier, specifierLen, Arg))
return false;
SmallString<128> FSString;
llvm::raw_svector_ostream os(FSString);
FS.toString(os);
CheckVarargsInCheckedScope(CS, startSpecifier, specifierLen, Arg, FSString);
return true;
}
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("CFIndex", Context.getNSIntegerType())
.Case("NSInteger", Context.getNSIntegerType())
.Case("NSUInteger", Context.getNSUIntegerType())
.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());
}
/// Return true if \p ICE is an implicit argument promotion of an arithmetic
/// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
/// type do not count.
static bool
isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
QualType From = ICE->getSubExpr()->getType();
QualType To = ICE->getType();
// It's an integer promotion if the destination type is the promoted
// source type.
if (ICE->getCastKind() == CK_IntegralCast &&
From->isPromotableIntegerType() &&
S.Context.getPromotedIntegerType(From) == To)
return true;
// Look through vector types, since we do default argument promotion for
// those in OpenCL.
if (const auto *VecTy = From->getAs<ExtVectorType>())
From = VecTy->getElementType();
if (const auto *VecTy = To->getAs<ExtVectorType>())
To = VecTy->getElementType();
// It's a floating promotion if the source type is a lower rank.
return ICE->getCastKind() == CK_FloatingCast &&
S.Context.getFloatingTypeOrder(From, To) < 0;
}
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, isObjCContext());
if (!AT.isValid())
return true;
QualType ExprTy = E->getType();
while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
ExprTy = TET->getUnderlyingExpr()->getType();
}
// Diagnose attempts to print a boolean value as a character. Unlike other
// -Wformat diagnostics, this is fine from a type perspective, but it still
// doesn't make sense.
if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
E->isKnownToHaveBooleanValue()) {
const CharSourceRange &CSR =
getSpecifierRange(StartSpecifier, SpecifierLen);
SmallString<4> FSString;
llvm::raw_svector_ostream os(FSString);
FS.toString(os);
EmitFormatDiagnostic((S.IsCheckedScope() ?
S.PDiag(diag::err_format_bool_as_character) :
S.PDiag(diag::warn_format_bool_as_character))
<< FSString,
E->getExprLoc(), false, CSR);
return true;
}
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 *') and
// certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
if (isArithmeticArgumentPromotion(S, ICE)) {
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
const analyze_printf::ArgType::MatchKind ImplicitMatch =
AT.matchesType(S.Context, ExprTy);
if (ImplicitMatch == analyze_printf::ArgType::Match)
return true;
if (ImplicitMatch == ArgType::NoMatchPedantic ||
ImplicitMatch == ArgType::NoMatchTypeConfusion)
Match = ImplicitMatch;
}
}
} 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 (isObjCContext() &&
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->getBeginLoc(),
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()) {
// %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
// (long in ASTContext). Only complain to pedants.
if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
(AT.isSizeT() || AT.isPtrdiffT()) &&
AT.matchesType(S.Context, CastTy))
Match = ArgType::NoMatchPedantic;
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, isObjCContext());
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;
switch (Match) {
case ArgType::Match: llvm_unreachable("expected non-matching");
case ArgType::NoMatchPedantic:
if (S.IsCheckedScope())
Diag = diag::err_format_conversion_argument_type_mismatch_pedantic;
else
Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
break;
case ArgType::NoMatchTypeConfusion:
if (S.IsCheckedScope())
Diag = diag::err_format_conversion_argument_type_mismatch_confusion;
else
Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
break;
case ArgType::NoMatch:
if (S.IsCheckedScope())
Diag = diag::err_format_conversion_argument_type_mismatch;
else
Diag = diag::warn_format_conversion_argument_type_mismatch;
break;
}
// 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->getBeginLoc(),
/*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) || ShouldNotPrintDirectly)
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->getBeginLoc(), CastFix.str()));
} else {
// Otherwise, add parens around the expression as well as the cast.
CastFix << "(";
Hints.push_back(
FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
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;
unsigned Diag;
if (S.IsCheckedScope()) {
Diag = Match == ArgType::NoMatchPedantic
? diag::err_format_argument_needs_cast_pedantic
: diag::err_format_argument_needs_cast;
} else {
Diag = Match == ArgType::NoMatchPedantic
? diag::warn_format_argument_needs_cast_pedantic
: diag::warn_format_argument_needs_cast;
}
EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
<< E->getSourceRange(),
E->getBeginLoc(), /*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.IsCheckedScope() ?
S.PDiag(diag::err_format_conversion_argument_type_mismatch) :
S.PDiag(diag::warn_format_conversion_argument_type_mismatch))
<< AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
<< E->getSourceRange(),
E->getBeginLoc(), /*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;
switch (Match) {
case ArgType::Match: llvm_unreachable("expected non-matching");
case ArgType::NoMatchPedantic:
if (S.IsCheckedScope())
Diag = diag::err_format_conversion_argument_type_mismatch_pedantic;
else
Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
break;
case ArgType::NoMatchTypeConfusion:
if (S.IsCheckedScope())
Diag = diag::err_format_conversion_argument_type_mismatch_confusion;
else
Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
break;
case ArgType::NoMatch:
if (S.IsCheckedScope())
Diag = diag::err_format_conversion_argument_type_mismatch;
else
Diag = diag::warn_format_conversion_argument_type_mismatch;
break;
}
EmitFormatDiagnostic(
S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
<< IsEnum << CSR << E->getSourceRange(),
E->getBeginLoc(), /*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->getBeginLoc(), /*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->getBeginLoc(), /*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->getBeginLoc(), 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 FormatStringLiteral *fexpr,
const Expr *origFormatExpr, Sema::FormatStringType type,
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, type, 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;
};
} // namespace
void CheckScanfHandler::HandleIncompleteScanList(const char *start,
const char *end) {
EmitFormatDiagnostic((S.IsCheckedScope() ?
S.PDiag(diag::err_scanf_scanlist_incomplete) :
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 width is non-zero.
const OptionalAmount &Amt = FS.getFieldWidth();
if (S.IsCheckedScope() &&
Amt.getHowSpecified() != OptionalAmount::NotSpecified) {
const CharSourceRange &R = getSpecifierRange(startSpecifier, specifierLen);
EmitFormatDiagnostic(S.PDiag(diag::err_checked_scope_scanf_width),
getLocationOfByte(Amt.getStart()),
/*IsStringLocation*/true, R,
FixItHint::CreateRemoval(R));
}
if (Amt.getHowSpecified() == OptionalAmount::Constant) {
if (Amt.getConstantAmount() == 0) {
const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
Amt.getConstantLength());
EmitFormatDiagnostic((S.IsCheckedScope() ?
S.PDiag(diag::err_scanf_nonzero_width) :
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(),
S.getLangOpts()))
HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
(S.IsCheckedScope() ?
diag::err_format_nonsensical_length :
diag::warn_format_nonsensical_length));
else if (!FS.hasStandardLengthModifier())
HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
else if (!FS.hasStandardLengthConversionCombination())
HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
(S.IsCheckedScope() ?
diag::err_format_non_standard_conversion_spec :
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;
}
SmallString<128> FSString;
llvm::raw_svector_ostream os(FSString);
FS.toString(os);
CheckVarargsInCheckedScope(CS, startSpecifier, specifierLen, Ex, FSString,
/*IsFuncScanfLike*/ true);
analyze_format_string::ArgType::MatchKind Match =
AT.matchesType(S.Context, Ex->getType());
bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
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;
if (S.IsCheckedScope()) {
Diag =
Pedantic ? diag::err_format_conversion_argument_type_mismatch_pedantic
: diag::err_format_conversion_argument_type_mismatch;
} else {
Diag =
Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
: diag::warn_format_conversion_argument_type_mismatch;
}
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->getBeginLoc(),
/*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->getBeginLoc(),
/*IsStringLocation*/ false,
getSpecifierRange(startSpecifier, specifierLen));
}
return true;
}
static void CheckFormatString(Sema &S, const FormatStringLiteral *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,
bool IgnoreStringsWithoutSpecifiers) {
// CHECK: is the format string a wide literal?
if (!FExpr->isAscii() && !FExpr->isUTF8()) {
CheckFormatHandler::EmitFormatDiagnostic(
S, inFunctionCall, Args[format_idx],
(S.IsCheckedScope() ?
S.PDiag(diag::err_format_string_is_wide_literal) :
S.PDiag(diag::warn_format_string_is_wide_literal)),
FExpr->getBeginLoc(),
/*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;
if (IgnoreStringsWithoutSpecifiers &&
!analyze_format_string::parseFormatStringHasFormattingSpecifiers(
Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
return;
// 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.IsCheckedScope() ?
S.PDiag(diag::err_printf_format_string_not_null_terminated) :
S.PDiag(diag::warn_printf_format_string_not_null_terminated)),
FExpr->getBeginLoc(),
/*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
return;
}
// CHECK: empty format string?
if (StrLen == 0 && numDataArgs > 0) {
CheckFormatHandler::EmitFormatDiagnostic(
S, inFunctionCall, Args[format_idx],
(S.IsCheckedScope() ?
S.PDiag(diag::err_empty_format_string) :
S.PDiag(diag::warn_empty_format_string)),
FExpr->getBeginLoc(),
/*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
return;
}
if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
Type == Sema::FST_OSTrace) {
CheckPrintfHandler H(
S, FExpr, OrigFormatExpr, Type, 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, Type, 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;
}
template <std::size_t StrLen>
static bool IsStdFunction(const FunctionDecl *FDecl,
const char (&Str)[StrLen]) {
if (!FDecl)
return false;
if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
return false;
if (!FDecl->isInStdNamespace())
return false;
return true;
}
// Warn when using the wrong abs() function.
void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
const FunctionDecl *FDecl) {
if (Call->getNumArgs() != 1)
return;
unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
bool IsStdAbs = IsStdFunction(FDecl, "abs");
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: Warn on use of std::max and unsigned zero. r---------------===//
void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
const FunctionDecl *FDecl) {
if (!Call || !FDecl) return;
// Ignore template specializations and macros.
if (inTemplateInstantiation()) return;
if (Call->getExprLoc().isMacroID()) return;
// Only care about the one template argument, two function parameter std::max
if (Call->getNumArgs() != 2) return;
if (!IsStdFunction(FDecl, "max")) return;
const auto * ArgList = FDecl->getTemplateSpecializationArgs();
if (!ArgList) return;
if (ArgList->size() != 1) return;
// Check that template type argument is unsigned integer.
const auto& TA = ArgList->get(0);
if (TA.getKind() != TemplateArgument::Type) return;
QualType ArgType = TA.getAsType();
if (!ArgType->isUnsignedIntegerType()) return;
// See if either argument is a literal zero.
auto IsLiteralZeroArg = [](const Expr* E) -> bool {
const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
if (!MTE) return false;
const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
if (!Num) return false;
if (Num->getValue() != 0) return false;
return true;
};
const Expr *FirstArg = Call->getArg(0);
const Expr *SecondArg = Call->getArg(1);
const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
// Only warn when exactly one argument is zero.
if (IsFirstArgZero == IsSecondArgZero) return;
SourceRange FirstRange = FirstArg->getSourceRange();
SourceRange SecondRange = SecondArg->getSourceRange();
SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
<< IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
// Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
SourceRange RemovalRange;
if (IsFirstArgZero) {
RemovalRange = SourceRange(FirstRange.getBegin(),
SecondRange.getBegin().getLocWithOffset(-1));
} else {
RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
SecondRange.getEnd());
}
Diag(Call->getExprLoc(), diag::note_remove_max_call)
<< FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
<< FixItHint::CreateRemoval(RemovalRange);
}
//===--- CHECK: Standard memory functions ---------------------------------===//
/// 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->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()->getEndLoc()), ")")
<< 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;
}
/// 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;
}
static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
if (Unary->getKind() == UETT_SizeOf)
return Unary;
return nullptr;
}
/// If E is a sizeof expression, returns its argument expression,
/// otherwise returns NULL.
static const Expr *getSizeOfExprArg(const Expr *E) {
if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
if (!SizeOf->isArgumentType())
return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
return nullptr;
}
/// If E is a sizeof expression, returns its argument type.
static QualType getSizeOfArgType(const Expr *E) {
if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
return SizeOf->getTypeOfArgument();
return QualType();
}
namespace {
struct SearchNonTrivialToInitializeField
: DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
using Super =
DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
SourceLocation SL) {
if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
asDerived().visitArray(PDIK, AT, SL);
return;
}
Super::visitWithKind(PDIK, FT, SL);
}
void visitARCStrong(QualType FT, SourceLocation SL) {
S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
}
void visitARCWeak(QualType FT, SourceLocation SL) {
S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
}
void visitStruct(QualType FT, SourceLocation SL) {
for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
visit(FD->getType(), FD->getLocation());
}
void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
const ArrayType *AT, SourceLocation SL) {
visit(getContext().getBaseElementType(AT), SL);
}
void visitTrivial(QualType FT, SourceLocation SL) {}
static void diag(QualType RT, const Expr *E, Sema &S) {
SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
}
ASTContext &getContext() { return S.getASTContext(); }
const Expr *E;
Sema &S;
};
struct SearchNonTrivialToCopyField
: CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
SourceLocation SL) {
if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
asDerived().visitArray(PCK, AT, SL);
return;
}
Super::visitWithKind(PCK, FT, SL);
}
void visitARCStrong(QualType FT, SourceLocation SL) {
S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
}
void visitARCWeak(QualType FT, SourceLocation SL) {
S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
}
void visitStruct(QualType FT, SourceLocation SL) {
for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
visit(FD->getType(), FD->getLocation());
}
void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
SourceLocation SL) {
visit(getContext().getBaseElementType(AT), SL);
}
void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
SourceLocation SL) {}
void visitTrivial(QualType FT, SourceLocation SL) {}
void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
static void diag(QualType RT, const Expr *E, Sema &S) {
SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
}
ASTContext &getContext() { return S.getASTContext(); }
const Expr *E;
Sema &S;
};
}
/// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
return false;
return doesExprLikelyComputeSize(BO->getLHS()) ||
doesExprLikelyComputeSize(BO->getRHS());
}
return getAsSizeOfExpr(SizeofExpr) != nullptr;
}
/// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
///
/// \code
/// #define MACRO 0
/// foo(MACRO);
/// foo(0);
/// \endcode
///
/// This should return true for the first call to foo, but not for the second
/// (regardless of whether foo is a macro or function).
static bool isArgumentExpandedFromMacro(SourceManager &SM,
SourceLocation CallLoc,
SourceLocation ArgLoc) {
if (!CallLoc.isMacroID())
return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
}
/// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
/// last two arguments transposed.
static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
return;
const Expr *SizeArg =
Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
auto isLiteralZero = [](const Expr *E) {
return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
};
// If we're memsetting or bzeroing 0 bytes, then this is likely an error.
SourceLocation CallLoc = Call->getRParenLoc();
SourceManager &SM = S.getSourceManager();
if (isLiteralZero(SizeArg) &&
!isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
SourceLocation DiagLoc = SizeArg->getExprLoc();
// Some platforms #define bzero to __builtin_memset. See if this is the
// case, and if so, emit a better diagnostic.
if (BId == Builtin::BIbzero ||
(CallLoc.isMacroID() && Lexer::getImmediateMacroName(
CallLoc, SM, S.getLangOpts()) == "bzero")) {
S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
} else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
}
return;
}
// If the second argument to a memset is a sizeof expression and the third
// isn't, this is also likely an error. This should catch
// 'memset(buf, sizeof(buf), 0xff)'.
if (BId == Builtin::BImemset &&
doesExprLikelyComputeSize(Call->getArg(1)) &&
!doesExprLikelyComputeSize(Call->getArg(2))) {
SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
return;
}
}
/// 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 || BId == Builtin::BIbzero ? 2 : 3);
if (Call->getNumArgs() < ExpectedNumArgs)
return;
unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
BId == Builtin::BIstrndup ? 1 : 2);
unsigned LenArg =
(BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
Call->getBeginLoc(), Call->getRParenLoc()))
return;
// Catch cases like 'memset(buf, sizeof(buf), 0)'.
CheckMemaccessSize(*this, BId, Call);
// We have special checking when the length is a sizeof expression.
QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
llvm::FoldingSetNodeID SizeOfArgID;
// Although widely used, 'bzero' is not a standard function. Be more strict
// with the argument types before allowing diagnostics and only allow the
// form bzero(ptr, sizeof(...)).
QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
return;
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;
const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
// "overwritten" if we're warning about the destination for any call
// but memcmp; otherwise a verb appropriate to the call.
if (ArgIdx != 0 || IsCmp) {
if (BId == Builtin::BImemcpy)
OperationType = 1;
else if(BId == Builtin::BImemmove)
OperationType = 2;
else if (IsCmp)
OperationType = 3;
}
DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
PDiag(diag::warn_dyn_class_memaccess)
<< (IsCmp ? 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 if (const auto *RT = PointeeTy->getAs<RecordType>()) {
if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
PDiag(diag::warn_cstruct_memaccess)
<< ArgIdx << FnName << PointeeTy << 0);
SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
} else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
PDiag(diag::warn_cstruct_memaccess)
<< ArgIdx << FnName << PointeeTy << 1);
SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
} else {
continue;
}
} 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();
while (true) {
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->getBeginLoc(), 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->getBeginLoc(), 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->getBeginLoc(), 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->getBeginLoc(),
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->getBeginLoc();
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());
}
namespace {
void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
const UnaryOperator *UnaryExpr,
const VarDecl *Var) {
StorageClass Class = Var->getStorageClass();
if (Class == StorageClass::SC_Extern ||
Class == StorageClass::SC_PrivateExtern ||
Var->getType()->isReferenceType())
return;
S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
<< CalleeName << Var;
}
void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
const UnaryOperator *UnaryExpr, const Decl *D) {
if (const auto *Field = dyn_cast<FieldDecl>(D))
S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
<< CalleeName << Field;
}
void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
const UnaryOperator *UnaryExpr) {
if (UnaryExpr->getOpcode() != UnaryOperator::Opcode::UO_AddrOf)
return;
if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr()))
if (const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl()))
return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, Var);
if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
Lvalue->getMemberDecl());
}
void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
const DeclRefExpr *Lvalue) {
if (!Lvalue->getType()->isArrayType())
return;
const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
if (Var == nullptr)
return;
S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
<< CalleeName << Var;
}
} // namespace
/// Alerts the user that they are attempting to free a non-malloc'd object.
void Sema::CheckFreeArguments(const CallExpr *E) {
const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
const std::string CalleeName =
dyn_cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
}
void
Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
SourceLocation ReturnLoc,
bool isObjCMethod,
const AttrVec *Attrs,
const FunctionDecl *FD) {
// 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(/*ResultIfDependent*/true) &&
CheckNonNullExpr(*this, RetValExp))
Diag(ReturnLoc, diag::warn_operator_new_returns_null)
<< FD << getLangOpts().CPlusPlus11;
}
}
// PPC MMA non-pointer types are not allowed as return type. Checking the type
// here prevent the user from using a PPC MMA type as trailing return type.
if (Context.getTargetInfo().getTriple().isPPC64())
CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
}
//===--- 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. Note that this includes exactly one
/// sign bit if !NonNegative.
unsigned Width;
/// True if the int is known not to have negative values. If so, all leading
/// bits before Width are known zero, otherwise they are known to be the
/// same as the MSB within Width.
bool NonNegative;
IntRange(unsigned Width, bool NonNegative)
: Width(Width), NonNegative(NonNegative) {}
/// Number of bits excluding the sign bit.
unsigned valueBits() const {
return NonNegative ? Width : Width - 1;
}
/// 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();
if (!C.getLangOpts().CPlusPlus) {
// For enum types in C code, use the underlying datatype.
if (const EnumType *ET = dyn_cast<EnumType>(T))
T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
} else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
// For enum types in C++, use the known bit width of the enumerators.
EnumDecl *Enum = ET->getDecl();
// In C++11, enums can have a fixed underlying type. Use this type to
// compute the range.
if (Enum->isFixed()) {
return IntRange(C.getIntWidth(QualType(T, 0)),
!ET->isSignedIntegerOrEnumerationType());
}
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*/);
}
if (const auto *EIT = dyn_cast<ExtIntType>(T))
return IntRange(EIT->getNumBits(), EIT->isUnsigned());
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();
if (const auto *EIT = dyn_cast<ExtIntType>(T))
return IntRange(EIT->getNumBits(), EIT->isUnsigned());
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) {
bool Unsigned = L.NonNegative && R.NonNegative;
return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
L.NonNegative && R.NonNegative);
}
/// Return the range of a bitwise-AND of the two ranges.
static IntRange bit_and(IntRange L, IntRange R) {
unsigned Bits = std::max(L.Width, R.Width);
bool NonNegative = false;
if (L.NonNegative) {
Bits = std::min(Bits, L.Width);
NonNegative = true;
}
if (R.NonNegative) {
Bits = std::min(Bits, R.Width);
NonNegative = true;
}
return IntRange(Bits, NonNegative);
}
/// Return the range of a sum of the two ranges.
static IntRange sum(IntRange L, IntRange R) {
bool Unsigned = L.NonNegative && R.NonNegative;
return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
Unsigned);
}
/// Return the range of a difference of the two ranges.
static IntRange difference(IntRange L, IntRange R) {
// We need a 1-bit-wider range if:
// 1) LHS can be negative: least value can be reduced.
// 2) RHS can be negative: greatest value can be increased.
bool CanWiden = !L.NonNegative || !R.NonNegative;
bool Unsigned = L.NonNegative && R.Width == 0;
return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
!Unsigned,
Unsigned);
}
/// Return the range of a product of the two ranges.
static IntRange product(IntRange L, IntRange R) {
// If both LHS and RHS can be negative, we can form
// -2^L * -2^R = 2^(L + R)
// which requires L + R + 1 value bits to represent.
bool CanWiden = !L.NonNegative && !R.NonNegative;
bool Unsigned = L.NonNegative && R.NonNegative;
return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
Unsigned);
}
/// Return the range of a remainder operation between the two ranges.
static IntRange rem(IntRange L, IntRange R) {
// The result of a remainder can't be larger than the result of
// either side. The sign of the result is the sign of the LHS.
bool Unsigned = L.NonNegative;
return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
Unsigned);
}
};
} // namespace
static 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);
}
static 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());
}
static 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.
/// \param Approximate If \c true, return a likely range for the result: in
/// particular, assume that aritmetic on narrower types doesn't leave
/// those types. If \c false, return a range including all possible
/// result values.
static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
bool InConstantContext, bool Approximate) {
E = E->IgnoreParens();
// Try a full evaluation first.
Expr::EvalResult result;
if (E->EvaluateAsRValue(result, C, InConstantContext))
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, InConstantContext,
Approximate);
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),
InConstantContext, Approximate);
// 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, InConstantContext, Approximate);
// Otherwise, conservatively merge.
// GetExprRange requires an integer expression, but a throw expression
// results in a void type.
Expr *E = CO->getTrueExpr();
IntRange L = E->getType()->isVoidType()
? IntRange{0, true}
: GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
E = CO->getFalseExpr();
IntRange R = E->getType()->isVoidType()
? IntRange{0, true}
: GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
return IntRange::join(L, R);
}
if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
switch (BO->getOpcode()) {
case BO_Cmp:
llvm_unreachable("builtin <=> should have class type");
// 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, InConstantContext,
Approximate);
// 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:
Combine = IntRange::bit_and;
break;
// 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);
}
}
LLVM_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, InConstantContext,
Approximate);
// If the shift amount is a positive constant, drop the width by
// that much.
if (Optional<llvm::APSInt> shift =
BO->getRHS()->getIntegerConstantExpr(C)) {
if (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, InConstantContext,
Approximate);
case BO_Add:
if (!Approximate)
Combine = IntRange::sum;
break;
case BO_Sub:
if (BO->getLHS()->getType()->isPointerType())
return IntRange::forValueOfType(C, GetExprType(E));
if (!Approximate)
Combine = IntRange::difference;
break;
case BO_Mul:
if (!Approximate)
Combine = IntRange::product;
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, InConstantContext,
Approximate);
// If the divisor is constant, use that.
if (Optional<llvm::APSInt> divisor =
BO->getRHS()->getIntegerConstantExpr(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.
// FIXME: This is wrong if the LHS could be its minimal value and the RHS
// could be -1.
IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext,
Approximate);
return IntRange(L.Width, L.NonNegative && R.NonNegative);
}
case BO_Rem:
Combine = IntRange::rem;
break;
// The default behavior is okay for these.
case BO_Xor:
case BO_Or:
break;
}
// Combine the two ranges, but limit the result to the type in which we
// performed the computation.
QualType T = GetExprType(E);
unsigned opWidth = C.getIntWidth(T);
IntRange L =
GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate);
IntRange R =
GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate);
IntRange C = Combine(L, R);
C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
C.Width = std::min(C.Width, MaxWidth);
return C;
}
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, InConstantContext,
Approximate);
}
}
if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
Approximate);
if (const auto *BitField = E->getSourceBitField())
return IntRange(BitField->getBitWidthValue(C),
BitField->getType()->isUnsignedIntegerOrEnumerationType());
return IntRange::forValueOfType(C, GetExprType(E));
}
static IntRange GetExprRange(ASTContext &C, const Expr *E,
bool InConstantContext, bool Approximate) {
return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
Approximate);
}
/// Checks whether the given value, which currently has the given
/// source semantics, has the same value when coerced through the
/// target semantics.
static 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).
static 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));
}
static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
bool IsListInit = false);
static bool IsEnumConstOrFromMacro(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 true;
// Suppress cases where the value is expanded from a macro, unless that macro
// is how a language represents a boolean literal. This is the case in both C
// and Objective-C.
SourceLocation BeginLoc = E->getBeginLoc();
if (BeginLoc.isMacroID()) {
StringRef MacroName = Lexer::getImmediateMacroName(
BeginLoc, S.getSourceManager(), S.getLangOpts());
return MacroName != "YES" && MacroName != "NO" &&
MacroName != "true" && MacroName != "false";
}
return false;
}
static bool isKnownToHaveUnsignedValue(Expr *E) {
return E->getType()->isIntegerType() &&
(!E->getType()->isSignedIntegerType() ||
!E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
}
namespace {
/// The promoted range of values of a type. In general this has the
/// following structure:
///
/// |-----------| . . . |-----------|
/// ^ ^ ^ ^
/// Min HoleMin HoleMax Max
///
/// ... where there is only a hole if a signed type is promoted to unsigned
/// (in which case Min and Max are the smallest and largest representable
/// values).
struct PromotedRange {
// Min, or HoleMax if there is a hole.
llvm::APSInt PromotedMin;
// Max, or HoleMin if there is a hole.
llvm::APSInt PromotedMax;
PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
if (R.Width == 0)
PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
else if (R.Width >= BitWidth && !Unsigned) {
// Promotion made the type *narrower*. This happens when promoting
// a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
// Treat all values of 'signed int' as being in range for now.
PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
} else {
PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
.extOrTrunc(BitWidth);
PromotedMin.setIsUnsigned(Unsigned);
PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
.extOrTrunc(BitWidth);
PromotedMax.setIsUnsigned(Unsigned);
}
}
// Determine whether this range is contiguous (has no hole).
bool isContiguous() const { return PromotedMin <= PromotedMax; }
// Where a constant value is within the range.
enum ComparisonResult {
LT = 0x1,
LE = 0x2,
GT = 0x4,
GE = 0x8,
EQ = 0x10,
NE = 0x20,
InRangeFlag = 0x40,
Less = LE | LT | NE,
Min = LE | InRangeFlag,
InRange = InRangeFlag,
Max = GE | InRangeFlag,
Greater = GE | GT | NE,
OnlyValue = LE | GE | EQ | InRangeFlag,
InHole = NE
};
ComparisonResult compare(const llvm::APSInt &Value) const {
assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
Value.isUnsigned() == PromotedMin.isUnsigned());
if (!isContiguous()) {
assert(Value.isUnsigned() && "discontiguous range for signed compare");
if (Value.isMinValue()) return Min;
if (Value.isMaxValue()) return Max;
if (Value >= PromotedMin) return InRange;
if (Value <= PromotedMax) return InRange;
return InHole;
}
switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
case -1: return Less;
case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
case 1:
switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
case -1: return InRange;
case 0: return Max;
case 1: return Greater;
}
}
llvm_unreachable("impossible compare result");
}
static llvm::Optional<StringRef>
constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
if (Op == BO_Cmp) {
ComparisonResult LTFlag = LT, GTFlag = GT;
if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
if (R & EQ) return StringRef("'std::strong_ordering::equal'");
if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
return llvm::None;
}
ComparisonResult TrueFlag, FalseFlag;
if (Op == BO_EQ) {
TrueFlag = EQ;
FalseFlag = NE;
} else if (Op == BO_NE) {
TrueFlag = NE;
FalseFlag = EQ;
} else {
if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
TrueFlag = LT;
FalseFlag = GE;
} else {
TrueFlag = GT;
FalseFlag = LE;
}
if (Op == BO_GE || Op == BO_LE)
std::swap(TrueFlag, FalseFlag);
}
if (R & TrueFlag)
return StringRef("true");
if (R & FalseFlag)
return StringRef("false");
return llvm::None;
}
};
}
static 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();
}
static int classifyConstantValue(Expr *Constant) {
// The values of this enumeration are used in the diagnostics
// diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
enum ConstantValueKind {
Miscellaneous = 0,
LiteralTrue,
LiteralFalse
};
if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
return BL->getValue() ? ConstantValueKind::LiteralTrue
: ConstantValueKind::LiteralFalse;
return ConstantValueKind::Miscellaneous;
}
static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
Expr *Constant, Expr *Other,
const llvm::APSInt &Value,
bool RhsConstant) {
if (S.inTemplateInstantiation())
return false;
Expr *OriginalOther = Other;
Constant = Constant->IgnoreParenImpCasts();
Other = Other->IgnoreParenImpCasts();
// Suppress warnings on tautological comparisons between values of the same
// enumeration type. There are only two ways we could warn on this:
// - If the constant is outside the range of representable values of
// the enumeration. In such a case, we should warn about the cast
// to enumeration type, not about the comparison.
// - If the constant is the maximum / minimum in-range value. For an
// enumeratin type, such comparisons can be meaningful and useful.
if (Constant->getType()->isEnumeralType() &&
S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
return false;
IntRange OtherValueRange = GetExprRange(
S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false);
QualType OtherT = Other->getType();
if (const auto *AT = OtherT->getAs<AtomicType>())
OtherT = AT->getValueType();
IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
// Special case for ObjC BOOL on targets where its a typedef for a signed char
// (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
S.NSAPIObj->isObjCBOOLType(OtherT) &&
OtherT->isSpecificBuiltinType(BuiltinType::SChar);
// Whether we're treating Other as being a bool because of the form of
// expression despite it having another type (typically 'int' in C).
bool OtherIsBooleanDespiteType =
!OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
OtherTypeRange = OtherValueRange = IntRange::forBoolType();
// Check if all values in the range of possible values of this expression
// lead to the same comparison outcome.
PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(),
Value.isUnsigned());
auto Cmp = OtherPromotedValueRange.compare(Value);
auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
if (!Result)
return false;
// Also consider the range determined by the type alone. This allows us to
// classify the warning under the proper diagnostic group.
bool TautologicalTypeCompare = false;
{
PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
Value.isUnsigned());
auto TypeCmp = OtherPromotedTypeRange.compare(Value);
if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
RhsConstant)) {
TautologicalTypeCompare = true;
Cmp = TypeCmp;
Result = TypeResult;
}
}
// Don't warn if the non-constant operand actually always evaluates to the
// same value.
if (!TautologicalTypeCompare && OtherValueRange.Width == 0)
return false;
// Suppress the diagnostic for an in-range comparison if the constant comes
// from a macro or enumerator. We don't want to diagnose
//
// some_long_value <= INT_MAX
//
// when sizeof(int) == sizeof(long).
bool InRange = Cmp & PromotedRange::InRangeFlag;
if (InRange && IsEnumConstOrFromMacro(S, Constant))
return false;
// A comparison of an unsigned bit-field against 0 is really a type problem,
// even though at the type level the bit-field might promote to 'signed int'.
if (Other->refersToBitField() && InRange && Value == 0 &&
Other->getType()->isUnsignedIntegerOrEnumerationType())
TautologicalTypeCompare = true;
// 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());
// Should be enough for uint128 (39 decimal digits)
SmallString<64> PrettySourceValue;
llvm::raw_svector_ostream OS(PrettySourceValue);
if (ED) {
OS << '\'' << *ED << "' (" << Value << ")";
} else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
Constant->IgnoreParenImpCasts())) {
OS << (BL->getValue() ? "YES" : "NO");
} else {
OS << Value;
}
if (!TautologicalTypeCompare) {
S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
<< RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative
<< E->getOpcodeStr() << OS.str() << *Result
<< E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
return true;
}
if (IsObjCSignedCharBool) {
S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
S.PDiag(diag::warn_tautological_compare_objc_bool)
<< OS.str() << *Result);
return true;
}
// FIXME: We use a somewhat different formatting for the in-range cases and
// cases involving boolean values for historical reasons. We should pick a
// consistent way of presenting these diagnostics.
if (!InRange || Other->isKnownToHaveBooleanValue()) {
S.DiagRuntimeBehavior(
E->getOperatorLoc(), E,
S.PDiag(!InRange ? diag::warn_out_of_range_compare
: diag::warn_tautological_bool_compare)
<< OS.str() << classifyConstantValue(Constant) << OtherT
<< OtherIsBooleanDespiteType << *Result
<< E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
} else {
unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
? (HasEnumType(OriginalOther)
? diag::warn_unsigned_enum_always_true_comparison
: diag::warn_unsigned_always_true_comparison)
: diag::warn_tautological_constant_compare;
S.Diag(E->getOperatorLoc(), Diag)
<< RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
<< E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
}
return true;
}
/// Analyze the operands of the given comparison. Implements the
/// fallback case from AnalyzeComparison.
static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
}
/// Implements -Wsign-compare.
///
/// \param E the binary operator to check for warnings
static 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();
Expr *RHS = E->getRHS();
if (T->isIntegralType(S.Context)) {
Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context);
Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context);
// We don't care about expressions whose result is a constant.
if (RHSValue && LHSValue)
return AnalyzeImpConvsInComparison(S, E);
// We only care about expressions where just one side is literal
if ((bool)RHSValue ^ (bool)LHSValue) {
// Is the constant on the RHS or LHS?
const bool RhsConstant = (bool)RHSValue;
Expr *Const = RhsConstant ? RHS : LHS;
Expr *Other = RhsConstant ? LHS : RHS;
const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
// Check whether an integer constant comparison results in a value
// of 'true' or 'false'.
if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
return AnalyzeImpConvsInComparison(S, E);
}
}
if (!T->hasUnsignedIntegerRepresentation()) {
// 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.
return AnalyzeImpConvsInComparison(S, E);
}
LHS = LHS->IgnoreParenImpCasts();
RHS = RHS->IgnoreParenImpCasts();
if (!S.getLangOpts().CPlusPlus) {
// Avoid warning about comparison of integers with different signs when
// RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
// the type of `E`.
if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
}
// 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 {
return AnalyzeImpConvsInComparison(S, E);
}
// Otherwise, calculate the effective range of the signed operand.
IntRange signedRange = GetExprRange(
S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true);
// 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.
if (signedRange.NonNegative)
return;
// 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, S.isConstantEvaluated(),
/*Approximate*/ true);
// 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.
static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
SourceLocation InitLoc) {
assert(Bitfield->isBitField());
if (Bitfield->isInvalidDecl())
return false;
// White-list bool bitfields.
QualType BitfieldType = Bitfield->getType();
if (BitfieldType->isBooleanType())
return false;
if (BitfieldType->isEnumeralType()) {
EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
// If the underlying enum type was not explicitly specified as an unsigned
// type and the enum contain only positive values, MSVC++ will cause an
// inconsistency by storing this as a signed type.
if (S.getLangOpts().CPlusPlus11 &&
!BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
BitfieldEnumDecl->getNumPositiveBits() > 0 &&
BitfieldEnumDecl->getNumNegativeBits() == 0) {
S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
<< BitfieldEnumDecl;
}
}
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();
unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
Expr::EvalResult Result;
if (!OriginalInit->EvaluateAsInt(Result, S.Context,
Expr::SE_AllowSideEffects)) {
// The RHS is not constant. If the RHS has an enum type, make sure the
// bitfield is wide enough to hold all the values of the enum without
// truncation.
if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
EnumDecl *ED = EnumTy->getDecl();
bool SignedBitfield = BitfieldType->isSignedIntegerType();
// Enum types are implicitly signed on Windows, so check if there are any
// negative enumerators to see if the enum was intended to be signed or
// not.
bool SignedEnum = ED->getNumNegativeBits() > 0;
// Check for surprising sign changes when assigning enum values to a
// bitfield of different signedness. If the bitfield is signed and we
// have exactly the right number of bits to store this unsigned enum,
// suggest changing the enum to an unsigned type. This typically happens
// on Windows where unfixed enums always use an underlying type of 'int'.
unsigned DiagID = 0;
if (SignedEnum && !SignedBitfield) {
DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
} else if (SignedBitfield && !SignedEnum &&
ED->getNumPositiveBits() == FieldWidth) {
DiagID = diag::warn_signed_bitfield_enum_conversion;
}
if (DiagID) {
S.Diag(InitLoc, DiagID) << Bitfield << ED;
TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
SourceRange TypeRange =
TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
<< SignedEnum << TypeRange;
}
// Compute the required bitwidth. If the enum has negative values, we need
// one more bit than the normal number of positive bits to represent the
// sign bit.
unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
ED->getNumNegativeBits())
: ED->getNumPositiveBits();
// Check the bitwidth.
if (BitsNeeded > FieldWidth) {
Expr *WidthExpr = Bitfield->getBitWidth();
S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
<< Bitfield << ED;
S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
<< BitsNeeded << ED << WidthExpr->getSourceRange();
}
}
return false;
}
llvm::APSInt Value = Result.Val.getInt();
unsigned OriginalWidth = Value.getBitWidth();
if (!Value.isSigned() || Value.isNegative())
if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
OriginalWidth = Value.getMinSignedBits();
if (OriginalWidth <= FieldWidth)
return false;
// Compute the value which the bitfield will contain.
llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
TruncatedValue.setIsSigned(BitfieldType->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.
static 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 implicitly sequentially-consistent atomic assignment.
if (E->getLHS()->getType()->isAtomicType())
S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
}
/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
static 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.
static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
SourceLocation CContext,
unsigned diag, bool pruneControlFlow = false) {
DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
}
static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
}
static void adornObjCBoolConversionDiagWithTernaryFixit(
Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
Expr *Ignored = SourceExpr->IgnoreImplicit();
if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
Ignored = OVE->getSourceExpr();
bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
isa<BinaryOperator>(Ignored) ||
isa<CXXOperatorCallExpr>(Ignored);
SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
if (NeedsParens)
Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
<< FixItHint::CreateInsertion(EndLoc, ")");
Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
}
/// Diagnose an implicit cast from a floating point value to an integer value.
static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
SourceLocation CContext) {
const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
const bool PruneWarnings = S.inTemplateInstantiation();
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) {
if (isObjCSignedCharBool(S, T)) {
return adornObjCBoolConversionDiagWithTernaryFixit(
S, E,
S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
<< E->getType());
}
return DiagnoseImpCast(S, E, T, CContext,
diag::warn_impcast_float_integer, PruneWarnings);
}
bool isExact = false;
llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
T->hasUnsignedIntegerRepresentation());
llvm::APFloat::opStatus Result = Value.convertToInteger(
IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
// 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);
if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
return adornObjCBoolConversionDiagWithTernaryFixit(
S, E,
S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
<< PrettySourceValue);
}
if (Result == llvm::APFloat::opOK && isExact) {
if (IsLiteral) return;
return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
PruneWarnings);
}
// Conversion of a floating-point value to a non-bool integer where the
// integral part cannot be represented by the integer type is undefined.
if (!IsBool && Result == llvm::APFloat::opInvalidOp)
return DiagnoseImpCast(
S, E, T, CContext,
IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
: diag::warn_impcast_float_to_integer_out_of_range,
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;
}
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);
}
}
/// Analyze the given compound assignment for the possible losing of
/// floating-point precision.
static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
assert(isa<CompoundAssignOperator>(E) &&
"Must be compound assignment operation");
// Recurse on the LHS and RHS in here
AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
if (E->getLHS()->getType()->isAtomicType())
S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
// Now check the outermost expression
const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
const auto *RBT = cast<CompoundAssignOperator>(E)
->getComputationResultType()
->getAs<BuiltinType>();
// The below checks assume source is floating point.
if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
// If source is floating point but target is an integer.
if (ResultBT->isInteger())
return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
E->getExprLoc(), diag::warn_impcast_float_integer);
if (!ResultBT->isFloatingPoint())
return;
// If both source and target are floating points, warn about losing precision.
int Order = S.getASTContext().getFloatingTypeSemanticOrder(
QualType(ResultBT, 0), QualType(RBT, 0));
if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
// warn about dropping FP rank.
DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
diag::warn_impcast_float_result_precision);
}
static 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);
}
static 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()));
}
static 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);
}
}
}
static 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.
Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
CC = S.SourceMgr.getTopMacroCallerLoc(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).getBegin();
}
// 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 << SourceRange(CC)
<< FixItHint::CreateReplacement(Loc,
S.getFixItZeroLiteralForType(T, Loc));
}
static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
ObjCArrayLiteral *ArrayLiteral);
static void
checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
ObjCDictionaryLiteral *DictionaryLiteral);
/// Check a single element within a collection literal against the
/// target element type.
static 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->getBeginLoc(), 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.
static 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.
static 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.
static 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->getBeginLoc())[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;
}
static const IntegerLiteral *getIntegerLiteral(Expr *E) {
const auto *IL = dyn_cast<IntegerLiteral>(E);
if (!IL) {
if (auto *UO = dyn_cast<UnaryOperator>(E)) {
if (UO->getOpcode() == UO_Minus)
return dyn_cast<IntegerLiteral>(UO->getSubExpr());
}
}
return IL;
}
static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
E = E->IgnoreParenImpCasts();
SourceLocation ExprLoc = E->getExprLoc();
if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
BinaryOperator::Opcode Opc = BO->getOpcode();
Expr::EvalResult Result;
// Do not diagnose unsigned shifts.
if (Opc == BO_Shl) {
const auto *LHS = getIntegerLiteral(BO->getLHS());
const auto *RHS = getIntegerLiteral(BO->getRHS());
if (LHS && LHS->getValue() == 0)
S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
else if (!E->isValueDependent() && LHS && RHS &&
RHS->getValue().isNonNegative() &&
E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
S.Diag(ExprLoc, diag::warn_left_shift_always)
<< (Result.Val.getInt() != 0);
else if (E->getType()->isSignedIntegerType())
S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
}
}
if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
if (!LHS || !RHS)
return;
if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
(RHS->getValue() == 0 || RHS->getValue() == 1))
// Do not diagnose common idioms.
return;
if (LHS->getValue() != 0 && RHS->getValue() != 0)
S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
}
}
static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
SourceLocation CC,
bool *ICContext = nullptr,
bool IsListInit = false) {
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;
if (Source->isAtomicType())
S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
// 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));
}
}
// If the we're converting a constant to an ObjC BOOL on a platform where BOOL
// is a typedef for signed char (macOS), then that constant value has to be 1
// or 0.
if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
Expr::EvalResult Result;
if (E->EvaluateAsInt(Result, S.getASTContext(),
Expr::SE_AllowSideEffects)) {
if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
adornObjCBoolConversionDiagWithTernaryFixit(
S, E,
S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
<< Result.Val.getInt().toString(10));
}
return;
}
}
// 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) || Target->isBooleanType())
return;
return DiagnoseImpCast(S, E, T, CC,
S.getLangOpts().CPlusPlus
? diag::err_impcast_complex_scalar
: 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.
int Order = S.getASTContext().getFloatingTypeSemanticOrder(
QualType(SourceBT, 0), QualType(TargetBT, 0));
if (Order > 0) {
// 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 (Order < 0) {
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;
}
// Valid casts involving fixed point types should be accounted for here.
if (Source->isFixedPointType()) {
if (Target->isUnsaturatedFixedPointType()) {
Expr::EvalResult Result;
if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
S.isConstantEvaluated())) {
llvm::APFixedPoint Value = Result.Val.getFixedPoint();
llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T);
if (Value > MaxVal || Value < MinVal) {
S.DiagRuntimeBehavior(E->getExprLoc(), E,
S.PDiag(diag::warn_impcast_fixed_point_range)
<< Value.toString() << T
<< E->getSourceRange()
<< clang::SourceRange(CC));
return;
}
}
} else if (Target->isIntegerType()) {
Expr::EvalResult Result;
if (!S.isConstantEvaluated() &&
E->EvaluateAsFixedPoint(Result, S.Context,
Expr::SE_AllowSideEffects)) {
llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
bool Overflowed;
llvm::APSInt IntResult = FXResult.convertToInt(
S.Context.getIntWidth(T),
Target->isSignedIntegerOrEnumerationType(), &Overflowed);
if (Overflowed) {
S.DiagRuntimeBehavior(E->getExprLoc(), E,
S.PDiag(diag::warn_impcast_fixed_point_range)
<< FXResult.toString() << T
<< E->getSourceRange()
<< clang::SourceRange(CC));
return;
}
}
}
} else if (Target->isUnsaturatedFixedPointType()) {
if (Source->isIntegerType()) {
Expr::EvalResult Result;
if (!S.isConstantEvaluated() &&
E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
llvm::APSInt Value = Result.Val.getInt();
bool Overflowed;
llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
Value, S.Context.getFixedPointSemantics(T), &Overflowed);
if (Overflowed) {
S.DiagRuntimeBehavior(E->getExprLoc(), E,
S.PDiag(diag::warn_impcast_fixed_point_range)
<< Value.toString(/*Radix=*/10) << T
<< E->getSourceRange()
<< clang::SourceRange(CC));
return;
}
}
}
}
// If we are casting an integer type to a floating point type without
// initialization-list syntax, we might lose accuracy if the floating
// point type has a narrower significand than the integer type.
if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
TargetBT->isFloatingType() && !IsListInit) {
// Determine the number of precision bits in the source integer type.
IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(),
/*Approximate*/ true);
unsigned int SourcePrecision = SourceRange.Width;
// Determine the number of precision bits in the
// target floating point type.
unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
if (SourcePrecision > 0 && TargetPrecision > 0 &&
SourcePrecision > TargetPrecision) {
if (Optional<llvm::APSInt> SourceInt =
E->getIntegerConstantExpr(S.Context)) {
// If the source integer is a constant, convert it to the target
// floating point type. Issue a warning if the value changes
// during the whole conversion.
llvm::APFloat TargetFloatValue(
S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
llvm::APFloat::opStatus ConversionStatus =
TargetFloatValue.convertFromAPInt(
*SourceInt, SourceBT->isSignedInteger(),
llvm::APFloat::rmNearestTiesToEven);
if (ConversionStatus != llvm::APFloat::opOK) {
std::string PrettySourceValue = SourceInt->toString(10);
SmallString<32> PrettyTargetValue;
TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
S.DiagRuntimeBehavior(
E->getExprLoc(), E,
S.PDiag(diag::warn_impcast_integer_float_precision_constant)
<< PrettySourceValue << PrettyTargetValue << E->getType() << T
<< E->getSourceRange() << clang::SourceRange(CC));
}
} else {
// Otherwise, the implicit conversion may lose precision.
DiagnoseImpCast(S, E, T, CC,
diag::warn_impcast_integer_float_precision);
}
}
}
DiagnoseNullConversion(S, E, T, CC);
S.DiscardMisalignedMemberAddress(Target, E);
if (Target->isBooleanType())
DiagnoseIntInBoolContext(S, E);
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;
if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
!E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
return adornObjCBoolConversionDiagWithTernaryFixit(
S, E,
S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
<< E->getType());
}
IntRange SourceTypeRange =
IntRange::forTargetOfCanonicalType(S.Context, Source);
IntRange LikelySourceRange =
GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true);
IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
if (LikelySourceRange.Width > TargetRange.Width) {
// If the source is a constant, use a default-on diagnostic.
// TODO: this should happen for bitfield stores, too.
Expr::EvalResult Result;
if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
S.isConstantEvaluated())) {
llvm::APSInt Value(32);
Value = Result.Val.getInt();
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() << 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 > SourceTypeRange.Width) {
if (auto *UO = dyn_cast<UnaryOperator>(E))
if (UO->getOpcode() == UO_Minus)
if (Source->isUnsignedIntegerType()) {
if (Target->isUnsignedIntegerType())
return DiagnoseImpCast(S, E, T, CC,
diag::warn_impcast_high_order_zero_bits);
if (Target->isSignedIntegerType())
return DiagnoseImpCast(S, E, T, CC,
diag::warn_impcast_nonnegative_result);
}
}
if (TargetRange.Width == LikelySourceRange.Width &&
!TargetRange.NonNegative && LikelySourceRange.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.
Expr::EvalResult Result;
if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
!S.SourceMgr.isInSystemMacro(CC)) {
llvm::APSInt Value = Result.Val.getInt();
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() << SourceRange(CC));
return;
}
}
// Fall through for non-constants to give a sign conversion warning.
}
if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) ||
(!TargetRange.NonNegative && LikelySourceRange.NonNegative &&
LikelySourceRange.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);
}
}
static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
SourceLocation CC, QualType T);
static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
SourceLocation CC, bool &ICContext) {
E = E->IgnoreParenImpCasts();
if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
return CheckConditionalOperator(S, CO, CC, T);
AnalyzeImplicitConversions(S, E, CC);
if (E->getType() != T)
return CheckImplicitConversion(S, E, T, CC, &ICContext);
}
static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
SourceLocation CC, QualType T) {
AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
Expr *TrueExpr = E->getTrueExpr();
if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
TrueExpr = BCO->getCommon();
bool Suspicious = false;
CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
if (T->isBooleanType())
DiagnoseIntInBoolContext(S, E);
// 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, TrueExpr->IgnoreParenImpCasts(),
E->getType(), CC, &Suspicious);
if (!Suspicious)
CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
E->getType(), CC, &Suspicious);
}
/// Check conversion of given expression to boolean.
/// Input argument E is a logical expression.
static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
if (S.getLangOpts().Bool)
return;
if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
return;
CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
}
namespace {
struct AnalyzeImplicitConversionsWorkItem {
Expr *E;
SourceLocation CC;
bool IsListInit;
};
}
/// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
/// that should be visited are added to WorkList.
static void AnalyzeImplicitConversions(
Sema &S, AnalyzeImplicitConversionsWorkItem Item,
llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
Expr *OrigE = Item.E;
SourceLocation CC = Item.CC;
QualType T = OrigE->getType();
Expr *E = OrigE->IgnoreParenImpCasts();
// Propagate whether we are in a C++ list initialization expression.
// If so, we do not issue warnings for implicit int-float conversion
// precision loss, because C++11 narrowing already handles it.
bool IsListInit = Item.IsListInit ||
(isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
if (E->isTypeDependent() || E->isValueDependent())
return;
Expr *SourceExpr = E;
// Examine, but don't traverse into the source expression of an
// OpaqueValueExpr, since it may have multiple parents and we don't want to
// emit duplicate diagnostics. Its fine to examine the form or attempt to
// evaluate it in the context of checking the specific conversion to T though.
if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
if (auto *Src = OVE->getSourceExpr())
SourceExpr = Src;
if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
if (UO->getOpcode() == UO_Not &&
UO->getSubExpr()->isKnownToHaveBooleanValue())
S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
<< OrigE->getSourceRange() << T->isBooleanType()
<< FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
// For conditional operators, we analyze the arguments as if they
// were being fed directly into the output.
if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
CheckConditionalOperator(S, CO, CC, T);
return;
}
// Check implicit argument conversions for function calls.
if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
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 (SourceExpr->getType() != T)
CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
// 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))
WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
}
// Skip past explicit casts.
if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
E = CE->getSubExpr()->IgnoreParenImpCasts();
if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
WorkList.push_back({E, CC, IsListInit});
return;
}
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);
// And with compound assignments.
if (BO->isAssignmentOp())
return AnalyzeCompoundAssignment(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;
WorkList.push_back({ChildExpr, CC, IsListInit});
}
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);
} else if (U->getOpcode() != UO_AddrOf) {
if (U->getSubExpr()->getType()->isAtomicType())
S.Diag(U->getSubExpr()->getBeginLoc(),
diag::warn_atomic_implicit_seq_cst);
}
}
}
/// AnalyzeImplicitConversions - Find and report any interesting
/// implicit conversions in the given expression. There are a couple
/// of competing diagnostics here, -Wconversion and -Wsign-compare.
static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
bool IsListInit/*= false*/) {
llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
WorkList.push_back({OrigE, CC, IsListInit});
while (!WorkList.empty())
AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
}
/// Diagnose integer type and any valid implicit conversion to it.
static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
// Taking into account implicit conversions,
// allow any integer.
if (!E->getType()->isIntegerType()) {
S.Diag(E->getBeginLoc(),
diag::err_opencl_enqueue_kernel_invalid_local_size_type);
return true;
}
// Potentially emit standard warnings for implicit conversions if enabled
// using -Wconversion.
CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
return false;
}
// 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,
const 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;
}
/// 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 = [&](const Attr *NonnullAttr) {
bool IsParam = isa<NonNullAttr>(NonnullAttr);
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;
Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
};
// 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 (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
ComplainAboutNonnullParamOrCall(A);
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 (const Attr *A = PV->getAttr<NonNullAttr>()) {
ComplainAboutNonnullParamOrCall(A);
return;
}
if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
// Skip function template not specialized yet.
if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
return;
auto ParamIter = llvm::find(FD->parameters(), 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(NonNull);
return;
}
for (const ParamIdx &ArgNo : NonNull->args()) {
if (ArgNo.getASTIndex() == ParamNo) {
ComplainAboutNonnullParamOrCall(NonNull);
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->getBeginLoc(), "&");
// 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->getEndLoc()), "()");
}
/// 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 *OriginalE = Exprs.pop_back_val();
Expr *E = OriginalE->IgnoreParenCasts();
if (isa<BinaryOperator>(E)) {
E->EvaluateForOverflow(Context);
continue;
}
if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
Exprs.append(InitList->inits().begin(), InitList->inits().end());
else if (isa<ObjCBoxedExpr>(OriginalE))
E->EvaluateForOverflow(Context);
else if (auto Call = dyn_cast<CallExpr>(E))
Exprs.append(Call->arg_begin(), Call->arg_end());
else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
Exprs.append(Message->arg_begin(), Message->arg_end());
} while (!Exprs.empty());
}
namespace {
/// Visitor for expressions which looks for unsequenced operations on the
/// same object.
class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
/// 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;
unsigned Merged : 1;
};
SmallVector<Value, 8> Values;
public:
/// A region within an expression which may be sequenced with respect
/// to some other region.
class Seq {
friend class SequenceTree;
unsigned Index;
explicit Seq(unsigned N) : Index(N) {}
public:
Seq() : Index(0) {}
};
SequenceTree() { Values.push_back(Value(0)); }
Seq root() const { return Seq(0); }
/// 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);
}
/// Merge a sequence of operations into its parent.
void merge(Seq S) {
Values[S.Index].Merged = true;
}
/// 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:
/// 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.
using Object = const NamedDecl *;
/// 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
};
/// Bundle together a sequencing region and the expression corresponding
/// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
struct Usage {
const Expr *UsageExpr;
SequenceTree::Seq Seq;
Usage() : UsageExpr(nullptr), Seq() {}
};
struct UsageInfo {
Usage Uses[UK_Count];
/// Have we issued a diagnostic for this object already?
bool Diagnosed;
UsageInfo() : Uses(), Diagnosed(false) {}
};
using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
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 = nullptr;
/// Expressions to check later. We defer checking these to reduce
/// stack usage.
SmallVectorImpl<const 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 (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
// Add a new usage with usage kind UK_ModAsValue, and then restore
// the previous usage with UK_ModAsSideEffect (thus clearing it if
// the previous one was empty).
UsageInfo &UI = Self.UsageMap[M.first];
auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
SideEffectUsage = M.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) {
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, Self.SemaRef.isConstantEvaluated());
return EvalOK;
}
private:
SequenceChecker &Self;
EvaluationTracker *Prev;
bool EvalOK = true;
} *EvalTracker = nullptr;
/// Find the object which is produced by the specified expression,
/// if any.
Object getObject(const Expr *E, bool Mod) const {
E = E->IgnoreParenCasts();
if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
return getObject(UO->getSubExpr(), Mod);
} else if (const 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 (const 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 (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
// FIXME: If this is a reference, map through to its value.
return DRE->getDecl();
return nullptr;
}
/// Note that an object \p O was modified or used by an expression
/// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
/// the object \p O as obtained via the \p UsageMap.
void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
// Get the old usage for the given object and usage kind.
Usage &U = UI.Uses[UK];
if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
// If we have a modification as side effect and are in a sequenced
// subexpression, save the old Usage so that we can restore it later
// in SequencedSubexpression::~SequencedSubexpression.
if (UK == UK_ModAsSideEffect && ModAsSideEffect)
ModAsSideEffect->push_back(std::make_pair(O, U));
// Then record the new usage with the current sequencing region.
U.UsageExpr = UsageExpr;
U.Seq = Region;
}
}
/// Check whether a modification or use of an object \p O in an expression
/// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
/// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
/// \p IsModMod is true when we are checking for a mod-mod unsequenced
/// usage and false we are checking for a mod-use unsequenced usage.
void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
UsageKind OtherKind, bool IsModMod) {
if (UI.Diagnosed)
return;
const Usage &U = UI.Uses[OtherKind];
if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
return;
const Expr *Mod = U.UsageExpr;
const Expr *ModOrUse = UsageExpr;
if (OtherKind == UK_Use)
std::swap(Mod, ModOrUse);
SemaRef.DiagRuntimeBehavior(
Mod->getExprLoc(), {Mod, ModOrUse},
SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
: diag::warn_unsequenced_mod_use)
<< O << SourceRange(ModOrUse->getExprLoc()));
UI.Diagnosed = true;
}
// A note on note{Pre, Post}{Use, Mod}:
//
// (It helps to follow the algorithm with an expression such as
// "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
// operations before C++17 and both are well-defined in C++17).
//
// When visiting a node which uses/modify an object we first call notePreUse
// or notePreMod before visiting its sub-expression(s). At this point the
// children of the current node have not yet been visited and so the eventual
// uses/modifications resulting from the children of the current node have not
// been recorded yet.
//
// We then visit the children of the current node. After that notePostUse or
// notePostMod is called. These will 1) detect an unsequenced modification
// as side effect (as in "k++ + k") and 2) add a new usage with the
// appropriate usage kind.
//
// We also have to be careful that some operation sequences modification as
// side effect as well (for example: || or ,). To account for this we wrap
// the visitation of such a sub-expression (for example: the LHS of || or ,)
// with SequencedSubexpression. SequencedSubexpression is an RAII object
// which record usages which are modifications as side effect, and then
// downgrade them (or more accurately restore the previous usage which was a
// modification as side effect) when exiting the scope of the sequenced
// subexpression.
void notePreUse(Object O, const Expr *UseExpr) {
UsageInfo &UI = UsageMap[O];
// Uses conflict with other modifications.
checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
}
void notePostUse(Object O, const Expr *UseExpr) {
UsageInfo &UI = UsageMap[O];
checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
/*IsModMod=*/false);
addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
}
void notePreMod(Object O, const Expr *ModExpr) {
UsageInfo &UI = UsageMap[O];
// Modifications conflict with other modifications and with uses.
checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
}
void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
UsageInfo &UI = UsageMap[O];
checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
/*IsModMod=*/true);
addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
}
public:
SequenceChecker(Sema &S, const Expr *E,
SmallVectorImpl<const Expr *> &WorkList)
: Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
Visit(E);
// Silence a -Wunused-private-field since WorkList is now unused.
// TODO: Evaluate if it can be used, and if not remove it.
(void)this->WorkList;
}
void VisitStmt(const Stmt *S) {
// Skip all statements which aren't expressions for now.
}
void VisitExpr(const Expr *E) {
// By default, just recurse to evaluated subexpressions.
Base::VisitStmt(E);
}
void VisitCastExpr(const 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 VisitSequencedExpressions(const Expr *SequencedBefore,
const Expr *SequencedAfter) {
SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
SequenceTree::Seq AfterRegion = Tree.allocate(Region);
SequenceTree::Seq OldRegion = Region;
{
SequencedSubexpression SeqBefore(*this);
Region = BeforeRegion;
Visit(SequencedBefore);
}
Region = AfterRegion;
Visit(SequencedAfter);
Region = OldRegion;
Tree.merge(BeforeRegion);
Tree.merge(AfterRegion);
}
void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
// C++17 [expr.sub]p1:
// The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
// expression E1 is sequenced before the expression E2.
if (SemaRef.getLangOpts().CPlusPlus17)
VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
else {
Visit(ASE->getLHS());
Visit(ASE->getRHS());
}
}
void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
void VisitBinPtrMem(const BinaryOperator *BO) {
// C++17 [expr.mptr.oper]p4:
// Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
// the expression E1 is sequenced before the expression E2.
if (SemaRef.getLangOpts().CPlusPlus17)
VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
else {
Visit(BO->getLHS());
Visit(BO->getRHS());
}
}
void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
void VisitBinShlShr(const BinaryOperator *BO) {
// C++17 [expr.shift]p4:
// The expression E1 is sequenced before the expression E2.
if (SemaRef.getLangOpts().CPlusPlus17)
VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
else {
Visit(BO->getLHS());
Visit(BO->getRHS());
}
}
void VisitBinComma(const 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.
VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
}
void VisitBinAssign(const BinaryOperator *BO) {
SequenceTree::Seq RHSRegion;
SequenceTree::Seq LHSRegion;
if (SemaRef.getLangOpts().CPlusPlus17) {
RHSRegion = Tree.allocate(Region);
LHSRegion = Tree.allocate(Region);
} else {
RHSRegion = Region;
LHSRegion = Region;
}
SequenceTree::Seq OldRegion = Region;
// C++11 [expr.ass]p1:
// [...] the assignment is sequenced after the value computation
// of the right and left operands, [...]
//
// so check it before inspecting the operands and update the
// map afterwards.
Object O = getObject(BO->getLHS(), /*Mod=*/true);
if (O)
notePreMod(O, BO);
if (SemaRef.getLangOpts().CPlusPlus17) {
// C++17 [expr.ass]p1:
// [...] The right operand is sequenced before the left operand. [...]
{
SequencedSubexpression SeqBefore(*this);
Region = RHSRegion;
Visit(BO->getRHS());
}
Region = LHSRegion;
Visit(BO->getLHS());
if (O && isa<CompoundAssignOperator>(BO))
notePostUse(O, BO);
} else {
// C++11 does not specify any sequencing between the LHS and RHS.
Region = LHSRegion;
Visit(BO->getLHS());
if (O && isa<CompoundAssignOperator>(BO))
notePostUse(O, BO);
Region = RHSRegion;
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.
Region = OldRegion;
if (O)
notePostMod(O, BO,
SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
: UK_ModAsSideEffect);
if (SemaRef.getLangOpts().CPlusPlus17) {
Tree.merge(RHSRegion);
Tree.merge(LHSRegion);
}
}
void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
VisitBinAssign(CAO);
}
void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
void VisitUnaryPreIncDec(const 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(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
void VisitUnaryPostIncDec(const UnaryOperator *UO) {
Object O = getObject(UO->getSubExpr(), true);
if (!O)
return VisitExpr(UO);
notePreMod(O, UO);
Visit(UO->getSubExpr());
notePostMod(O, UO, UK_ModAsSideEffect);
}
void VisitBinLOr(const BinaryOperator *BO) {
// C++11 [expr.log.or]p2:
// If the second expression is evaluated, every value computation and
// side effect associated with the first expression is sequenced before
// every value computation and side effect associated with the
// second expression.
SequenceTree::Seq LHSRegion = Tree.allocate(Region);
SequenceTree::Seq RHSRegion = Tree.allocate(Region);
SequenceTree::Seq OldRegion = Region;
EvaluationTracker Eval(*this);
{
SequencedSubexpression Sequenced(*this);
Region = LHSRegion;
Visit(BO->getLHS());
}
// C++11 [expr.log.or]p1:
// [...] the second operand is not evaluated if the first operand
// evaluates to true.
bool EvalResult = false;
bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
if (ShouldVisitRHS) {
Region = RHSRegion;
Visit(BO->getRHS());
}
Region = OldRegion;
Tree.merge(LHSRegion);
Tree.merge(RHSRegion);
}
void VisitBinLAnd(const BinaryOperator *BO) {
// C++11 [expr.log.and]p2:
// If the second expression is evaluated, every value computation and
// side effect associated with the first expression is sequenced before
// every value computation and side effect associated with the
// second expression.
SequenceTree::Seq LHSRegion = Tree.allocate(Region);
SequenceTree::Seq RHSRegion = Tree.allocate(Region);
SequenceTree::Seq OldRegion = Region;
EvaluationTracker Eval(*this);
{
SequencedSubexpression Sequenced(*this);
Region = LHSRegion;
Visit(BO->getLHS());
}
// C++11 [expr.log.and]p1:
// [...] the second operand is not evaluated if the first operand is false.
bool EvalResult = false;
bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
if (ShouldVisitRHS) {
Region = RHSRegion;
Visit(BO->getRHS());
}
Region = OldRegion;
Tree.merge(LHSRegion);
Tree.merge(RHSRegion);
}
void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
// C++11 [expr.cond]p1:
// [...] Every value computation and side effect associated with the first
// expression is sequenced before every value computation and side effect
// associated with the second or third expression.
SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
// No sequencing is specified between the true and false expression.
// However since exactly one of both is going to be evaluated we can
// consider them to be sequenced. This is needed to avoid warning on
// something like "x ? y+= 1 : y += 2;" in the case where we will visit
// both the true and false expressions because we can't evaluate x.
// This will still allow us to detect an expression like (pre C++17)
// "(x ? y += 1 : y += 2) = y".
//
// We don't wrap the visitation of the true and false expression with
// SequencedSubexpression because we don't want to downgrade modifications
// as side effect in the true and false expressions after the visition
// is done. (for example in the expression "(x ? y++ : y++) + y" we should
// not warn between the two "y++", but we should warn between the "y++"
// and the "y".
SequenceTree::Seq TrueRegion = Tree.allocate(Region);
SequenceTree::Seq FalseRegion = Tree.allocate(Region);
SequenceTree::Seq OldRegion = Region;
EvaluationTracker Eval(*this);
{
SequencedSubexpression Sequenced(*this);
Region = ConditionRegion;
Visit(CO->getCond());
}
// C++11 [expr.cond]p1:
// [...] The first expression is contextually converted to bool (Clause 4).
// It is evaluated and if it is true, the result of the conditional
// expression is the value of the second expression, otherwise that of the
// third expression. Only one of the second and third expressions is
// evaluated. [...]
bool EvalResult = false;
bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
if (ShouldVisitTrueExpr) {
Region = TrueRegion;
Visit(CO->getTrueExpr());
}
if (ShouldVisitFalseExpr) {
Region = FalseRegion;
Visit(CO->getFalseExpr());
}
Region = OldRegion;
Tree.merge(ConditionRegion);
Tree.merge(TrueRegion);
Tree.merge(FalseRegion);
}
void VisitCallExpr(const CallExpr *CE) {
// FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
if (CE->isUnevaluatedBuiltinCall(Context))
return;
// 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);
SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
// C++17 [expr.call]p5
// The postfix-expression is sequenced before each expression in the
// expression-list and any default argument. [...]
SequenceTree::Seq CalleeRegion;
SequenceTree::Seq OtherRegion;
if (SemaRef.getLangOpts().CPlusPlus17) {
CalleeRegion = Tree.allocate(Region);
OtherRegion = Tree.allocate(Region);
} else {
CalleeRegion = Region;
OtherRegion = Region;
}
SequenceTree::Seq OldRegion = Region;
// Visit the callee expression first.
Region = CalleeRegion;
if (SemaRef.getLangOpts().CPlusPlus17) {
SequencedSubexpression Sequenced(*this);
Visit(CE->getCallee());
} else {
Visit(CE->getCallee());
}
// Then visit the argument expressions.
Region = OtherRegion;
for (const Expr *Argument : CE->arguments())
Visit(Argument);
Region = OldRegion;
if (SemaRef.getLangOpts().CPlusPlus17) {
Tree.merge(CalleeRegion);
Tree.merge(OtherRegion);
}
});
}
void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
// C++17 [over.match.oper]p2:
// [...] the operator notation is first transformed to the equivalent
// function-call notation as summarized in Table 12 (where @ denotes one
// of the operators covered in the specified subclause). However, the
// operands are sequenced in the order prescribed for the built-in
// operator (Clause 8).
//
// From the above only overloaded binary operators and overloaded call
// operators have sequencing rules in C++17 that we need to handle
// separately.
if (!SemaRef.getLangOpts().CPlusPlus17 ||
(CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
return VisitCallExpr(CXXOCE);
enum {
NoSequencing,
LHSBeforeRHS,
RHSBeforeLHS,
LHSBeforeRest
} SequencingKind;
switch (CXXOCE->getOperator()) {
case OO_Equal:
case OO_PlusEqual:
case OO_MinusEqual:
case OO_StarEqual:
case OO_SlashEqual:
case OO_PercentEqual:
case OO_CaretEqual:
case OO_AmpEqual:
case OO_PipeEqual:
case OO_LessLessEqual:
case OO_GreaterGreaterEqual:
SequencingKind = RHSBeforeLHS;
break;
case OO_LessLess:
case OO_GreaterGreater:
case OO_AmpAmp:
case OO_PipePipe:
case OO_Comma:
case OO_ArrowStar:
case OO_Subscript:
SequencingKind = LHSBeforeRHS;
break;
case OO_Call:
SequencingKind = LHSBeforeRest;
break;
default:
SequencingKind = NoSequencing;
break;
}
if (SequencingKind == NoSequencing)
return VisitCallExpr(CXXOCE);
// This is a call, so all subexpressions are sequenced before the result.
SequencedSubexpression Sequenced(*this);
SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
assert(SemaRef.getLangOpts().CPlusPlus17 &&
"Should only get there with C++17 and above!");
assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
"Should only get there with an overloaded binary operator"
" or an overloaded call operator!");
if (SequencingKind == LHSBeforeRest) {
assert(CXXOCE->getOperator() == OO_Call &&
"We should only have an overloaded call operator here!");
// This is very similar to VisitCallExpr, except that we only have the
// C++17 case. The postfix-expression is the first argument of the
// CXXOperatorCallExpr. The expressions in the expression-list, if any,
// are in the following arguments.
//
// Note that we intentionally do not visit the callee expression since
// it is just a decayed reference to a function.
SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
SequenceTree::Seq OldRegion = Region;
assert(CXXOCE->getNumArgs() >= 1 &&
"An overloaded call operator must have at least one argument"
" for the postfix-expression!");
const Expr *PostfixExpr = CXXOCE->getArgs()[0];
llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
CXXOCE->getNumArgs() - 1);
// Visit the postfix-expression first.
{
Region = PostfixExprRegion;
SequencedSubexpression Sequenced(*this);
Visit(PostfixExpr);
}
// Then visit the argument expressions.
Region = ArgsRegion;
for (const Expr *Arg : Args)
Visit(Arg);
Region = OldRegion;
Tree.merge(PostfixExprRegion);
Tree.merge(ArgsRegion);
} else {
assert(CXXOCE->getNumArgs() == 2 &&
"Should only have two arguments here!");
assert((SequencingKind == LHSBeforeRHS ||
SequencingKind == RHSBeforeLHS) &&
"Unexpected sequencing kind!");
// We do not visit the callee expression since it is just a decayed
// reference to a function.
const Expr *E1 = CXXOCE->getArg(0);
const Expr *E2 = CXXOCE->getArg(1);
if (SequencingKind == RHSBeforeLHS)
std::swap(E1, E2);
return VisitSequencedExpressions(E1, E2);
}
});
}
void VisitCXXConstructExpr(const 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::const_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(const 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) {
const 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]);
}
};
} // namespace
void Sema::CheckUnsequencedOperations(const Expr *E) {
SmallVector<const Expr *, 8> WorkList;
WorkList.push_back(E);
while (!WorkList.empty()) {
const Expr *Item = WorkList.pop_back_val();
SequenceChecker(*this, Item, WorkList);
}
}
void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
bool IsConstexpr) {
llvm::SaveAndRestore<bool> ConstantContext(
isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
CheckImplicitConversions(E, CheckLoc);
if (!E->isInstantiationDependent())
CheckUnsequencedOperations(E);
if (!IsConstexpr && !E->isValueDependent())
CheckForIntOverflow(E);
DiagnoseMisalignedMembers();
}
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(ArrayRef<ParmVarDecl *> Parameters,
bool CheckParameterNames) {
bool HasInvalidParm = false;
for (ParmVarDecl *Param : Parameters) {
// 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) {
// Diagnose this as an extension in C17 and earlier.
if (!getLangOpts().C2x)
Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
}
// 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());
// If the parameter is a c++ class type and it has to be destructed in the
// callee function, declare the destructor so that it can be called by the
// callee function. Do not perform any direct access check on the dtor here.
if (!Param->isInvalidDecl()) {
if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
if (!ClassDecl->isInvalidDecl() &&
!ClassDecl->hasIrrelevantDestructor() &&
!ClassDecl->isDependentContext() &&
ClassDecl->isParamDestroyedInCallee()) {
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;
// Check for parameter names shadowing fields from the class.
if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
// The owning context for the parameter should be the function, but we
// want to see if this function's declaration context is a record.
DeclContext *DC = Param->getDeclContext();
if (DC && DC->isFunctionOrMethod()) {
if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
RD, /*DeclIsField*/ false);
}
}
}
return HasInvalidParm;
}
Optional<std::pair<CharUnits, CharUnits>>
static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx);
/// Compute the alignment and offset of the base class object given the
/// derived-to-base cast expression and the alignment and offset of the derived
/// class object.
static std::pair<CharUnits, CharUnits>
getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
CharUnits BaseAlignment, CharUnits Offset,
ASTContext &Ctx) {
for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
++PathI) {
const CXXBaseSpecifier *Base = *PathI;
const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
if (Base->isVirtual()) {
// The complete object may have a lower alignment than the non-virtual
// alignment of the base, in which case the base may be misaligned. Choose
// the smaller of the non-virtual alignment and BaseAlignment, which is a
// conservative lower bound of the complete object alignment.
CharUnits NonVirtualAlignment =
Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment();
BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
Offset = CharUnits::Zero();
} else {
const ASTRecordLayout &RL =
Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
Offset += RL.getBaseClassOffset(BaseDecl);
}
DerivedType = Base->getType();
}
return std::make_pair(BaseAlignment, Offset);
}
/// Compute the alignment and offset of a binary additive operator.
static Optional<std::pair<CharUnits, CharUnits>>
getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
bool IsSub, ASTContext &Ctx) {
QualType PointeeType = PtrE->getType()->getPointeeType();
if (!PointeeType->isConstantSizeType())
return llvm::None;
auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
if (!P)
return llvm::None;
CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
CharUnits Offset = EltSize * IdxRes->getExtValue();
if (IsSub)
Offset = -Offset;
return std::make_pair(P->first, P->second + Offset);
}
// If the integer expression isn't a constant expression, compute the lower
// bound of the alignment using the alignment and offset of the pointer
// expression and the element size.
return std::make_pair(
P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
CharUnits::Zero());
}
/// This helper function takes an lvalue expression and returns the alignment of
/// a VarDecl and a constant offset from the VarDecl.
Optional<std::pair<CharUnits, CharUnits>>
static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) {
E = E->IgnoreParens();
switch (E->getStmtClass()) {
default:
break;
case Stmt::CStyleCastExprClass:
case Stmt::CXXStaticCastExprClass:
case Stmt::ImplicitCastExprClass: {
auto *CE = cast<CastExpr>(E);
const Expr *From = CE->getSubExpr();
switch (CE->getCastKind()) {
default:
break;
case CK_NoOp:
return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
case CK_UncheckedDerivedToBase:
case CK_DerivedToBase: {
auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
if (!P)
break;
return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
P->second, Ctx);
}
}
break;
}
case Stmt::ArraySubscriptExprClass: {
auto *ASE = cast<ArraySubscriptExpr>(E);
return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(),
false, Ctx);
}
case Stmt::DeclRefExprClass: {
if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
// FIXME: If VD is captured by copy or is an escaping __block variable,
// use the alignment of VD's type.
if (!VD->getType()->isReferenceType())
return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
if (VD->hasInit())
return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
}
break;
}
case Stmt::MemberExprClass: {
auto *ME = cast<MemberExpr>(E);
auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
if (!FD || FD->getType()->isReferenceType())
break;
Optional<std::pair<CharUnits, CharUnits>> P;
if (ME->isArrow())
P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
else
P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
if (!P)
break;
const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
return std::make_pair(P->first,
P->second + CharUnits::fromQuantity(Offset));
}
case Stmt::UnaryOperatorClass: {
auto *UO = cast<UnaryOperator>(E);
switch (UO->getOpcode()) {
default:
break;
case UO_Deref:
return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx);
}
break;
}
case Stmt::BinaryOperatorClass: {
auto *BO = cast<BinaryOperator>(E);
auto Opcode = BO->getOpcode();
switch (Opcode) {
default:
break;
case BO_Comma:
return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx);
}
break;
}
}
return llvm::None;
}
/// This helper function takes a pointer expression and returns the alignment of
/// a VarDecl and a constant offset from the VarDecl.
Optional<std::pair<CharUnits, CharUnits>>
static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) {
E = E->IgnoreParens();
switch (E->getStmtClass()) {
default:
break;
case Stmt::CStyleCastExprClass:
case Stmt::CXXStaticCastExprClass:
case Stmt::ImplicitCastExprClass: {
auto *CE = cast<CastExpr>(E);
const Expr *From = CE->getSubExpr();
switch (CE->getCastKind()) {
default:
break;
case CK_NoOp:
return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
case CK_ArrayToPointerDecay:
return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
case CK_UncheckedDerivedToBase:
case CK_DerivedToBase: {
auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
if (!P)
break;
return getDerivedToBaseAlignmentAndOffset(
CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
}
}
break;
}
case Stmt::CXXThisExprClass: {
auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment();
return std::make_pair(Alignment, CharUnits::Zero());
}
case Stmt::UnaryOperatorClass: {
auto *UO = cast<UnaryOperator>(E);
if (UO->getOpcode() == UO_AddrOf)
return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx);
break;
}
case Stmt::BinaryOperatorClass: {
auto *BO = cast<BinaryOperator>(E);
auto Opcode = BO->getOpcode();
switch (Opcode) {
default:
break;
case BO_Add:
case BO_Sub: {
const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
std::swap(LHS, RHS);
return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
Ctx);
}
case BO_Comma:
return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
}
break;
}
}
return llvm::None;
}
static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
// See if we can compute the alignment of a VarDecl and an offset from it.
Optional<std::pair<CharUnits, CharUnits>> P =
getBaseAlignmentAndOffsetFromPtr(E, S.Context);
if (P)
return P->first.alignmentAtOffset(P->second);
// If that failed, return the type's alignment.
return S.Context.getTypeAlignInChars(E->getType()->getPointeeType());
}
/// 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();
// Explicitly allow casts from cv void*. We already implicitly
// allowed casts to cv void*, since they have alignment 1.
// Also allow casts involving incomplete types, which implicitly
// includes 'void'.
if (SrcPointee->isIncompleteType()) return;
CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
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();
}
/// 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, const 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) {
// Already diagnosed by the constant evaluator.
if (isConstantEvaluated())
return;
IndexExpr = IndexExpr->IgnoreParenImpCasts();
if (IndexExpr->isValueDependent())
return;
const Type *EffectiveType =
BaseExpr->getType()->getPointeeOrArrayElementType();
BaseExpr = BaseExpr->IgnoreParenCasts();
const ConstantArrayType *ArrayTy =
Context.getAsConstantArrayType(BaseExpr->getType());
if (!ArrayTy)
return;
const Type *BaseType = ArrayTy->getElementType().getTypePtr();
if (EffectiveType->isDependentType() || BaseType->isDependentType())
return;
Expr::EvalResult Result;
if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
return;
llvm::APSInt index = Result.Val.getInt();
if (IndexNegated)
index = -index;
const NamedDecl *ND = nullptr;
if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
ND = DRE->getDecl();
if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
ND = ME->getMemberDecl();
if (index.isUnsigned() || !index.isNegative()) {
// It is possible that the type of the base expression after
// IgnoreParenCasts is incomplete, even though the type of the base
// expression before IgnoreParenCasts is complete (see PR39746 for an
// example). In this case we have no information about whether the array
// access exceeds the array bounds. However we can still diagnose an array
// access which precedes the array bounds.
if (BaseType->isIncompleteType())
return;
llvm::APInt size = ArrayTy->getSize();
if (!size.isStrictlyPositive())
return;
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->getBeginLoc());
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->getBeginLoc(), 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->getBeginLoc(), 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 = DRE->getDecl();
if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
ND = ME->getMemberDecl();
}
if (ND)
DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
PDiag(diag::note_array_declared_here) << ND);
}
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);
expr = ASE->getBase();
break;
}
case Stmt::MemberExprClass: {
expr = cast<MemberExpr>(expr)->getBase();
break;
}
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;
}
case Stmt::CXXOperatorCallExprClass: {
const auto *OCE = cast<CXXOperatorCallExpr>(expr);
for (const auto *Arg : OCE->arguments())
CheckArrayAccess(Arg);
return;
}
default:
return;
}
}
}
//===--- CHECK: Objective-C retain cycles ----------------------------------//
namespace {
struct RetainCycleOwner {
VarDecl *Variable = nullptr;
SourceRange Range;
SourceLocation Loc;
bool Indirect = false;
RetainCycleOwner() = default;
void setLocsFrom(Expr *e) {
Loc = e->getExprLoc();
Range = e->getSourceRange();
}
};
} // 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> {
ASTContext &Context;
VarDecl *Variable;
Expr *Capturer = nullptr;
bool VarWillBeReased = false;
FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
: EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Context(Context), Variable(variable) {}
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();
Optional<llvm::APSInt> Value;
VarWillBeReased =
(RHS && (Value = RHS->getIntegerConstantExpr(Context)) &&
*Value == 0);
}
}
}
};
} // 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 allow '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() << 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 << Decl;
if (!ArgRE->isObjCSelfExpr()) {
Diag(Decl->getLocation(),
diag::note_objc_circular_container_declared_here)
<< Decl;
}
}
}
} 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 << Decl;
Diag(Decl->getLocation(),
diag::note_objc_circular_container_declared_here)
<< Decl;
}
}
}
}
}
/// 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.
const ObjCMethodDecl *MD = msg->getMethodDecl();
for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
// noescape blocks should not be retained by the method.
if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
continue;
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 & ObjCPropertyAttribute::kind_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 & ObjCPropertyAttribute::kind_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 & ObjCPropertyAttribute::kind_weak) {
if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
return;
}
}
}
//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
static 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;
}
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->getBeginLoc(), &BodyColInvalid);
if (BodyColInvalid)
return;
bool StmtColInvalid;
unsigned StmtCol =
SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &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 (inTemplateInstantiation())
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
if (!CE->isCallToStdMove())
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();
}
bool Sema::AllowedInCheckedScope(QualType Ty,
const InteropTypeExpr *InteropType,
bool IsParam, CheckedScopeTypeLocation Loc,
CheckedScopeTypeLocation &ProblemLoc,
QualType &ProblemTy) {
if (Ty.isNull())
return true;
CheckedScopeTypeLocation CurrentLoc = Loc;
if (Loc == CSTL_TopLevel)
Loc = CSTL_Nested;
if (Ty->isPointerType() || Ty->isArrayType()) {
if ((Ty->isUncheckedPointerType() || Ty->isUncheckedArrayType()) &&
!InteropType) {
ProblemLoc = CurrentLoc;
ProblemTy = Ty;
return false;
}
// Any interop type annotation must be "at least as checked" as the
// original type, so use that instead.
if (InteropType) {
Ty = Context.getInteropTypeAndAdjust(InteropType, IsParam);
Loc = CSTL_BoundsSafeInterface;
if (!(Ty->isPointerType() || Ty->isArrayType())) {
llvm_unreachable("unexpected interop type");
return false;
}
}
QualType ReferentType = QualType(Ty->getPointeeOrArrayElementType(), 0);
return AllowedInCheckedScope(ReferentType, nullptr, false, Loc,
ProblemLoc, ProblemTy);
} else if (const FunctionProtoType *fpt = Ty->getAs<FunctionProtoType>()) {
const BoundsAnnotations ReturnAnnots = fpt->getReturnAnnots();
InteropTypeExpr *ReturnInteropType = ReturnAnnots.getInteropTypeExpr();
if (!AllowedInCheckedScope(fpt->getReturnType(), ReturnInteropType,
false, Loc, ProblemLoc, ProblemTy))
return false;
unsigned int paramCount = fpt->getNumParams();
for (unsigned int i = 0; i < paramCount; i++) {
const BoundsAnnotations ParamAnnots = fpt->getParamAnnots(i);
InteropTypeExpr *ParamInteropType = ParamAnnots.getInteropTypeExpr();
if (!AllowedInCheckedScope(fpt->getParamType(i), ParamInteropType,
true, Loc, ProblemLoc, ProblemTy))
return false;
}
}
else
assert(!InteropType && "unexpected bounds-safe interface type on type");
return true;
}
static bool DisplaysAsArrayOrPointer(QualType QT) {
QT = QT.IgnoreParens();
const Type *Ty = QT.getTypePtr();
return (isa<PointerType>(Ty) || isa<ArrayType>(Ty));
}
//===--- CHECK: Checked scope -------------------------===//
// Checked C - type restrictions on declarations in checked scope.
bool Sema::DiagnoseCheckedDecl(const ValueDecl *Decl, SourceLocation UseLoc) {
// We're not a checked scope.
if (!IsCheckedScope())
return true;
if (Decl->isInvalidDecl())
return true;
// Checked pointer type or unchecked pointer type with bounds-safe interface
// is only allowed in checked scope or function.
const DeclaratorDecl *TargetDecl = nullptr;
CheckedDeclKind DeclKind;
QualType Ty;
if (const ParmVarDecl *Parm = dyn_cast<ParmVarDecl>(Decl)) {
TargetDecl = Parm;
DeclKind = CDK_Parameter;
Ty = Parm->getType();
}
else if (const FunctionDecl *Func = dyn_cast<FunctionDecl>(Decl)) {
TargetDecl = Func;
DeclKind = CDK_FunctionReturn;
Ty = Func->getReturnType();
}
else if (const VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
TargetDecl = Var;
DeclKind = Var->isLocalVarDecl() ? CDK_LocalVariable : CDK_GlobalVariable; // decl var
Ty = Var->getType();
}
else if (const FieldDecl *Field = dyn_cast<FieldDecl>(Decl)) {
TargetDecl = Field;
DeclKind = CDK_Member;
Ty = Field->getType();
}
else {
Ty = Decl->getType();
}
if (!TargetDecl)
return true;
unsigned IsUse = !UseLoc.isInvalid();
SourceLocation Loc = IsUse ? UseLoc : TargetDecl->getBeginLoc();
bool Result = true;
CheckedScopeTypeLocation ProblemLoc = CSTL_TopLevel;
QualType ProblemTy = Ty;
if (!AllowedInCheckedScope(Ty, TargetDecl->getInteropTypeExpr(),
isa<ParmVarDecl>(TargetDecl), CSTL_TopLevel,
ProblemLoc, ProblemTy)) {
Diag(Loc, diag::err_checked_scope_decl_type) << DeclKind << IsUse
<< ProblemLoc;
if (IsUse) {
Diag(TargetDecl->getBeginLoc(), diag::note_checked_scope_declaration)
<< DeclKind;
}
// Undo adjustments involving array types so that the error message
// displays the source-level type. We leave adjustments from function
// types alone, though. It is not obvious that the source-level function
// type is adjust to be an unchecked type.
if (const AdjustedType *AdjustedTy = dyn_cast<AdjustedType>(ProblemTy)) {
QualType Original = AdjustedTy->getOriginalType();
if (Original->isArrayType())
ProblemTy = Original;
}
// Print a note about the problem type if it might not be obvious.
if (ProblemLoc != CSTL_TopLevel || !DisplaysAsArrayOrPointer(ProblemTy))
Diag(Loc, diag::note_checked_scope_problem_type) << ProblemTy;
Result = false;
}
if (Ty->hasVariadicType()) {
Diag(Loc, diag::err_checked_scope_decl_variable_args) << DeclKind
<< IsUse;
Result = false;
}
return Result;
}
bool Sema::DiagnoseTypeInCheckedScope(QualType Ty, SourceLocation StartLoc,
SourceLocation EndLoc) {
CheckedScopeTypeLocation ProblemLoc = CSTL_TopLevel;
QualType ProblemTy = Ty;
if (!AllowedInCheckedScope(Ty, nullptr, false, CSTL_TopLevel,
ProblemLoc, ProblemTy)) {
Diag(StartLoc, diag::err_checked_scope_type) << ProblemLoc
<< SourceRange(StartLoc, EndLoc);
// Print a note about the problem type if it might not be obvious.
if (ProblemLoc != CSTL_TopLevel || !DisplaysAsArrayOrPointer(ProblemTy))
Diag(StartLoc, diag::note_checked_scope_problem_type) << ProblemTy;
return false;
}
if (Ty->hasVariadicType()) {
Diag(StartLoc, diag::err_checked_scope_type_variable_args) <<
SourceRange(StartLoc, EndLoc);
return false;
}
return true;
}
//===--- Layout compatibility ----------------------------------------------//
static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
/// Check if two enumeration types are layout-compatible.
static 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());
}
/// Check if two fields are layout-compatible.
static 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;
}
/// Check if two standard-layout structs are layout-compatible.
/// (C++11 [class.mem] p17)
static 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;
}
/// Check if two standard-layout unions are layout-compatible.
/// (C++11 [class.mem] p18)
static 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();
}
static 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);
}
/// Check if two types are layout-compatible in C++11 sense.
static 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;
}
//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
/// 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.
///
/// \param isConstantEvaluated wether the evalaution should be performed in
/// constant context.
static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
const ValueDecl **VD, uint64_t *MagicValue,
bool isConstantEvaluated) {
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,
isConstantEvaluated)) {
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;
}
}
}
/// 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.
///
/// \param isConstantEvaluated wether the evalaution should be performed in
/// constant context.
///
/// \returns true if the corresponding C type was found.
static bool GetMatchingCType(
const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
const ASTContext &Ctx,
const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
*MagicValues,
bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
bool isConstantEvaluated) {
FoundWrongKind = false;
// Variable declaration that has type_tag_for_datatype attribute.
const ValueDecl *VD = nullptr;
uint64_t MagicValue;
if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
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;
}
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);
}
static 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);
}
void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
const ArrayRef<const Expr *> ExprArgs,
SourceLocation CallSiteLoc) {
const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
bool IsPointerAttr = Attr->getIsPointer();
// Retrieve the argument representing the 'type_tag'.
unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
if (TypeTagIdxAST >= ExprArgs.size()) {
Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
<< 0 << Attr->getTypeTagIdx().getSourceIndex();
return;
}
const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
bool FoundWrongKind;
TypeTagData TypeInfo;
if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
TypeInfo, isConstantEvaluated())) {
if (FoundWrongKind)
Diag(TypeTagExpr->getExprLoc(),
diag::warn_type_tag_for_datatype_wrong_kind)
<< TypeTagExpr->getSourceRange();
return;
}
// Retrieve the argument representing the 'arg_idx'.
unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
if (ArgumentIdxAST >= ExprArgs.size()) {
Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
<< 1 << Attr->getArgumentIdx().getSourceIndex();
return;
}
const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
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();
}
void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
CharUnits Alignment) {
if (!DisableSubstitionDiagnostics)
MisalignedMembers.emplace_back(E, RD, MD, Alignment);
}
void Sema::DiagnoseMisalignedMembers() {
for (MisalignedMember &m : MisalignedMembers) {
const NamedDecl *ND = m.RD;
if (ND->getName().empty()) {
if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
ND = TD;
}
Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
<< m.MD << ND << m.E->getSourceRange();
}
MisalignedMembers.clear();
}
void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
E = E->IgnoreParens();
if (!T->isPointerType() && !T->isIntegerType())
return;
if (isa<UnaryOperator>(E) &&
cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
if (isa<MemberExpr>(Op)) {
auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
if (MA != MisalignedMembers.end() &&
(T->isIntegerType() ||
(T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
Context.getTypeAlignInChars(
T->getPointeeType()) <= MA->Alignment))))
MisalignedMembers.erase(MA);
}
}
}
void Sema::RefersToMemberWithReducedAlignment(
Expr *E,
llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
Action) {
const auto *ME = dyn_cast<MemberExpr>(E);
if (!ME)
return;
// No need to check expressions with an __unaligned-qualified type.
if (E->getType().getQualifiers().hasUnaligned())
return;
// For a chain of MemberExpr like "a.b.c.d" this list
// will keep FieldDecl's like [d, c, b].
SmallVector<FieldDecl *, 4> ReverseMemberChain;
const MemberExpr *TopME = nullptr;
bool AnyIsPacked = false;
do {
QualType BaseType = ME->getBase()->getType();
if (BaseType->isDependentType())
return;
if (ME->isArrow())
BaseType = BaseType->getPointeeType();
RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
if (RD->isInvalidDecl())
return;
ValueDecl *MD = ME->getMemberDecl();
auto *FD = dyn_cast<FieldDecl>(MD);
// We do not care about non-data members.
if (!FD || FD->isInvalidDecl())
return;
AnyIsPacked =
AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
ReverseMemberChain.push_back(FD);
TopME = ME;
ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
} while (ME);
assert(TopME && "We did not compute a topmost MemberExpr!");
// Not the scope of this diagnostic.
if (!AnyIsPacked)
return;
const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
// TODO: The innermost base of the member expression may be too complicated.
// For now, just disregard these cases. This is left for future
// improvement.
if (!DRE && !isa<CXXThisExpr>(TopBase))
return;
// Alignment expected by the whole expression.
CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
// No need to do anything else with this case.
if (ExpectedAlignment.isOne())
return;
// Synthesize offset of the whole access.
CharUnits Offset;
for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
I++) {
Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
}
// Compute the CompleteObjectAlignment as the alignment of the whole chain.
CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
ReverseMemberChain.back()->getParent()->getTypeForDecl());
// The base expression of the innermost MemberExpr may give
// stronger guarantees than the class containing the member.
if (DRE && !TopME->isArrow()) {
const ValueDecl *VD = DRE->getDecl();
if (!VD->getType()->isReferenceType())
CompleteObjectAlignment =
std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
}
// Check if the synthesized offset fulfills the alignment.
if (Offset % ExpectedAlignment != 0 ||
// It may fulfill the offset it but the effective alignment may still be
// lower than the expected expression alignment.
CompleteObjectAlignment < ExpectedAlignment) {
// If this happens, we want to determine a sensible culprit of this.
// Intuitively, watching the chain of member expressions from right to
// left, we start with the required alignment (as required by the field
// type) but some packed attribute in that chain has reduced the alignment.
// It may happen that another packed structure increases it again. But if
// we are here such increase has not been enough. So pointing the first
// FieldDecl that either is packed or else its RecordDecl is,
// seems reasonable.
FieldDecl *FD = nullptr;
CharUnits Alignment;
for (FieldDecl *FDI : ReverseMemberChain) {
if (FDI->hasAttr<PackedAttr>() ||
FDI->getParent()->hasAttr<PackedAttr>()) {
FD = FDI;
Alignment = std::min(
Context.getTypeAlignInChars(FD->getType()),
Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
break;
}
}
assert(FD && "We did not find a packed FieldDecl!");
Action(E, FD->getParent(), FD, Alignment);
}
}
void Sema::CheckAddressOfPackedMember(Expr *rhs) {
using namespace std::placeholders;
RefersToMemberWithReducedAlignment(
rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
_2, _3, _4));
}
ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall,
ExprResult CallResult) {
if (checkArgCount(*this, TheCall, 1))
return ExprError();
ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
if (MatrixArg.isInvalid())
return MatrixArg;
Expr *Matrix = MatrixArg.get();
auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
if (!MType) {
Diag(Matrix->getBeginLoc(), diag::err_builtin_matrix_arg);
return ExprError();
}
// Create returned matrix type by swapping rows and columns of the argument
// matrix type.
QualType ResultType = Context.getConstantMatrixType(
MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
// Change the return type to the type of the returned matrix.
TheCall->setType(ResultType);
// Update call argument to use the possibly converted matrix argument.
TheCall->setArg(0, Matrix);
return CallResult;
}
// Get and verify the matrix dimensions.
static llvm::Optional<unsigned>
getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
SourceLocation ErrorPos;
Optional<llvm::APSInt> Value =
Expr->getIntegerConstantExpr(S.Context, &ErrorPos);
if (!Value) {
S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
<< Name;
return {};
}
uint64_t Dim = Value->getZExtValue();
if (!ConstantMatrixType::isDimensionValid(Dim)) {
S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
<< Name << ConstantMatrixType::getMaxElementsPerDimension();
return {};
}
return Dim;
}
ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
ExprResult CallResult) {
if (!getLangOpts().MatrixTypes) {
Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
return ExprError();
}
if (checkArgCount(*this, TheCall, 4))
return ExprError();
unsigned PtrArgIdx = 0;
Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
Expr *RowsExpr = TheCall->getArg(1);
Expr *ColumnsExpr = TheCall->getArg(2);
Expr *StrideExpr = TheCall->getArg(3);
bool ArgError = false;
// Check pointer argument.
{
ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
if (PtrConv.isInvalid())
return PtrConv;
PtrExpr = PtrConv.get();
TheCall->setArg(0, PtrExpr);
if (PtrExpr->isTypeDependent()) {
TheCall->setType(Context.DependentTy);
return TheCall;
}
}
auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
QualType ElementTy;
if (!PtrTy) {
Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
<< PtrArgIdx + 1;
ArgError = true;
} else {
ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
if (!ConstantMatrixType::isValidElementType(ElementTy)) {
Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
<< PtrArgIdx + 1;
ArgError = true;
}
}
// Apply default Lvalue conversions and convert the expression to size_t.
auto ApplyArgumentConversions = [this](Expr *E) {
ExprResult Conv = DefaultLvalueConversion(E);
if (Conv.isInvalid())
return Conv;
return tryConvertExprToType(Conv.get(), Context.getSizeType());
};
// Apply conversion to row and column expressions.
ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
if (!RowsConv.isInvalid()) {
RowsExpr = RowsConv.get();
TheCall->setArg(1, RowsExpr);
} else
RowsExpr = nullptr;
ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
if (!ColumnsConv.isInvalid()) {
ColumnsExpr = ColumnsConv.get();
TheCall->setArg(2, ColumnsExpr);
} else
ColumnsExpr = nullptr;
// If any any part of the result matrix type is still pending, just use
// Context.DependentTy, until all parts are resolved.
if ((RowsExpr && RowsExpr->isTypeDependent()) ||
(ColumnsExpr && ColumnsExpr->isTypeDependent())) {
TheCall->setType(Context.DependentTy);
return CallResult;
}
// Check row and column dimenions.
llvm::Optional<unsigned> MaybeRows;
if (RowsExpr)
MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
llvm::Optional<unsigned> MaybeColumns;
if (ColumnsExpr)
MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
// Check stride argument.
ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
if (StrideConv.isInvalid())
return ExprError();
StrideExpr = StrideConv.get();
TheCall->setArg(3, StrideExpr);
if (MaybeRows) {
if (Optional<llvm::APSInt> Value =
StrideExpr->getIntegerConstantExpr(Context)) {
uint64_t Stride = Value->getZExtValue();
if (Stride < *MaybeRows) {
Diag(StrideExpr->getBeginLoc(),
diag::err_builtin_matrix_stride_too_small);
ArgError = true;
}
}
}
if (ArgError || !MaybeRows || !MaybeColumns)
return ExprError();
TheCall->setType(
Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
return CallResult;
}
ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
ExprResult CallResult) {
if (checkArgCount(*this, TheCall, 3))
return ExprError();
unsigned PtrArgIdx = 1;
Expr *MatrixExpr = TheCall->getArg(0);
Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
Expr *StrideExpr = TheCall->getArg(2);
bool ArgError = false;
{
ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
if (MatrixConv.isInvalid())
return MatrixConv;
MatrixExpr = MatrixConv.get();
TheCall->setArg(0, MatrixExpr);
}
if (MatrixExpr->isTypeDependent()) {
TheCall->setType(Context.DependentTy);
return TheCall;
}
auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
if (!MatrixTy) {
Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_matrix_arg) << 0;
ArgError = true;
}
{
ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
if (PtrConv.isInvalid())
return PtrConv;
PtrExpr = PtrConv.get();
TheCall->setArg(1, PtrExpr);
if (PtrExpr->isTypeDependent()) {
TheCall->setType(Context.DependentTy);
return TheCall;
}
}
// Check pointer argument.
auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
if (!PtrTy) {
Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
<< PtrArgIdx + 1;
ArgError = true;
} else {
QualType ElementTy = PtrTy->getPointeeType();
if (ElementTy.isConstQualified()) {
Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
ArgError = true;
}
ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
if (MatrixTy &&
!Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
Diag(PtrExpr->getBeginLoc(),
diag::err_builtin_matrix_pointer_arg_mismatch)
<< ElementTy << MatrixTy->getElementType();
ArgError = true;
}
}
// Apply default Lvalue conversions and convert the stride expression to
// size_t.
{
ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
if (StrideConv.isInvalid())
return StrideConv;
StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
if (StrideConv.isInvalid())
return StrideConv;
StrideExpr = StrideConv.get();
TheCall->setArg(2, StrideExpr);
}
// Check stride argument.
if (MatrixTy) {
if (Optional<llvm::APSInt> Value =
StrideExpr->getIntegerConstantExpr(Context)) {
uint64_t Stride = Value->getZExtValue();
if (Stride < MatrixTy->getNumRows()) {
Diag(StrideExpr->getBeginLoc(),
diag::err_builtin_matrix_stride_too_small);
ArgError = true;
}
}
}
if (ArgError)
return ExprError();
return CallResult;
}
/// \brief Enforce the bounds of a TCB
/// CheckTCBEnforcement - Enforces that every function in a named TCB only
/// directly calls other functions in the same TCB as marked by the enforce_tcb
/// and enforce_tcb_leaf attributes.
void Sema::CheckTCBEnforcement(const CallExpr *TheCall,
const FunctionDecl *Callee) {
const FunctionDecl *Caller = getCurFunctionDecl();
// Calls to builtins are not enforced.
if (!Caller || !Caller->hasAttr<EnforceTCBAttr>() ||
Callee->getBuiltinID() != 0)
return;
// Search through the enforce_tcb and enforce_tcb_leaf attributes to find
// all TCBs the callee is a part of.
llvm::StringSet<> CalleeTCBs;
for_each(Callee->specific_attrs<EnforceTCBAttr>(),
[&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(),
[&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
// Go through the TCBs the caller is a part of and emit warnings if Caller
// is in a TCB that the Callee is not.
for_each(
Caller->specific_attrs<EnforceTCBAttr>(),
[&](const auto *A) {
StringRef CallerTCB = A->getTCBName();
if (CalleeTCBs.count(CallerTCB) == 0) {
this->Diag(TheCall->getExprLoc(),
diag::warn_tcb_enforcement_violation) << Callee
<< CallerTCB;
}
});
}
|
/*
* ***** BEGIN GPL LICENSE BLOCK *****
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
* All rights reserved.
*
* The Original Code is: all of this file.
*
* Contributor(s): none yet.
*
* ***** END GPL LICENSE BLOCK *****
*/
/** \file gameengine/GameLogic/SCA_IScene.cpp
* \ingroup gamelogic
*/
#include "SCA_IScene.h"
#define DEBUG_MAX_DISPLAY 100
SCA_DebugProp::SCA_DebugProp(SCA_IObject *gameobj, const std::string &name)
: m_obj(gameobj), m_name(name)
{
}
SCA_DebugProp::~SCA_DebugProp()
{
}
SCA_IScene::SCA_IScene()
{
}
void SCA_IScene::RemoveAllDebugProperties()
{
m_debugList.clear();
}
SCA_IScene::~SCA_IScene()
{
RemoveAllDebugProperties();
}
const std::vector<SCA_DebugProp> &SCA_IScene::GetDebugProperties() const
{
return m_debugList;
}
bool SCA_IScene::PropertyInDebugList(SCA_IObject *gameobj, const std::string &name)
{
for (const SCA_DebugProp &prop : m_debugList) {
if (prop.m_obj == gameobj && prop.m_name == name) {
return true;
}
}
return false;
}
bool SCA_IScene::ObjectInDebugList(SCA_IObject *gameobj)
{
for (const SCA_DebugProp &prop : m_debugList) {
if (prop.m_obj == gameobj) {
return true;
}
}
return false;
}
void SCA_IScene::AddDebugProperty(SCA_IObject *gameobj, const std::string &name)
{
if (m_debugList.size() < DEBUG_MAX_DISPLAY) {
m_debugList.emplace_back(gameobj, name);
}
}
void SCA_IScene::RemoveDebugProperty(SCA_IObject *gameobj, const std::string &name)
{
for (std::vector<SCA_DebugProp>::iterator it = m_debugList.begin(); it != m_debugList.end();) {
const SCA_DebugProp &prop = *it;
if (prop.m_obj == gameobj && prop.m_name == name) {
it = m_debugList.erase(it);
break;
}
else {
++it;
}
}
}
void SCA_IScene::RemoveObjectDebugProperties(SCA_IObject *gameobj)
{
for (std::vector<SCA_DebugProp>::iterator it = m_debugList.begin(); it != m_debugList.end();) {
const SCA_DebugProp &prop = *it;
if (prop.m_obj == gameobj) {
it = m_debugList.erase(it);
continue;
}
else {
++it;
}
}
}
|
// MIT License
// Copyright (C) August 2016 Hotride
#include "GumpShop.h"
enum
{
ID_GB_NONE,
ID_GB_BUTTON_ACCEPT,
ID_GB_BUTTON_CLEAR,
ID_GB_SHOP_LIST,
ID_GB_SHOP_RESULT,
ID_GB_COUNT,
};
CGumpShop::CGumpShop(uint32_t serial, bool isBuyGump, short x, short y)
: CGump(GT_SHOP, serial, x, y)
, IsBuyGump(isBuyGump)
{
DEBUG_TRACE_FUNCTION;
Visible = !isBuyGump;
if (isBuyGump)
{
Add(new CGUIGumppic(0x0870, 0, 0));
}
else
{
Add(new CGUIGumppic(0x0872, 0, 0));
}
Add(new CGUIShader(&g_ColorizerShader, true));
m_ItemList[0] =
(CGUIHTMLGump *)Add(new CGUIHTMLGump(ID_GB_SHOP_LIST, 0, 30, 60, 215, 176, false, true));
Add(new CGUIShader(&g_ColorizerShader, false));
if (isBuyGump)
{
Add(new CGUIGumppic(0x0871, 170, 214));
}
else
{
Add(new CGUIGumppic(0x0873, 170, 214));
}
m_ItemList[1] =
(CGUIHTMLGump *)Add(new CGUIHTMLGump(ID_GB_SHOP_RESULT, 0, 200, 280, 215, 92, false, true));
Add(new CGUIHitBox(ID_GB_BUTTON_ACCEPT, 200, 406, 34, 30, true));
Add(new CGUIHitBox(ID_GB_BUTTON_CLEAR, 372, 410, 24, 24, true));
if (isBuyGump)
{
m_TotalPriceText = (CGUIText *)Add(new CGUIText(0x0386, 240, 385));
m_TotalPriceText->CreateTextureA(9, "0");
m_TotalGoldText = (CGUIText *)Add(new CGUIText(0x0386, 358, 385));
m_TotalGoldText->CreateTextureA(9, std::to_string(g_Player->Gold));
}
else
{
m_TotalPriceText = (CGUIText *)Add(new CGUIText(0x0386, 358, 386));
m_TotalPriceText->CreateTextureA(9, "0");
m_TotalGoldText = nullptr;
}
m_NameText = (CGUIText *)Add(new CGUIText(0x0386, 242, 408));
for (int i = 0; i < 2; i++)
{
CGUIHTMLButton *button = m_ItemList[i]->m_ButtonUp;
if (button != nullptr)
{
button->Graphic = 0x0824;
button->GraphicSelected = 0x0824;
button->GraphicPressed = 0x0824;
button->CheckPolygone = true;
if (i == 0)
{
button->SetY(button->GetY() - 11);
}
else
{
button->SetY(button->GetY() - 16);
}
}
button = m_ItemList[i]->m_ButtonDown;
if (button != nullptr)
{
button->Graphic = 0x0825;
button->GraphicSelected = 0x0825;
button->GraphicPressed = 0x0825;
button->CheckPolygone = true;
if (i == 0)
{
button->SetY(button->GetY() - 25);
}
else
{
button->SetX(button->GetX() - 1);
button->SetY(button->GetY() + 18);
}
}
CGUIHTMLSlider *slider = m_ItemList[i]->m_Slider;
if (slider != nullptr)
{
slider->Graphic = 0x001F;
slider->GraphicSelected = 0x001F;
slider->GraphicPressed = 0x001F;
slider->BackgroundGraphic = 0;
if (i == 0)
{
slider->SetY(slider->GetY() - 11);
slider->Length -= 14;
}
else
{
slider->SetY(slider->GetY() - 16);
slider->Length += 34;
}
}
}
}
CGumpShop::~CGumpShop()
{
}
void CGumpShop::SendList()
{
DEBUG_TRACE_FUNCTION;
CGameCharacter *vendor = g_World->FindWorldCharacter(Serial);
if (vendor == nullptr)
{
return;
}
if (IsBuyGump)
{
CPacketBuyRequest(this).Send();
}
else
{
CPacketSellRequest(this).Send();
}
}
void CGumpShop::UpdateTotalPrice()
{
DEBUG_TRACE_FUNCTION;
if (m_TotalPriceText != nullptr)
{
int totalPrice = 0;
QFOR(item, m_ItemList[1]->m_Items, CBaseGUI *)
{
if (item->Type == GOT_SHOPRESULT)
{
CGUIShopResult *shop = (CGUIShopResult *)item;
totalPrice += shop->Price * shop->m_MinMaxButtons->Value;
}
}
m_TotalPriceText->CreateTextureA(9, std::to_string(totalPrice));
}
}
void CGumpShop::PrepareContent()
{
DEBUG_TRACE_FUNCTION;
if (NoProcess && g_Player != nullptr)
{
string name = g_Player->GetName();
int len = (int)name.length();
if (m_ContinueCounter > len)
{
m_ContinueCounter = len;
}
name.resize(m_ContinueCounter);
static int counterCount = 0;
if (m_ContinueCounter == len)
{
NoProcess = false;
SendList();
}
else if (counterCount == 0)
{
if (m_ContinueCounter < len)
{
m_ContinueCounter++;
}
}
counterCount++;
if (counterCount >= 3)
{
counterCount = 0;
}
m_NameText->CreateTextureA(5, name);
WantRedraw = true;
}
}
void CGumpShop::GUMP_BUTTON_EVENT_C
{
DEBUG_TRACE_FUNCTION;
if (serial == ID_GB_BUTTON_ACCEPT) //Accept
{
NoProcess = true;
m_ContinueCounter = 0;
}
else if (serial == ID_GB_BUTTON_CLEAR)
{ //Clear
m_ContinueCounter = 0;
}
}
void CGumpShop::GUMP_SCROLL_BUTTON_EVENT_C
{
DEBUG_TRACE_FUNCTION;
CGUIMinMaxButtons *minmax = (CGUIMinMaxButtons *)g_PressedObject.LeftObject;
if (minmax == nullptr)
{
return;
}
bool deleteItem = false;
QFOR(item, m_ItemList[0]->m_Items, CBaseGUI *)
{
if (item->Type == GOT_SHOPITEM && item->Serial == minmax->Serial)
{
((CGUIShopItem *)item)->CreateCountText(minmax->Value);
deleteItem = (minmax->Value < 1);
break;
}
}
if (deleteItem)
{
uint32_t itemSerial = minmax->Serial;
int y = 0;
for (CBaseGUI *item = (CBaseGUI *)m_ItemList[1]->m_Items; item != nullptr;)
{
CBaseGUI *next = (CBaseGUI *)item->m_Next;
if (item->Type == GOT_SHOPRESULT)
{
if (item->Serial == itemSerial)
{
m_ItemList[1]->Delete(item);
}
else
{
item->SetY(y);
y += item->GetSize().Height;
}
}
item = next;
}
}
UpdateTotalPrice();
}
void CGumpShop::OnLeftMouseButtonUp()
{
DEBUG_TRACE_FUNCTION;
CGump::OnLeftMouseButtonUp();
if (g_Target.IsTargeting() && !g_ObjectInHand.Enabled &&
g_World->FindWorldObject(g_SelectedObject.Serial) != nullptr)
{
g_Target.SendTargetObject(g_SelectedObject.Serial);
g_MouseManager.CancelDoubleClick = true;
}
}
bool CGumpShop::OnLeftMouseButtonDoubleClick()
{
DEBUG_TRACE_FUNCTION;
bool result = false;
if (g_PressedObject.LeftObject != nullptr && g_PressedObject.LeftObject->IsGUI())
{
if (((CBaseGUI *)g_PressedObject.LeftObject)->Type == GOT_SHOPITEM)
{
CGUIShopItem *shopItem = (CGUIShopItem *)g_PressedObject.LeftObject;
CGUIShopResult *shopResult = nullptr;
int posY = 0;
QFOR(item, m_ItemList[1]->m_Items, CBaseGUI *)
{
if (item->Type == GOT_SHOPRESULT)
{
if (item->Serial == shopItem->Serial)
{
shopResult = (CGUIShopResult *)item;
break;
}
posY += ((CGUIShopResult *)item)->GetSize().Height;
}
}
if (shopResult != nullptr)
{
CGUIMinMaxButtons *minmax = shopResult->m_MinMaxButtons;
if (minmax->Value < minmax->MaxValue)
{
if (g_ShiftPressed)
{
minmax->Value = minmax->MaxValue;
}
else
{
minmax->Value += 1;
}
minmax->UpdateText();
shopItem->CreateCountText(minmax->Value);
WantRedraw = true;
result = true;
UpdateTotalPrice();
}
}
else
{
shopResult =
(CGUIShopResult *)m_ItemList[1]->Add(new CGUIShopResult(shopItem, 0, posY));
CGUIMinMaxButtons *minmax = shopResult->m_MinMaxButtons;
if (g_ShiftPressed)
{
minmax->Value = minmax->MaxValue;
minmax->UpdateText();
}
shopItem->CreateCountText(minmax->Value);
WantRedraw = true;
result = true;
UpdateTotalPrice();
m_ItemList[1]->CalculateDataSize();
}
}
}
return result;
}
|
/*******************************************************************************
+
+ LEDA 6.3
+
+
+ stl_sort0.c
+
+
+ Copyright (c) 1995-2010
+ by Algorithmic Solutions Software GmbH
+ All rights reserved.
+
*******************************************************************************/
#define LEDA_NO_MIN_MAX_TEMPL
#include <LEDA/anim/gw_view.h>
#include <LEDA/anim/cell.h>
#include <LEDA/anim/smart_pointer.h>
#include <assert.h>
#include <algorithm>
using namespace leda;
using std::cout;
using std::endl;
typedef cell<int> Int;
typedef smart_pointer<Int> Iterator;
static gw_view V(850,700,"STL Sort");
static map<const Int*,gw_stick_element*> M(0);
static map<const Iterator*,gw_pointer_element*> P(0);
static map<gw_pointer_element*,list<point> > p_stack;
static map<gw_pointer_element*,list<point> > e_stack;
static bool Wait = false;
static int id = 0;
static int id1 = 0;
static int id2 = 0;
static double cell_x = 80;
static double cell_y = 200;
const int steps = 150;
//const int steps = 64;
//const int steps = 16;
void assign_value(Int& i, const int& x)
{ V.scene_begin(steps);
M[&i]->assign(x);
V.scene_end();
V.scene_play();
}
void assign_cell(Int& i, const Int& j)
{ gw_stick_element* s1 = M[&i];
gw_stick_element* s2 = M[&j];
assert(s1);
assert(s2);
point pi = M[&i]->get_position();
point pj = M[&j]->get_position();
double angle = LEDA_PI/2;
if (pi.xcoord() < pj.xcoord()) angle = -angle;
circular_motion cm(angle);
V.scene_begin(steps);
s1->assign(*s2,&cm);
V.scene_end();
V.scene_play();
}
void construct_cell(Int& i, const int& x)
{
cout << "construct_cell x = " << x << endl;
gw_stick_element* st = new gw_stick_element;
st->set_value(x);
st->set_position(cell_x+ 40 * id++, cell_y);
V.add_element(*st);
V.draw();
M[&i] = st;
}
void copy_cell(Int& i, const Int& j)
{ gw_stick_element* st = new gw_stick_element;
st->set_value(0);
st->set_position(cell_x + 40 * id1++, cell_y+150);
V.add_element(*st);
M[&i] = st;
assign_cell(i,j);
}
void delete_cell(Int& i)
{ //if (Wait) V.wait();
V.del_element(*M[&i]); id1--;
}
void assign_pointer(Iterator& i, const Int* p)
{
cout << "assign pointer" << endl;
V.scene_begin(steps);
P[&i]->assign(*M[p]);
V.scene_end();
V.scene_play();
}
void assign_iterator(Iterator& i, const Iterator& j)
{
cout << "assign iterator" << endl;
gw_pointer_element* p1 = P[&i];
gw_stick_element* c2 = M[&(*j)];
assert(p1);
assert(c2);
V.scene_begin(steps);
p1->assign(*c2);
V.scene_end();
V.scene_play();
}
void construct_iterator(Iterator& i, Int* p)
{
cout << "construct_iterator" << endl;
gw_pointer_element* pt = new gw_pointer_element(*M[p]);
point pos(cell_x, cell_y-(20*++id2));
pt->set_position(pos);
V.add_element(*pt);
V.draw();
P[&i] = pt;
}
void copy_iterator(Iterator& i, const Iterator& j)
{
cout << "copy_iterator" << endl;
gw_pointer_element* pt = P[&j];
P[&i] = pt;
p_stack[pt].push(pt->get_position());
e_stack[pt].push(pt->get_value_position());
V.draw();
leda::wait(0.25);
}
void delete_iterator(Iterator& i)
{ //if (Wait) V.wait();
cout << "delete_iterator" << endl;
gw_pointer_element* pt = P[&i];
if (p_stack[pt].empty())
{ V.del_element(*pt);
id2--;
}
else {
point p = p_stack[pt].pop();
point q = e_stack[pt].pop();
pt->set_position(p);
pt->set_value_position(q);
}
V.draw();
leda::wait(0.25);
}
void increment_iterator(Iterator& i)
{
cout << "increment_iterator" << endl;
gw_pointer_element* pt = P[&i];
V.scene_begin(steps);
pt->assign(*M[&(*i)]);
V.scene_end();
V.scene_play();
}
void increment_iterator1(Iterator& i, Int*) { increment_iterator(i); }
void decrement_iterator(Iterator& i)
{
cout << "decrement_iterator" << endl;
gw_pointer_element* pt = P[&i];
V.scene_begin(steps);
pt->assign(*M[&(*i)]);
V.scene_end();
V.scene_play();
}
void decrement_iterator1(Iterator& i, Int*) { decrement_iterator(i); }
template<class Iter>
void bubblesort(const Iter& first, const Iter& stop)
{ for(Iter x=stop; x!=first; x--)
for(Iter y=first+1; y!=x; y++)
{ Iter z = y-1;
if (*z > *y) std::swap(*z,*y);
}
}
template<class Iter>
void merge(Iter first, Iter middle, const Iter& stop)
{
typedef typename Iter::value_type E;
int len = stop-first;
E* tmp = new E[len+1];
Iter p = tmp;
Iter q = tmp + len;
for(Iter p = tmp; p != q; ++p)
{ if (middle == stop || *first < *middle)
*p = *first++;
else
*p = *middle++;
}
}
int main(int argc, char** argv)
{
cout << argc << endl;
if (argc > 1) { srandom(atoi(argv[1])); srand(atoi(argv[1])); }
attach(Int::construct_event, construct_cell);
attach(Int::copy_event, copy_cell);
attach(Int::assign_event, assign_value);
attach(Int::assign_event, assign_cell);
attach(Int::destruct_event, delete_cell);
attach(Iterator::construct_event, construct_iterator);
attach(Iterator::copy_event, copy_iterator);
attach(Iterator::increment_event, increment_iterator);
attach(Iterator::increment_event, increment_iterator1);
attach(Iterator::decrement_event, decrement_iterator);
attach(Iterator::decrement_event, decrement_iterator1);
attach(Iterator::assign_event, assign_iterator);
attach(Iterator::assign_event, assign_pointer);
attach(Iterator::destruct_event, delete_iterator);
V.display(window::center,window::center);
Int A[13];
Iterator first = A;
Iterator middle = A+6;
Iterator stop = A+12;
Int* p_first = A;
Int* p_middle = A+6;
Int* p_stop = A+12;
do
{ //V.wait();
//V.scene_begin(32);
//V.set_anim(false);
{
Iterator i = stop;
do *--i = 10*(i - first + 1);
while (i!=first);
}
//V.wait();
//std::random_shuffle(p_first,p_stop);
std::random_shuffle(first,stop);
V.wait();
//bubblesort(p_first,p_middle);
bubblesort(first,middle);
//bubblesort(p_middle,p_stop);
bubblesort(middle,stop);
//V.set_anim(true);
//V.scene_end();
//V.scene_play();
V.wait();
id = 0;
cell_y += 150;
std::inplace_merge(first,middle,stop);
//merge(first,middle,stop);
// std::sort(first,stop);
//std::stable_sort(first,stop);
} while (V.wait());
return 0;
}
|
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "nsGIOService.h"
#include "nsStringAPI.h"
#include "nsIURI.h"
#include "nsTArray.h"
#include "nsIStringEnumerator.h"
#include "nsAutoPtr.h"
#include <dlfcn.h>
#include <gio/gio.h>
#include <gtk/gtk.h>
typedef const char* (*get_commandline_t)(GAppInfo*);
char *
get_content_type_from_mime_type(const char *mimeType)
{
GList* contentTypes = g_content_types_get_registered();
GList* ct_ptr = contentTypes;
char* foundContentType = NULL;
while (ct_ptr) {
char *mimeTypeFromContentType = g_content_type_get_mime_type((char*)ct_ptr->data);
if (strcmp(mimeTypeFromContentType, mimeType) == 0) {
foundContentType = g_strdup((char*)ct_ptr->data);
g_free(mimeTypeFromContentType);
break;
}
g_free(mimeTypeFromContentType);
ct_ptr = ct_ptr->next;
}
g_list_foreach(contentTypes, (GFunc) g_free, NULL);
g_list_free(contentTypes);
return foundContentType;
}
class nsGIOMimeApp : public nsIGIOMimeApp
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIGIOMIMEAPP
nsGIOMimeApp(GAppInfo* aApp) : mApp(aApp) {}
~nsGIOMimeApp() { g_object_unref(mApp); }
private:
GAppInfo *mApp;
};
NS_IMPL_ISUPPORTS1(nsGIOMimeApp, nsIGIOMimeApp)
NS_IMETHODIMP
nsGIOMimeApp::GetId(nsACString& aId)
{
aId.Assign(g_app_info_get_id(mApp));
return NS_OK;
}
NS_IMETHODIMP
nsGIOMimeApp::GetName(nsACString& aName)
{
aName.Assign(g_app_info_get_name(mApp));
return NS_OK;
}
NS_IMETHODIMP
nsGIOMimeApp::GetCommand(nsACString& aCommand)
{
get_commandline_t g_app_info_get_commandline_ptr;
void *libHandle = dlopen("libgio-2.0.so.0", RTLD_LAZY);
if (!libHandle) {
return NS_ERROR_FAILURE;
}
dlerror(); /* clear any existing error */
g_app_info_get_commandline_ptr =
(get_commandline_t) dlsym(libHandle, "g_app_info_get_commandline");
if (dlerror() == NULL) {
const char *cmd = g_app_info_get_commandline_ptr(mApp);
if (!cmd) {
dlclose(libHandle);
return NS_ERROR_FAILURE;
}
aCommand.Assign(cmd);
}
dlclose(libHandle);
return NS_OK;
}
NS_IMETHODIMP
nsGIOMimeApp::GetExpectsURIs(int32_t* aExpects)
{
*aExpects = g_app_info_supports_uris(mApp);
return NS_OK;
}
NS_IMETHODIMP
nsGIOMimeApp::Launch(const nsACString& aUri)
{
GList uris = { 0 };
PromiseFlatCString flatUri(aUri);
uris.data = const_cast<char*>(flatUri.get());
GError *error = NULL;
gboolean result = g_app_info_launch_uris(mApp, &uris, NULL, &error);
if (!result) {
g_warning("Cannot launch application: %s", error->message);
g_error_free(error);
return NS_ERROR_FAILURE;
}
return NS_OK;
}
class GIOUTF8StringEnumerator : public nsIUTF8StringEnumerator
{
public:
GIOUTF8StringEnumerator() : mIndex(0) { }
~GIOUTF8StringEnumerator() { }
NS_DECL_ISUPPORTS
NS_DECL_NSIUTF8STRINGENUMERATOR
nsTArray<nsCString> mStrings;
uint32_t mIndex;
};
NS_IMPL_ISUPPORTS1(GIOUTF8StringEnumerator, nsIUTF8StringEnumerator)
NS_IMETHODIMP
GIOUTF8StringEnumerator::HasMore(bool* aResult)
{
*aResult = mIndex < mStrings.Length();
return NS_OK;
}
NS_IMETHODIMP
GIOUTF8StringEnumerator::GetNext(nsACString& aResult)
{
if (mIndex >= mStrings.Length())
return NS_ERROR_UNEXPECTED;
aResult.Assign(mStrings[mIndex]);
++mIndex;
return NS_OK;
}
NS_IMETHODIMP
nsGIOMimeApp::GetSupportedURISchemes(nsIUTF8StringEnumerator** aSchemes)
{
*aSchemes = nullptr;
nsRefPtr<GIOUTF8StringEnumerator> array = new GIOUTF8StringEnumerator();
NS_ENSURE_TRUE(array, NS_ERROR_OUT_OF_MEMORY);
GVfs *gvfs = g_vfs_get_default();
if (!gvfs) {
g_warning("Cannot get GVfs object.");
return NS_ERROR_OUT_OF_MEMORY;
}
const gchar* const * uri_schemes = g_vfs_get_supported_uri_schemes(gvfs);
while (*uri_schemes != NULL) {
if (!array->mStrings.AppendElement(*uri_schemes)) {
return NS_ERROR_OUT_OF_MEMORY;
}
uri_schemes++;
}
NS_ADDREF(*aSchemes = array);
return NS_OK;
}
NS_IMETHODIMP
nsGIOMimeApp::SetAsDefaultForMimeType(nsACString const& aMimeType)
{
char *content_type =
get_content_type_from_mime_type(PromiseFlatCString(aMimeType).get());
if (!content_type)
return NS_ERROR_FAILURE;
GError *error = NULL;
g_app_info_set_as_default_for_type(mApp,
content_type,
&error);
if (error) {
g_warning("Cannot set application as default for MIME type (%s): %s",
PromiseFlatCString(aMimeType).get(),
error->message);
g_error_free(error);
g_free(content_type);
return NS_ERROR_FAILURE;
}
g_free(content_type);
return NS_OK;
}
/**
* Set default application for files with given extensions
* @param fileExts string of space separated extensions
* @return NS_OK when application was set as default for given extensions,
* NS_ERROR_FAILURE otherwise
*/
NS_IMETHODIMP
nsGIOMimeApp::SetAsDefaultForFileExtensions(nsACString const& fileExts)
{
GError *error = NULL;
char *extensions = g_strdup(PromiseFlatCString(fileExts).get());
char *ext_pos = extensions;
char *space_pos;
while ( (space_pos = strchr(ext_pos, ' ')) || (*ext_pos != '\0') ) {
if (space_pos) {
*space_pos = '\0';
}
g_app_info_set_as_default_for_extension(mApp, ext_pos, &error);
if (error) {
g_warning("Cannot set application as default for extension (%s): %s",
ext_pos,
error->message);
g_error_free(error);
g_free(extensions);
return NS_ERROR_FAILURE;
}
if (space_pos) {
ext_pos = space_pos + 1;
} else {
*ext_pos = '\0';
}
}
g_free(extensions);
return NS_OK;
}
/**
* Set default application for URI's of a particular scheme
* @param aURIScheme string containing the URI scheme
* @return NS_OK when application was set as default for URI scheme,
* NS_ERROR_FAILURE otherwise
*/
NS_IMETHODIMP
nsGIOMimeApp::SetAsDefaultForURIScheme(nsACString const& aURIScheme)
{
GError *error = NULL;
nsAutoCString contentType("x-scheme-handler/");
contentType.Append(aURIScheme);
g_app_info_set_as_default_for_type(mApp,
contentType.get(),
&error);
if (error) {
g_warning("Cannot set application as default for URI scheme (%s): %s",
PromiseFlatCString(aURIScheme).get(),
error->message);
g_error_free(error);
return NS_ERROR_FAILURE;
}
return NS_OK;
}
NS_IMPL_ISUPPORTS1(nsGIOService, nsIGIOService)
NS_IMETHODIMP
nsGIOService::GetMimeTypeFromExtension(const nsACString& aExtension,
nsACString& aMimeType)
{
nsAutoCString fileExtToUse("file.");
fileExtToUse.Append(aExtension);
gboolean result_uncertain;
char *content_type = g_content_type_guess(fileExtToUse.get(),
NULL,
0,
&result_uncertain);
if (!content_type)
return NS_ERROR_FAILURE;
char *mime_type = g_content_type_get_mime_type(content_type);
if (!mime_type) {
g_free(content_type);
return NS_ERROR_FAILURE;
}
aMimeType.Assign(mime_type);
g_free(mime_type);
g_free(content_type);
return NS_OK;
}
// used in nsGNOMERegistry
// -----------------------------------------------------------------------------
NS_IMETHODIMP
nsGIOService::GetAppForURIScheme(const nsACString& aURIScheme,
nsIGIOMimeApp** aApp)
{
*aApp = nullptr;
GAppInfo *app_info = g_app_info_get_default_for_uri_scheme(
PromiseFlatCString(aURIScheme).get());
if (app_info) {
nsGIOMimeApp *mozApp = new nsGIOMimeApp(app_info);
NS_ADDREF(*aApp = mozApp);
} else {
return NS_ERROR_FAILURE;
}
return NS_OK;
}
NS_IMETHODIMP
nsGIOService::GetAppForMimeType(const nsACString& aMimeType,
nsIGIOMimeApp** aApp)
{
*aApp = nullptr;
char *content_type =
get_content_type_from_mime_type(PromiseFlatCString(aMimeType).get());
if (!content_type)
return NS_ERROR_FAILURE;
GAppInfo *app_info = g_app_info_get_default_for_type(content_type, false);
if (app_info) {
nsGIOMimeApp *mozApp = new nsGIOMimeApp(app_info);
NS_ENSURE_TRUE(mozApp, NS_ERROR_OUT_OF_MEMORY);
NS_ADDREF(*aApp = mozApp);
} else {
g_free(content_type);
return NS_ERROR_FAILURE;
}
g_free(content_type);
return NS_OK;
}
NS_IMETHODIMP
nsGIOService::GetDescriptionForMimeType(const nsACString& aMimeType,
nsACString& aDescription)
{
char *content_type =
get_content_type_from_mime_type(PromiseFlatCString(aMimeType).get());
if (!content_type)
return NS_ERROR_FAILURE;
char *desc = g_content_type_get_description(content_type);
if (!desc) {
g_free(content_type);
return NS_ERROR_FAILURE;
}
aDescription.Assign(desc);
g_free(content_type);
g_free(desc);
return NS_OK;
}
NS_IMETHODIMP
nsGIOService::ShowURI(nsIURI* aURI)
{
nsAutoCString spec;
aURI->GetSpec(spec);
GError *error = NULL;
if (!g_app_info_launch_default_for_uri(spec.get(), NULL, &error)) {
g_warning("Could not launch default application for URI: %s" ,error->message);
g_error_free(error);
return NS_ERROR_FAILURE;
}
return NS_OK;
}
NS_IMETHODIMP
nsGIOService::ShowURIForInput(const nsACString& aUri)
{
GFile *file = g_file_new_for_commandline_arg(PromiseFlatCString(aUri).get());
char* spec = g_file_get_uri(file);
nsresult rv = NS_ERROR_FAILURE;
GError *error = NULL;
g_app_info_launch_default_for_uri(spec, NULL, &error);
if (error) {
g_warning("Cannot launch default application: %s", error->message);
g_error_free(error);
} else {
rv = NS_OK;
}
g_object_unref(file);
g_free(spec);
return rv;
}
/**
* Create or find already existing application info for specified command
* and application name.
* @param cmd command to execute
* @param appName application name
* @param appInfo location where created GAppInfo is stored
* @return NS_OK when object is created, NS_ERROR_FAILURE otherwise.
*/
NS_IMETHODIMP
nsGIOService::CreateAppFromCommand(nsACString const& cmd,
nsACString const& appName,
nsIGIOMimeApp** appInfo)
{
GError *error = NULL;
*appInfo = nullptr;
GAppInfo *app_info = NULL, *app_info_from_list = NULL;
GList *apps = g_app_info_get_all();
GList *apps_p = apps;
// Try to find relevant and existing GAppInfo in all installed application
// We do this by comparing each GAppInfo's executable with out own
while (apps_p) {
app_info_from_list = (GAppInfo*) apps_p->data;
if (!app_info) {
// If the executable is not absolute, get it's full path
char *executable = g_find_program_in_path(g_app_info_get_executable(app_info_from_list));
if (executable && strcmp(executable, PromiseFlatCString(cmd).get()) == 0) {
g_object_ref (app_info_from_list);
app_info = app_info_from_list;
}
g_free(executable);
}
g_object_unref(app_info_from_list);
apps_p = apps_p->next;
}
g_list_free(apps);
if (!app_info) {
app_info = g_app_info_create_from_commandline(PromiseFlatCString(cmd).get(),
PromiseFlatCString(appName).get(),
G_APP_INFO_CREATE_SUPPORTS_URIS,
&error);
}
if (!app_info) {
g_warning("Cannot create application info from command: %s", error->message);
g_error_free(error);
return NS_ERROR_FAILURE;
}
nsGIOMimeApp *mozApp = new nsGIOMimeApp(app_info);
NS_ENSURE_TRUE(mozApp, NS_ERROR_OUT_OF_MEMORY);
NS_ADDREF(*appInfo = mozApp);
return NS_OK;
}
|
/*
* Copyright (c) 2013-2014 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* 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 copyright holders 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.
*
* Authors: Andrew Bardsley
*/
#include <iomanip>
#include <sstream>
#include "arch/locked_mem.hh"
#include "arch/mmapped_ipr.hh"
#include "cpu/minor/cpu.hh"
#include "cpu/minor/exec_context.hh"
#include "cpu/minor/execute.hh"
#include "cpu/minor/lsq.hh"
#include "cpu/minor/pipeline.hh"
#include "debug/Activity.hh"
#include "debug/MinorMem.hh"
namespace Minor
{
/** Returns the offset of addr into an aligned a block of size block_size */
static Addr
addrBlockOffset(Addr addr, unsigned int block_size)
{
return addr & (block_size - 1);
}
/** Returns true if the given [addr .. addr+size-1] transfer needs to be
* fragmented across a block size of block_size */
static bool
transferNeedsBurst(Addr addr, unsigned int size, unsigned int block_size)
{
return (addrBlockOffset(addr, block_size) + size) > block_size;
}
LSQ::LSQRequest::LSQRequest(LSQ &port_, MinorDynInstPtr inst_, bool isLoad_,
PacketDataPtr data_, uint64_t *res_) :
SenderState(),
port(port_),
inst(inst_),
isLoad(isLoad_),
data(data_),
packet(NULL),
request(),
fault(NoFault),
res(res_),
skipped(false),
issuedToMemory(false),
state(NotIssued)
{ }
LSQ::AddrRangeCoverage
LSQ::LSQRequest::containsAddrRangeOf(
Addr req1_addr, unsigned int req1_size,
Addr req2_addr, unsigned int req2_size)
{
/* 'end' here means the address of the byte just past the request
* blocks */
Addr req2_end_addr = req2_addr + req2_size;
Addr req1_end_addr = req1_addr + req1_size;
AddrRangeCoverage ret;
if (req1_addr > req2_end_addr || req1_end_addr < req2_addr)
ret = NoAddrRangeCoverage;
else if (req1_addr <= req2_addr && req1_end_addr >= req2_end_addr)
ret = FullAddrRangeCoverage;
else
ret = PartialAddrRangeCoverage;
return ret;
}
LSQ::AddrRangeCoverage
LSQ::LSQRequest::containsAddrRangeOf(LSQRequestPtr other_request)
{
return containsAddrRangeOf(request.getPaddr(), request.getSize(),
other_request->request.getPaddr(), other_request->request.getSize());
}
bool
LSQ::LSQRequest::isBarrier()
{
return inst->isInst() && inst->staticInst->isMemBarrier();
}
bool
LSQ::LSQRequest::needsToBeSentToStoreBuffer()
{
return state == StoreToStoreBuffer;
}
void
LSQ::LSQRequest::setState(LSQRequestState new_state)
{
DPRINTFS(MinorMem, (&port), "Setting state from %d to %d for request:"
" %s\n", state, new_state, *inst);
state = new_state;
}
bool
LSQ::LSQRequest::isComplete() const
{
/* @todo, There is currently only one 'completed' state. This
* may not be a good choice */
return state == Complete;
}
void
LSQ::LSQRequest::reportData(std::ostream &os) const
{
os << (isLoad ? 'R' : 'W') << ';';
inst->reportData(os);
os << ';' << state;
}
std::ostream &
operator <<(std::ostream &os, LSQ::AddrRangeCoverage coverage)
{
switch (coverage) {
case LSQ::PartialAddrRangeCoverage:
os << "PartialAddrRangeCoverage";
break;
case LSQ::FullAddrRangeCoverage:
os << "FullAddrRangeCoverage";
break;
case LSQ::NoAddrRangeCoverage:
os << "NoAddrRangeCoverage";
break;
default:
os << "AddrRangeCoverage-" << static_cast<int>(coverage);
break;
}
return os;
}
std::ostream &
operator <<(std::ostream &os, LSQ::LSQRequest::LSQRequestState state)
{
switch (state) {
case LSQ::LSQRequest::NotIssued:
os << "NotIssued";
break;
case LSQ::LSQRequest::InTranslation:
os << "InTranslation";
break;
case LSQ::LSQRequest::Translated:
os << "Translated";
break;
case LSQ::LSQRequest::Failed:
os << "Failed";
break;
case LSQ::LSQRequest::RequestIssuing:
os << "RequestIssuing";
break;
case LSQ::LSQRequest::StoreToStoreBuffer:
os << "StoreToStoreBuffer";
break;
case LSQ::LSQRequest::StoreInStoreBuffer:
os << "StoreInStoreBuffer";
break;
case LSQ::LSQRequest::StoreBufferIssuing:
os << "StoreBufferIssuing";
break;
case LSQ::LSQRequest::RequestNeedsRetry:
os << "RequestNeedsRetry";
break;
case LSQ::LSQRequest::StoreBufferNeedsRetry:
os << "StoreBufferNeedsRetry";
break;
case LSQ::LSQRequest::Complete:
os << "Complete";
break;
default:
os << "LSQRequestState-" << static_cast<int>(state);
break;
}
return os;
}
void
LSQ::clearMemBarrier(MinorDynInstPtr inst)
{
bool is_last_barrier = inst->id.execSeqNum >= lastMemBarrier;
DPRINTF(MinorMem, "Moving %s barrier out of store buffer inst: %s\n",
(is_last_barrier ? "last" : "a"), *inst);
if (is_last_barrier)
lastMemBarrier = 0;
}
void
LSQ::SingleDataRequest::finish(const Fault &fault_, RequestPtr request_,
ThreadContext *tc, BaseTLB::Mode mode)
{
fault = fault_;
port.numAccessesInDTLB--;
DPRINTFS(MinorMem, (&port), "Received translation response for"
" request: %s\n", *inst);
makePacket();
setState(Translated);
port.tryToSendToTransfers(this);
/* Let's try and wake up the processor for the next cycle */
port.cpu.wakeupOnEvent(Pipeline::ExecuteStageId);
}
void
LSQ::SingleDataRequest::startAddrTranslation()
{
ThreadContext *thread = port.cpu.getContext(
inst->id.threadId);
port.numAccessesInDTLB++;
setState(LSQ::LSQRequest::InTranslation);
DPRINTFS(MinorMem, (&port), "Submitting DTLB request\n");
/* Submit the translation request. The response will come through
* finish/markDelayed on the LSQRequest as it bears the Translation
* interface */
thread->getDTBPtr()->translateTiming(
&request, thread, this, (isLoad ? BaseTLB::Read : BaseTLB::Write));
}
void
LSQ::SingleDataRequest::retireResponse(PacketPtr packet_)
{
DPRINTFS(MinorMem, (&port), "Retiring packet\n");
packet = packet_;
packetInFlight = false;
setState(Complete);
}
void
LSQ::SplitDataRequest::finish(const Fault &fault_, RequestPtr request_,
ThreadContext *tc, BaseTLB::Mode mode)
{
fault = fault_;
port.numAccessesInDTLB--;
unsigned int M5_VAR_USED expected_fragment_index =
numTranslatedFragments;
numInTranslationFragments--;
numTranslatedFragments++;
DPRINTFS(MinorMem, (&port), "Received translation response for fragment"
" %d of request: %s\n", expected_fragment_index, *inst);
assert(request_ == fragmentRequests[expected_fragment_index]);
/* Wake up next cycle to get things going again in case the
* tryToSendToTransfers does take */
port.cpu.wakeupOnEvent(Pipeline::ExecuteStageId);
if (fault != NoFault) {
/* tryToSendToTransfers will handle the fault */
DPRINTFS(MinorMem, (&port), "Faulting translation for fragment:"
" %d of request: %s\n",
expected_fragment_index, *inst);
setState(Translated);
port.tryToSendToTransfers(this);
} else if (numTranslatedFragments == numFragments) {
makeFragmentPackets();
setState(Translated);
port.tryToSendToTransfers(this);
} else {
/* Avoid calling translateTiming from within ::finish */
assert(!translationEvent.scheduled());
port.cpu.schedule(translationEvent, curTick());
}
}
LSQ::SplitDataRequest::SplitDataRequest(LSQ &port_, MinorDynInstPtr inst_,
bool isLoad_, PacketDataPtr data_, uint64_t *res_) :
LSQRequest(port_, inst_, isLoad_, data_, res_),
translationEvent(*this),
numFragments(0),
numInTranslationFragments(0),
numTranslatedFragments(0),
numIssuedFragments(0),
numRetiredFragments(0),
fragmentRequests(),
fragmentPackets()
{
/* Don't know how many elements are needed until the request is
* populated by the caller. */
}
LSQ::SplitDataRequest::~SplitDataRequest()
{
for (auto i = fragmentRequests.begin();
i != fragmentRequests.end(); i++)
{
delete *i;
}
for (auto i = fragmentPackets.begin();
i != fragmentPackets.end(); i++)
{
delete *i;
}
}
void
LSQ::SplitDataRequest::makeFragmentRequests()
{
Addr base_addr = request.getVaddr();
unsigned int whole_size = request.getSize();
unsigned int line_width = port.lineWidth;
unsigned int fragment_size;
Addr fragment_addr;
/* Assume that this transfer is across potentially many block snap
* boundaries:
*
* | _|________|________|________|___ |
* | |0| 1 | 2 | 3 | 4 | |
* | |_|________|________|________|___| |
* | | | | | |
*
* The first transfer (0) can be up to lineWidth in size.
* All the middle transfers (1-3) are lineWidth in size
* The last transfer (4) can be from zero to lineWidth - 1 in size
*/
unsigned int first_fragment_offset =
addrBlockOffset(base_addr, line_width);
unsigned int last_fragment_size =
addrBlockOffset(base_addr + whole_size, line_width);
unsigned int first_fragment_size =
line_width - first_fragment_offset;
unsigned int middle_fragments_total_size =
whole_size - (first_fragment_size + last_fragment_size);
assert(addrBlockOffset(middle_fragments_total_size, line_width) == 0);
unsigned int middle_fragment_count =
middle_fragments_total_size / line_width;
numFragments = 1 /* first */ + middle_fragment_count +
(last_fragment_size == 0 ? 0 : 1);
DPRINTFS(MinorMem, (&port), "Dividing transfer into %d fragmentRequests."
" First fragment size: %d Last fragment size: %d\n",
numFragments, first_fragment_size,
(last_fragment_size == 0 ? line_width : last_fragment_size));
assert(((middle_fragment_count * line_width) +
first_fragment_size + last_fragment_size) == whole_size);
fragment_addr = base_addr;
fragment_size = first_fragment_size;
/* Just past the last address in the request */
Addr end_addr = base_addr + whole_size;
for (unsigned int fragment_index = 0; fragment_index < numFragments;
fragment_index++)
{
bool M5_VAR_USED is_last_fragment = false;
if (fragment_addr == base_addr) {
/* First fragment */
fragment_size = first_fragment_size;
} else {
if ((fragment_addr + line_width) > end_addr) {
/* Adjust size of last fragment */
fragment_size = end_addr - fragment_addr;
is_last_fragment = true;
} else {
/* Middle fragments */
fragment_size = line_width;
}
}
Request *fragment = new Request();
fragment->setThreadContext(request.contextId(), /* thread id */ 0);
fragment->setVirt(0 /* asid */,
fragment_addr, fragment_size, request.getFlags(),
request.masterId(),
request.getPC());
DPRINTFS(MinorMem, (&port), "Generating fragment addr: 0x%x size: %d"
" (whole request addr: 0x%x size: %d) %s\n",
fragment_addr, fragment_size, base_addr, whole_size,
(is_last_fragment ? "last fragment" : ""));
fragment_addr += fragment_size;
fragmentRequests.push_back(fragment);
}
}
void
LSQ::SplitDataRequest::makeFragmentPackets()
{
Addr base_addr = request.getVaddr();
DPRINTFS(MinorMem, (&port), "Making packets for request: %s\n", *inst);
for (unsigned int fragment_index = 0; fragment_index < numFragments;
fragment_index++)
{
Request *fragment = fragmentRequests[fragment_index];
DPRINTFS(MinorMem, (&port), "Making packet %d for request: %s"
" (%d, 0x%x)\n",
fragment_index, *inst,
(fragment->hasPaddr() ? "has paddr" : "no paddr"),
(fragment->hasPaddr() ? fragment->getPaddr() : 0));
Addr fragment_addr = fragment->getVaddr();
unsigned int fragment_size = fragment->getSize();
uint8_t *request_data = NULL;
if (!isLoad) {
/* Split data for Packets. Will become the property of the
* outgoing Packets */
request_data = new uint8_t[fragment_size];
std::memcpy(request_data, data + (fragment_addr - base_addr),
fragment_size);
}
assert(fragment->hasPaddr());
PacketPtr fragment_packet =
makePacketForRequest(*fragment, isLoad, this, request_data);
fragmentPackets.push_back(fragment_packet);
/* Accumulate flags in parent request */
request.setFlags(fragment->getFlags());
}
/* Might as well make the overall/response packet here */
/* Get the physical address for the whole request/packet from the first
* fragment */
request.setPaddr(fragmentRequests[0]->getPaddr());
makePacket();
}
void
LSQ::SplitDataRequest::startAddrTranslation()
{
setState(LSQ::LSQRequest::InTranslation);
makeFragmentRequests();
numInTranslationFragments = 0;
numTranslatedFragments = 0;
/* @todo, just do these in sequence for now with
* a loop of:
* do {
* sendNextFragmentToTranslation ; translateTiming ; finish
* } while (numTranslatedFragments != numFragments);
*/
/* Do first translation */
sendNextFragmentToTranslation();
}
PacketPtr
LSQ::SplitDataRequest::getHeadPacket()
{
assert(numIssuedFragments < numFragments);
return fragmentPackets[numIssuedFragments];
}
void
LSQ::SplitDataRequest::stepToNextPacket()
{
assert(numIssuedFragments < numFragments);
numIssuedFragments++;
}
void
LSQ::SplitDataRequest::retireResponse(PacketPtr response)
{
assert(numRetiredFragments < numFragments);
DPRINTFS(MinorMem, (&port), "Retiring fragment addr: 0x%x size: %d"
" offset: 0x%x (retired fragment num: %d) %s\n",
response->req->getVaddr(), response->req->getSize(),
request.getVaddr() - response->req->getVaddr(),
numRetiredFragments,
(fault == NoFault ? "" : fault->name()));
numRetiredFragments++;
if (skipped) {
/* Skip because we already knew the request had faulted or been
* skipped */
DPRINTFS(MinorMem, (&port), "Skipping this fragment\n");
} else if (response->isError()) {
/* Mark up the error and leave to execute to handle it */
DPRINTFS(MinorMem, (&port), "Fragment has an error, skipping\n");
setSkipped();
packet->copyError(response);
} else {
if (isLoad) {
if (!data) {
/* For a split transfer, a Packet must be constructed
* to contain all returning data. This is that packet's
* data */
data = new uint8_t[request.getSize()];
}
/* Populate the portion of the overall response data represented
* by the response fragment */
std::memcpy(
data + (response->req->getVaddr() - request.getVaddr()),
response->getConstPtr<uint8_t>(),
response->req->getSize());
}
}
/* Complete early if we're skipping are no more in-flight accesses */
if (skipped && !hasPacketsInMemSystem()) {
DPRINTFS(MinorMem, (&port), "Completed skipped burst\n");
setState(Complete);
if (packet->needsResponse())
packet->makeResponse();
}
if (numRetiredFragments == numFragments)
setState(Complete);
if (!skipped && isComplete()) {
DPRINTFS(MinorMem, (&port), "Completed burst %d\n", packet != NULL);
DPRINTFS(MinorMem, (&port), "Retired packet isRead: %d isWrite: %d"
" needsResponse: %d packetSize: %s requestSize: %s responseSize:"
" %s\n", packet->isRead(), packet->isWrite(),
packet->needsResponse(), packet->getSize(), request.getSize(),
response->getSize());
/* A request can become complete by several paths, this is a sanity
* check to make sure the packet's data is created */
if (!data) {
data = new uint8_t[request.getSize()];
}
if (isLoad) {
DPRINTFS(MinorMem, (&port), "Copying read data\n");
std::memcpy(packet->getPtr<uint8_t>(), data, request.getSize());
}
packet->makeResponse();
}
/* Packets are all deallocated together in ~SplitLSQRequest */
}
void
LSQ::SplitDataRequest::sendNextFragmentToTranslation()
{
unsigned int fragment_index = numTranslatedFragments;
ThreadContext *thread = port.cpu.getContext(
inst->id.threadId);
DPRINTFS(MinorMem, (&port), "Submitting DTLB request for fragment: %d\n",
fragment_index);
port.numAccessesInDTLB++;
numInTranslationFragments++;
thread->getDTBPtr()->translateTiming(
fragmentRequests[fragment_index], thread, this, (isLoad ?
BaseTLB::Read : BaseTLB::Write));
}
bool
LSQ::StoreBuffer::canInsert() const
{
/* @todo, support store amalgamation */
return slots.size() < numSlots;
}
void
LSQ::StoreBuffer::deleteRequest(LSQRequestPtr request)
{
auto found = std::find(slots.begin(), slots.end(), request);
if (found != slots.end()) {
DPRINTF(MinorMem, "Deleting request: %s %s %s from StoreBuffer\n",
request, *found, *(request->inst));
slots.erase(found);
delete request;
}
}
void
LSQ::StoreBuffer::insert(LSQRequestPtr request)
{
if (!canInsert()) {
warn("%s: store buffer insertion without space to insert from"
" inst: %s\n", name(), *(request->inst));
}
DPRINTF(MinorMem, "Pushing store: %s into store buffer\n", request);
numUnissuedAccesses++;
if (request->state != LSQRequest::Complete)
request->setState(LSQRequest::StoreInStoreBuffer);
slots.push_back(request);
/* Let's try and wake up the processor for the next cycle to step
* the store buffer */
lsq.cpu.wakeupOnEvent(Pipeline::ExecuteStageId);
}
LSQ::AddrRangeCoverage
LSQ::StoreBuffer::canForwardDataToLoad(LSQRequestPtr request,
unsigned int &found_slot)
{
unsigned int slot_index = slots.size() - 1;
auto i = slots.rbegin();
AddrRangeCoverage ret = NoAddrRangeCoverage;
/* Traverse the store buffer in reverse order (most to least recent)
* and try to find a slot whose address range overlaps this request */
while (ret == NoAddrRangeCoverage && i != slots.rend()) {
LSQRequestPtr slot = *i;
if (slot->packet) {
AddrRangeCoverage coverage = slot->containsAddrRangeOf(request);
if (coverage != NoAddrRangeCoverage) {
DPRINTF(MinorMem, "Forwarding: slot: %d result: %s thisAddr:"
" 0x%x thisSize: %d slotAddr: 0x%x slotSize: %d\n",
slot_index, coverage,
request->request.getPaddr(), request->request.getSize(),
slot->request.getPaddr(), slot->request.getSize());
found_slot = slot_index;
ret = coverage;
}
}
i++;
slot_index--;
}
return ret;
}
/** Fill the given packet with appropriate date from slot slot_number */
void
LSQ::StoreBuffer::forwardStoreData(LSQRequestPtr load,
unsigned int slot_number)
{
assert(slot_number < slots.size());
assert(load->packet);
assert(load->isLoad);
LSQRequestPtr store = slots[slot_number];
assert(store->packet);
assert(store->containsAddrRangeOf(load) == FullAddrRangeCoverage);
Addr load_addr = load->request.getPaddr();
Addr store_addr = store->request.getPaddr();
Addr addr_offset = load_addr - store_addr;
unsigned int load_size = load->request.getSize();
DPRINTF(MinorMem, "Forwarding %d bytes for addr: 0x%x from store buffer"
" slot: %d addr: 0x%x addressOffset: 0x%x\n",
load_size, load_addr, slot_number,
store_addr, addr_offset);
void *load_packet_data = load->packet->getPtr<void>();
void *store_packet_data = store->packet->getPtr<uint8_t>() + addr_offset;
std::memcpy(load_packet_data, store_packet_data, load_size);
}
void
LSQ::StoreBuffer::countIssuedStore(LSQRequestPtr request)
{
/* Barriers are accounted for as they are cleared from
* the queue, not after their transfers are complete */
if (!request->isBarrier())
numUnissuedAccesses--;
}
void
LSQ::StoreBuffer::step()
{
DPRINTF(MinorMem, "StoreBuffer step numUnissuedAccesses: %d\n",
numUnissuedAccesses);
if (numUnissuedAccesses != 0 && lsq.state == LSQ::MemoryRunning) {
/* Clear all the leading barriers */
while (!slots.empty() &&
slots.front()->isComplete() && slots.front()->isBarrier())
{
LSQRequestPtr barrier = slots.front();
DPRINTF(MinorMem, "Clearing barrier for inst: %s\n",
*(barrier->inst));
numUnissuedAccesses--;
lsq.clearMemBarrier(barrier->inst);
slots.pop_front();
delete barrier;
}
auto i = slots.begin();
bool issued = true;
unsigned int issue_count = 0;
/* Skip trying if the memory system is busy */
if (lsq.state == LSQ::MemoryNeedsRetry)
issued = false;
/* Try to issue all stores in order starting from the head
* of the queue. Responses are allowed to be retired
* out of order */
while (issued &&
issue_count < storeLimitPerCycle &&
lsq.canSendToMemorySystem() &&
i != slots.end())
{
LSQRequestPtr request = *i;
DPRINTF(MinorMem, "Considering request: %s, sentAllPackets: %d"
" state: %s\n",
*(request->inst), request->sentAllPackets(),
request->state);
if (request->isBarrier() && request->isComplete()) {
/* Give up at barriers */
issued = false;
} else if (!(request->state == LSQRequest::StoreBufferIssuing &&
request->sentAllPackets()))
{
DPRINTF(MinorMem, "Trying to send request: %s to memory"
" system\n", *(request->inst));
if (lsq.tryToSend(request)) {
countIssuedStore(request);
issue_count++;
} else {
/* Don't step on to the next store buffer entry if this
* one hasn't issued all its packets as the store
* buffer must still enforce ordering */
issued = false;
}
}
i++;
}
}
}
void
LSQ::completeMemBarrierInst(MinorDynInstPtr inst,
bool committed)
{
if (committed) {
/* Not already sent to the store buffer as a store request? */
if (!inst->inStoreBuffer) {
/* Insert an entry into the store buffer to tick off barriers
* until there are none in flight */
storeBuffer.insert(new BarrierDataRequest(*this, inst));
}
} else {
/* Clear the barrier anyway if it wasn't actually committed */
clearMemBarrier(inst);
}
}
void
LSQ::StoreBuffer::minorTrace() const
{
unsigned int size = slots.size();
unsigned int i = 0;
std::ostringstream os;
while (i < size) {
LSQRequestPtr request = slots[i];
request->reportData(os);
i++;
if (i < numSlots)
os << ',';
}
while (i < numSlots) {
os << '-';
i++;
if (i < numSlots)
os << ',';
}
MINORTRACE("addr=%s num_unissued_stores=%d\n", os.str(),
numUnissuedAccesses);
}
void
LSQ::tryToSendToTransfers(LSQRequestPtr request)
{
if (state == MemoryNeedsRetry) {
DPRINTF(MinorMem, "Request needs retry, not issuing to"
" memory until retry arrives\n");
return;
}
if (request->state == LSQRequest::InTranslation) {
DPRINTF(MinorMem, "Request still in translation, not issuing to"
" memory\n");
return;
}
assert(request->state == LSQRequest::Translated ||
request->state == LSQRequest::RequestIssuing ||
request->state == LSQRequest::Failed ||
request->state == LSQRequest::Complete);
if (requests.empty() || requests.front() != request) {
DPRINTF(MinorMem, "Request not at front of requests queue, can't"
" issue to memory\n");
return;
}
if (transfers.unreservedRemainingSpace() == 0) {
DPRINTF(MinorMem, "No space to insert request into transfers"
" queue\n");
return;
}
if (request->isComplete() || request->state == LSQRequest::Failed) {
DPRINTF(MinorMem, "Passing a %s transfer on to transfers"
" queue\n", (request->isComplete() ? "completed" : "failed"));
request->setState(LSQRequest::Complete);
request->setSkipped();
moveFromRequestsToTransfers(request);
return;
}
if (!execute.instIsRightStream(request->inst)) {
/* Wrong stream, try to abort the transfer but only do so if
* there are no packets in flight */
if (request->hasPacketsInMemSystem()) {
DPRINTF(MinorMem, "Request's inst. is from the wrong stream,"
" waiting for responses before aborting request\n");
} else {
DPRINTF(MinorMem, "Request's inst. is from the wrong stream,"
" aborting request\n");
request->setState(LSQRequest::Complete);
request->setSkipped();
moveFromRequestsToTransfers(request);
}
return;
}
if (request->fault != NoFault) {
if (request->inst->staticInst->isPrefetch()) {
DPRINTF(MinorMem, "Not signalling fault for faulting prefetch\n");
}
DPRINTF(MinorMem, "Moving faulting request into the transfers"
" queue\n");
request->setState(LSQRequest::Complete);
request->setSkipped();
moveFromRequestsToTransfers(request);
return;
}
bool is_load = request->isLoad;
bool is_llsc = request->request.isLLSC();
bool is_swap = request->request.isSwap();
bool bufferable = !(request->request.isUncacheable() ||
is_llsc || is_swap);
if (is_load) {
if (numStoresInTransfers != 0) {
DPRINTF(MinorMem, "Load request with stores still in transfers"
" queue, stalling\n");
return;
}
} else {
/* Store. Can it be sent to the store buffer? */
if (bufferable && !request->request.isMmappedIpr()) {
request->setState(LSQRequest::StoreToStoreBuffer);
moveFromRequestsToTransfers(request);
DPRINTF(MinorMem, "Moving store into transfers queue\n");
return;
}
}
/* Check if this is the head instruction (and so must be executable as
* its stream sequence number was checked above) for loads which must
* not be speculatively issued and stores which must be issued here */
if (!bufferable) {
if (!execute.instIsHeadInst(request->inst)) {
DPRINTF(MinorMem, "Memory access not the head inst., can't be"
" sure it can be performed, not issuing\n");
return;
}
unsigned int forwarding_slot = 0;
if (storeBuffer.canForwardDataToLoad(request, forwarding_slot) !=
NoAddrRangeCoverage)
{
DPRINTF(MinorMem, "Memory access can receive forwarded data"
" from the store buffer, need to wait for store buffer to"
" drain\n");
return;
}
}
/* True: submit this packet to the transfers queue to be sent to the
* memory system.
* False: skip the memory and push a packet for this request onto
* requests */
bool do_access = true;
if (!is_llsc) {
/* Check for match in the store buffer */
if (is_load) {
unsigned int forwarding_slot = 0;
AddrRangeCoverage forwarding_result =
storeBuffer.canForwardDataToLoad(request,
forwarding_slot);
switch (forwarding_result) {
case FullAddrRangeCoverage:
/* Forward data from the store buffer into this request and
* repurpose this request's packet into a response packet */
storeBuffer.forwardStoreData(request, forwarding_slot);
request->packet->makeResponse();
/* Just move between queues, no access */
do_access = false;
break;
case PartialAddrRangeCoverage:
DPRINTF(MinorMem, "Load partly satisfied by store buffer"
" data. Must wait for the store to complete\n");
return;
break;
case NoAddrRangeCoverage:
DPRINTF(MinorMem, "No forwardable data from store buffer\n");
/* Fall through to try access */
break;
}
}
} else {
if (!canSendToMemorySystem()) {
DPRINTF(MinorMem, "Can't send request to memory system yet\n");
return;
}
SimpleThread &thread = *cpu.threads[request->inst->id.threadId];
TheISA::PCState old_pc = thread.pcState();
ExecContext context(cpu, thread, execute, request->inst);
/* Handle LLSC requests and tests */
if (is_load) {
TheISA::handleLockedRead(&context, &request->request);
} else {
do_access = TheISA::handleLockedWrite(&context,
&request->request, cacheBlockMask);
if (!do_access) {
DPRINTF(MinorMem, "Not perfoming a memory "
"access for store conditional\n");
}
}
thread.pcState(old_pc);
}
/* See the do_access comment above */
if (do_access) {
if (!canSendToMemorySystem()) {
DPRINTF(MinorMem, "Can't send request to memory system yet\n");
return;
}
/* Remember if this is an access which can't be idly
* discarded by an interrupt */
if (!bufferable && !request->issuedToMemory) {
numAccessesIssuedToMemory++;
request->issuedToMemory = true;
}
if (tryToSend(request))
moveFromRequestsToTransfers(request);
} else {
request->setState(LSQRequest::Complete);
moveFromRequestsToTransfers(request);
}
}
bool
LSQ::tryToSend(LSQRequestPtr request)
{
bool ret = false;
if (!canSendToMemorySystem()) {
DPRINTF(MinorMem, "Can't send request: %s yet, no space in memory\n",
*(request->inst));
} else {
PacketPtr packet = request->getHeadPacket();
DPRINTF(MinorMem, "Trying to send request: %s addr: 0x%x\n",
*(request->inst), packet->req->getVaddr());
/* The sender state of the packet *must* be an LSQRequest
* so the response can be correctly handled */
assert(packet->findNextSenderState<LSQRequest>());
if (request->request.isMmappedIpr()) {
ThreadContext *thread =
cpu.getContext(request->request.threadId());
if (request->isLoad) {
DPRINTF(MinorMem, "IPR read inst: %s\n", *(request->inst));
TheISA::handleIprRead(thread, packet);
} else {
DPRINTF(MinorMem, "IPR write inst: %s\n", *(request->inst));
TheISA::handleIprWrite(thread, packet);
}
request->stepToNextPacket();
ret = request->sentAllPackets();
if (!ret) {
DPRINTF(MinorMem, "IPR access has another packet: %s\n",
*(request->inst));
}
if (ret)
request->setState(LSQRequest::Complete);
else
request->setState(LSQRequest::RequestIssuing);
} else if (dcachePort.sendTimingReq(packet)) {
DPRINTF(MinorMem, "Sent data memory request\n");
numAccessesInMemorySystem++;
request->stepToNextPacket();
ret = request->sentAllPackets();
switch (request->state) {
case LSQRequest::Translated:
case LSQRequest::RequestIssuing:
/* Fully or partially issued a request in the transfers
* queue */
request->setState(LSQRequest::RequestIssuing);
break;
case LSQRequest::StoreInStoreBuffer:
case LSQRequest::StoreBufferIssuing:
/* Fully or partially issued a request in the store
* buffer */
request->setState(LSQRequest::StoreBufferIssuing);
break;
default:
assert(false);
break;
}
state = MemoryRunning;
} else {
DPRINTF(MinorMem,
"Sending data memory request - needs retry\n");
/* Needs to be resent, wait for that */
state = MemoryNeedsRetry;
retryRequest = request;
switch (request->state) {
case LSQRequest::Translated:
case LSQRequest::RequestIssuing:
request->setState(LSQRequest::RequestNeedsRetry);
break;
case LSQRequest::StoreInStoreBuffer:
case LSQRequest::StoreBufferIssuing:
request->setState(LSQRequest::StoreBufferNeedsRetry);
break;
default:
assert(false);
break;
}
}
}
return ret;
}
void
LSQ::moveFromRequestsToTransfers(LSQRequestPtr request)
{
assert(!requests.empty() && requests.front() == request);
assert(transfers.unreservedRemainingSpace() != 0);
/* Need to count the number of stores in the transfers
* queue so that loads know when their store buffer forwarding
* results will be correct (only when all those stores
* have reached the store buffer) */
if (!request->isLoad)
numStoresInTransfers++;
requests.pop();
transfers.push(request);
}
bool
LSQ::canSendToMemorySystem()
{
return state == MemoryRunning &&
numAccessesInMemorySystem < inMemorySystemLimit;
}
bool
LSQ::recvTimingResp(PacketPtr response)
{
LSQRequestPtr request =
safe_cast<LSQRequestPtr>(response->popSenderState());
DPRINTF(MinorMem, "Received response packet inst: %s"
" addr: 0x%x cmd: %s\n",
*(request->inst), response->getAddr(),
response->cmd.toString());
numAccessesInMemorySystem--;
if (response->isError()) {
DPRINTF(MinorMem, "Received error response packet: %s\n",
*request->inst);
}
switch (request->state) {
case LSQRequest::RequestIssuing:
case LSQRequest::RequestNeedsRetry:
/* Response to a request from the transfers queue */
request->retireResponse(response);
DPRINTF(MinorMem, "Has outstanding packets?: %d %d\n",
request->hasPacketsInMemSystem(), request->isComplete());
break;
case LSQRequest::StoreBufferIssuing:
case LSQRequest::StoreBufferNeedsRetry:
/* Response to a request from the store buffer */
request->retireResponse(response);
/* Remove completed requests unless they are barriers (which will
* need to be removed in order */
if (request->isComplete()) {
if (!request->isBarrier()) {
storeBuffer.deleteRequest(request);
} else {
DPRINTF(MinorMem, "Completed transfer for barrier: %s"
" leaving the request as it is also a barrier\n",
*(request->inst));
}
}
break;
default:
/* Shouldn't be allowed to receive a response from another
* state */
assert(false);
break;
}
/* We go to idle even if there are more things in the requests queue
* as it's the job of step to actually step us on to the next
* transaction */
/* Let's try and wake up the processor for the next cycle */
cpu.wakeupOnEvent(Pipeline::ExecuteStageId);
/* Never busy */
return true;
}
void
LSQ::recvReqRetry()
{
DPRINTF(MinorMem, "Received retry request\n");
assert(state == MemoryNeedsRetry);
switch (retryRequest->state) {
case LSQRequest::RequestNeedsRetry:
/* Retry in the requests queue */
retryRequest->setState(LSQRequest::Translated);
break;
case LSQRequest::StoreBufferNeedsRetry:
/* Retry in the store buffer */
retryRequest->setState(LSQRequest::StoreInStoreBuffer);
break;
default:
assert(false);
}
/* Set state back to MemoryRunning so that the following
* tryToSend can actually send. Note that this won't
* allow another transfer in as tryToSend should
* issue a memory request and either succeed for this
* request or return the LSQ back to MemoryNeedsRetry */
state = MemoryRunning;
/* Try to resend the request */
if (tryToSend(retryRequest)) {
/* Successfully sent, need to move the request */
switch (retryRequest->state) {
case LSQRequest::RequestIssuing:
/* In the requests queue */
moveFromRequestsToTransfers(retryRequest);
break;
case LSQRequest::StoreBufferIssuing:
/* In the store buffer */
storeBuffer.countIssuedStore(retryRequest);
break;
default:
assert(false);
break;
}
retryRequest = NULL;
}
}
LSQ::LSQ(std::string name_, std::string dcache_port_name_,
MinorCPU &cpu_, Execute &execute_,
unsigned int in_memory_system_limit, unsigned int line_width,
unsigned int requests_queue_size, unsigned int transfers_queue_size,
unsigned int store_buffer_size,
unsigned int store_buffer_cycle_store_limit) :
Named(name_),
cpu(cpu_),
execute(execute_),
dcachePort(dcache_port_name_, *this, cpu_),
lastMemBarrier(0),
state(MemoryRunning),
inMemorySystemLimit(in_memory_system_limit),
lineWidth((line_width == 0 ? cpu.cacheLineSize() : line_width)),
requests(name_ + ".requests", "addr", requests_queue_size),
transfers(name_ + ".transfers", "addr", transfers_queue_size),
storeBuffer(name_ + ".storeBuffer",
*this, store_buffer_size, store_buffer_cycle_store_limit),
numAccessesInMemorySystem(0),
numAccessesInDTLB(0),
numStoresInTransfers(0),
numAccessesIssuedToMemory(0),
retryRequest(NULL),
cacheBlockMask(~(cpu_.cacheLineSize() - 1))
{
if (in_memory_system_limit < 1) {
fatal("%s: executeMaxAccessesInMemory must be >= 1 (%d)\n", name_,
in_memory_system_limit);
}
if (store_buffer_cycle_store_limit < 1) {
fatal("%s: executeLSQMaxStoreBufferStoresPerCycle must be"
" >= 1 (%d)\n", name_, store_buffer_cycle_store_limit);
}
if (requests_queue_size < 1) {
fatal("%s: executeLSQRequestsQueueSize must be"
" >= 1 (%d)\n", name_, requests_queue_size);
}
if (transfers_queue_size < 1) {
fatal("%s: executeLSQTransfersQueueSize must be"
" >= 1 (%d)\n", name_, transfers_queue_size);
}
if (store_buffer_size < 1) {
fatal("%s: executeLSQStoreBufferSize must be"
" >= 1 (%d)\n", name_, store_buffer_size);
}
if ((lineWidth & (lineWidth - 1)) != 0) {
fatal("%s: lineWidth: %d must be a power of 2\n", name(), lineWidth);
}
}
LSQ::~LSQ()
{ }
LSQ::LSQRequest::~LSQRequest()
{
if (packet)
delete packet;
if (data)
delete [] data;
}
/**
* Step the memory access mechanism on to its next state. In reality, most
* of the stepping is done by the callbacks on the LSQ but this
* function is responsible for issuing memory requests lodged in the
* requests queue.
*/
void
LSQ::step()
{
/* Try to move address-translated requests between queues and issue
* them */
if (!requests.empty())
tryToSendToTransfers(requests.front());
storeBuffer.step();
}
LSQ::LSQRequestPtr
LSQ::findResponse(MinorDynInstPtr inst)
{
LSQ::LSQRequestPtr ret = NULL;
if (!transfers.empty()) {
LSQRequestPtr request = transfers.front();
/* Same instruction and complete access or a store that's
* capable of being moved to the store buffer */
if (request->inst->id == inst->id) {
bool complete = request->isComplete();
bool can_store = storeBuffer.canInsert();
bool to_store_buffer = request->state ==
LSQRequest::StoreToStoreBuffer;
if ((complete && !(request->isBarrier() && !can_store)) ||
(to_store_buffer && can_store))
{
ret = request;
}
}
}
if (ret) {
DPRINTF(MinorMem, "Found matching memory response for inst: %s\n",
*inst);
} else {
DPRINTF(MinorMem, "No matching memory response for inst: %s\n",
*inst);
}
return ret;
}
void
LSQ::popResponse(LSQ::LSQRequestPtr response)
{
assert(!transfers.empty() && transfers.front() == response);
transfers.pop();
if (!response->isLoad)
numStoresInTransfers--;
if (response->issuedToMemory)
numAccessesIssuedToMemory--;
if (response->state != LSQRequest::StoreInStoreBuffer) {
DPRINTF(MinorMem, "Deleting %s request: %s\n",
(response->isLoad ? "load" : "store"),
*(response->inst));
delete response;
}
}
void
LSQ::sendStoreToStoreBuffer(LSQRequestPtr request)
{
assert(request->state == LSQRequest::StoreToStoreBuffer);
DPRINTF(MinorMem, "Sending store: %s to store buffer\n",
*(request->inst));
request->inst->inStoreBuffer = true;
storeBuffer.insert(request);
}
bool
LSQ::isDrained()
{
return requests.empty() && transfers.empty() &&
storeBuffer.isDrained();
}
bool
LSQ::needsToTick()
{
bool ret = false;
if (canSendToMemorySystem()) {
bool have_translated_requests = !requests.empty() &&
requests.front()->state != LSQRequest::InTranslation &&
transfers.unreservedRemainingSpace() != 0;
ret = have_translated_requests ||
storeBuffer.numUnissuedStores() != 0;
}
if (ret)
DPRINTF(Activity, "Need to tick\n");
return ret;
}
void
LSQ::pushRequest(MinorDynInstPtr inst, bool isLoad, uint8_t *data,
unsigned int size, Addr addr, unsigned int flags, uint64_t *res)
{
bool needs_burst = transferNeedsBurst(addr, size, lineWidth);
LSQRequestPtr request;
/* Copy given data into the request. The request will pass this to the
* packet and then it will own the data */
uint8_t *request_data = NULL;
DPRINTF(MinorMem, "Pushing request (%s) addr: 0x%x size: %d flags:"
" 0x%x%s lineWidth : 0x%x\n",
(isLoad ? "load" : "store"), addr, size, flags,
(needs_burst ? " (needs burst)" : ""), lineWidth);
if (!isLoad) {
/* request_data becomes the property of a ...DataRequest (see below)
* and destroyed by its destructor */
request_data = new uint8_t[size];
if (flags & Request::CACHE_BLOCK_ZERO) {
/* For cache zeroing, just use zeroed data */
std::memset(request_data, 0, size);
} else {
std::memcpy(request_data, data, size);
}
}
if (needs_burst) {
request = new SplitDataRequest(
*this, inst, isLoad, request_data, res);
} else {
request = new SingleDataRequest(
*this, inst, isLoad, request_data, res);
}
if (inst->traceData)
inst->traceData->setMem(addr, size, flags);
request->request.setThreadContext(cpu.cpuId(), /* thread id */ 0);
request->request.setVirt(0 /* asid */,
addr, size, flags, cpu.dataMasterId(),
/* I've no idea why we need the PC, but give it */
inst->pc.instAddr());
requests.push(request);
request->startAddrTranslation();
}
void
LSQ::pushFailedRequest(MinorDynInstPtr inst)
{
LSQRequestPtr request = new FailedDataRequest(*this, inst);
requests.push(request);
}
void
LSQ::minorTrace() const
{
MINORTRACE("state=%s in_tlb_mem=%d/%d stores_in_transfers=%d"
" lastMemBarrier=%d\n",
state, numAccessesInDTLB, numAccessesInMemorySystem,
numStoresInTransfers, lastMemBarrier);
requests.minorTrace();
transfers.minorTrace();
storeBuffer.minorTrace();
}
LSQ::StoreBuffer::StoreBuffer(std::string name_, LSQ &lsq_,
unsigned int store_buffer_size,
unsigned int store_limit_per_cycle) :
Named(name_), lsq(lsq_),
numSlots(store_buffer_size),
storeLimitPerCycle(store_limit_per_cycle),
slots(),
numUnissuedAccesses(0)
{
}
PacketPtr
makePacketForRequest(Request &request, bool isLoad,
Packet::SenderState *sender_state, PacketDataPtr data)
{
PacketPtr ret = isLoad ? Packet::createRead(&request)
: Packet::createWrite(&request);
if (sender_state)
ret->pushSenderState(sender_state);
if (isLoad)
ret->allocate();
else
ret->dataDynamic(data);
return ret;
}
void
LSQ::issuedMemBarrierInst(MinorDynInstPtr inst)
{
assert(inst->isInst() && inst->staticInst->isMemBarrier());
assert(inst->id.execSeqNum > lastMemBarrier);
/* Remember the barrier. We only have a notion of one
* barrier so this may result in some mem refs being
* delayed if they are between barriers */
lastMemBarrier = inst->id.execSeqNum;
}
void
LSQ::LSQRequest::makePacket()
{
/* Make the function idempotent */
if (packet)
return;
packet = makePacketForRequest(request, isLoad, this, data);
/* Null the ret data so we know not to deallocate it when the
* ret is destroyed. The data now belongs to the ret and
* the ret is responsible for its destruction */
data = NULL;
}
std::ostream &
operator <<(std::ostream &os, LSQ::MemoryState state)
{
switch (state) {
case LSQ::MemoryRunning:
os << "MemoryRunning";
break;
case LSQ::MemoryNeedsRetry:
os << "MemoryNeedsRetry";
break;
default:
os << "MemoryState-" << static_cast<int>(state);
break;
}
return os;
}
void
LSQ::recvTimingSnoopReq(PacketPtr pkt)
{
/* LLSC operations in Minor can't be speculative and are executed from
* the head of the requests queue. We shouldn't need to do more than
* this action on snoops. */
/* THREAD */
TheISA::handleLockedSnoop(cpu.getContext(0), pkt, cacheBlockMask);
}
}
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2018 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include <config/bitcoin-config.h>
#endif
#include <chainparams.h>
#include <clientversion.h>
#include <compat.h>
#include <fs.h>
#include <rpc/server.h>
#include <init.h>
#include <noui.h>
#include <shutdown.h>
#include <util.h>
#include <httpserver.h>
#include <httprpc.h>
#include <utilstrencodings.h>
#include <walletinitinterface.h>
#include <stdio.h>
/* Introduction text for doxygen: */
/*! \mainpage Developer documentation
*
* \section intro_sec Introduction
*
* This is the developer documentation of the reference client for an experimental new digital currency called Bitcoin,
* which enables instant payments to anyone, anywhere in the world. Bitcoin uses peer-to-peer technology to operate
* with no central authority: managing transactions and issuing money are carried out collectively by the network.
*
* The software is a community-driven open source project, released under the MIT license.
*
* See https://github.com/bitcoin/bitcoin and https://bitcoincore.org/ for further information about the project.
*
* \section Navigation
* Use the buttons <code>Namespaces</code>, <code>Classes</code> or <code>Files</code> at the top of the page to start navigating the code.
*/
static void WaitForShutdown()
{
while (!ShutdownRequested())
{
MilliSleep(200);
}
Interrupt();
}
//////////////////////////////////////////////////////////////////////////////
//
// Start
//
static bool AppInit(int argc, char* argv[])
{
bool fRet = false;
//
// Parameters
//
// If Qt is used, parameters/bitcoin.conf are parsed in qt/bitcoin.cpp's main()
SetupServerArgs();
std::string error;
if (!gArgs.ParseParameters(argc, argv, error)) {
fprintf(stderr, "Error parsing command line arguments: %s\n", error.c_str());
return false;
}
// Process help and version before taking care about datadir
if (HelpRequested(gArgs) || gArgs.IsArgSet("-version")) {
std::string strUsage = PACKAGE_NAME " Daemon version " + FormatFullVersion() + "\n";
if (gArgs.IsArgSet("-version"))
{
strUsage += FormatParagraph(LicenseInfo());
}
else
{
strUsage += "\nUsage: hanacoind [options] Start " PACKAGE_NAME " Daemon\n";
strUsage += "\n" + gArgs.GetHelpMessage();
}
fprintf(stdout, "%s", strUsage.c_str());
return true;
}
try
{
if (!fs::is_directory(GetDataDir(false)))
{
fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", gArgs.GetArg("-datadir", "").c_str());
return false;
}
if (!gArgs.ReadConfigFiles(error, true)) {
fprintf(stderr, "Error reading configuration file: %s\n", error.c_str());
return false;
}
// Check for -testnet or -regtest parameter (Params() calls are only valid after this clause)
try {
SelectParams(gArgs.GetChainName());
} catch (const std::exception& e) {
fprintf(stderr, "Error: %s\n", e.what());
return false;
}
// Error out when loose non-argument tokens are encountered on command line
for (int i = 1; i < argc; i++) {
if (!IsSwitchChar(argv[i][0])) {
fprintf(stderr, "Error: Command line contains unexpected token '%s', see hanacoind -h for a list of options.\n", argv[i]);
return false;
}
}
// -server defaults to true for bitcoind but not for the GUI so do this here
gArgs.SoftSetBoolArg("-server", true);
// Set this early so that parameter interactions go to console
InitLogging();
InitParameterInteraction();
if (!AppInitBasicSetup())
{
// InitError will have been called with detailed error, which ends up on console
return false;
}
if (!AppInitParameterInteraction())
{
// InitError will have been called with detailed error, which ends up on console
return false;
}
if (!AppInitSanityChecks())
{
// InitError will have been called with detailed error, which ends up on console
return false;
}
if (gArgs.GetBoolArg("-daemon", false))
{
#if HAVE_DECL_DAEMON
#if defined(MAC_OSX)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#endif
fprintf(stdout, "Hanacoin server starting\n");
// Daemonize
if (daemon(1, 0)) { // don't chdir (1), do close FDs (0)
fprintf(stderr, "Error: daemon() failed: %s\n", strerror(errno));
return false;
}
#if defined(MAC_OSX)
#pragma GCC diagnostic pop
#endif
#else
fprintf(stderr, "Error: -daemon is not supported on this operating system\n");
return false;
#endif // HAVE_DECL_DAEMON
}
// Lock data directory after daemonization
if (!AppInitLockDataDirectory())
{
// If locking the data directory failed, exit immediately
return false;
}
fRet = AppInitMain();
}
catch (const std::exception& e) {
PrintExceptionContinue(&e, "AppInit()");
} catch (...) {
PrintExceptionContinue(nullptr, "AppInit()");
}
if (!fRet)
{
Interrupt();
} else {
WaitForShutdown();
}
Shutdown();
return fRet;
}
int main(int argc, char* argv[])
{
SetupEnvironment();
// Connect bitcoind signal handlers
noui_connect();
return (AppInit(argc, argv) ? EXIT_SUCCESS : EXIT_FAILURE);
}
|
// Copyright by Contributors
#include <dmlc/base.h>
#include <dmlc/recordio.h>
#include <dmlc/logging.h>
#include <algorithm>
namespace DMLC {
// implementation
void RecordIOWriter::WriteRecord(const void *buf, size_t size) {
CHECK(size < (1 << 29U))
<< "RecordIO only accept record less than 2^29 bytes";
const uint32_t umagic = kMagic;
// initialize the magic number, in stack
const char *magic = reinterpret_cast<const char*>(&umagic);
const char *bhead = reinterpret_cast<const char*>(buf);
uint32_t len = static_cast<uint32_t>(size);
uint32_t lower_align = (len >> 2U) << 2U;
uint32_t upper_align = ((len + 3U) >> 2U) << 2U;
uint32_t dptr = 0;
for (uint32_t i = 0; i < lower_align ; i += 4) {
// use char check for alignment safety reason
if (bhead[i] == magic[0] &&
bhead[i + 1] == magic[1] &&
bhead[i + 2] == magic[2] &&
bhead[i + 3] == magic[3]) {
uint32_t lrec = EncodeLRec(dptr == 0 ? 1U : 2U,
i - dptr);
stream_->Write(magic, 4);
stream_->Write(&lrec, sizeof(lrec));
if (i != dptr) {
stream_->Write(bhead + dptr, i - dptr);
}
dptr = i + 4;
except_counter_ += 1;
}
}
uint32_t lrec = EncodeLRec(dptr != 0 ? 3U : 0U,
len - dptr);
stream_->Write(magic, 4);
stream_->Write(&lrec, sizeof(lrec));
if (len != dptr) {
stream_->Write(bhead + dptr, len - dptr);
}
// write padded bytes
uint32_t zero = 0;
if (upper_align != len) {
stream_->Write(&zero, upper_align - len);
}
}
bool RecordIOReader::NextRecord(std::string *out_rec) {
if (end_of_stream_) return false;
const uint32_t kMagic = RecordIOWriter::kMagic;
out_rec->clear();
size_t size = 0;
while (true) {
uint32_t header[2];
size_t nread = stream_->Read(header, sizeof(header));
if (nread == 0) {
end_of_stream_ = true; return false;
}
CHECK(nread == sizeof(header)) << "Inavlid RecordIO File";
CHECK(header[0] == RecordIOWriter::kMagic) << "Invalid RecordIO File";
uint32_t cflag = RecordIOWriter::DecodeFlag(header[1]);
uint32_t len = RecordIOWriter::DecodeLength(header[1]);
uint32_t upper_align = ((len + 3U) >> 2U) << 2U;
out_rec->resize(size + upper_align);
if (upper_align != 0) {
CHECK(stream_->Read(BeginPtr(*out_rec) + size, upper_align) == upper_align)
<< "Invalid RecordIO File upper_align=" << upper_align;
}
// squeeze back
size += len; out_rec->resize(size);
if (cflag == 0U || cflag == 3U) break;
out_rec->resize(size + sizeof(kMagic));
std::memcpy(BeginPtr(*out_rec) + size, &kMagic, sizeof(kMagic));
size += sizeof(kMagic);
}
return true;
}
// helper function to find next recordio head
inline char *FindNextRecordIOHead(char *begin, char *end) {
CHECK_EQ((reinterpret_cast<size_t>(begin) & 3UL), 0U);
CHECK_EQ((reinterpret_cast<size_t>(end) & 3UL), 0U);
uint32_t *p = reinterpret_cast<uint32_t *>(begin);
uint32_t *pend = reinterpret_cast<uint32_t *>(end);
for (; p + 1 < pend; ++p) {
if (p[0] == RecordIOWriter::kMagic) {
uint32_t cflag = RecordIOWriter::DecodeFlag(p[1]);
if (cflag == 0 || cflag == 1) {
return reinterpret_cast<char*>(p);
}
}
}
return end;
}
RecordIOChunkReader::RecordIOChunkReader(InputSplit::Blob chunk,
unsigned part_index,
unsigned num_parts) {
size_t nstep = (chunk.size + num_parts - 1) / num_parts;
// align
nstep = ((nstep + 3UL) >> 2UL) << 2UL;
size_t begin = std::min(chunk.size, nstep * part_index);
size_t end = std::min(chunk.size, nstep * (part_index + 1));
char *head = reinterpret_cast<char*>(chunk.dptr);
pbegin_ = FindNextRecordIOHead(head + begin, head + chunk.size);
pend_ = FindNextRecordIOHead(head + end, head + chunk.size);
}
bool RecordIOChunkReader::NextRecord(InputSplit::Blob *out_rec) {
if (pbegin_ >= pend_) return false;
uint32_t *p = reinterpret_cast<uint32_t *>(pbegin_);
CHECK(p[0] == RecordIOWriter::kMagic);
uint32_t cflag = RecordIOWriter::DecodeFlag(p[1]);
uint32_t clen = RecordIOWriter::DecodeLength(p[1]);
if (cflag == 0) {
// skip header
out_rec->dptr = pbegin_ + 2 * sizeof(uint32_t);
// move pbegin
pbegin_ += 2 * sizeof(uint32_t) + (((clen + 3U) >> 2U) << 2U);
CHECK(pbegin_ <= pend_) << "Invalid RecordIO Format";
out_rec->size = clen;
return true;
} else {
const uint32_t kMagic = RecordIOWriter::kMagic;
// abnormal path, read into string
CHECK(cflag == 1U) << "Invalid RecordIO Format";
temp_.resize(0);
while (true) {
CHECK(pbegin_ + 2 * sizeof(uint32_t) <= pend_);
p = reinterpret_cast<uint32_t *>(pbegin_);
CHECK(p[0] == RecordIOWriter::kMagic);
cflag = RecordIOWriter::DecodeFlag(p[1]);
clen = RecordIOWriter::DecodeLength(p[1]);
size_t tsize = temp_.length();
temp_.resize(tsize + clen);
if (clen != 0) {
std::memcpy(BeginPtr(temp_) + tsize,
pbegin_ + 2 * sizeof(uint32_t),
clen);
tsize += clen;
}
pbegin_ += 2 * sizeof(uint32_t) + (((clen + 3U) >> 2U) << 2U);
if (cflag == 3U) break;
temp_.resize(tsize + sizeof(kMagic));
std::memcpy(BeginPtr(temp_) + tsize, &kMagic, sizeof(kMagic));
}
out_rec->dptr = BeginPtr(temp_);
out_rec->size = temp_.length();
return true;
}
}
} // namespace DMLC
|
//
// Copyright © 2017 Arm Ltd. All rights reserved.
// See LICENSE file in the project root for full license information.
//
#pragma once
#include "LayerWithParameters.hpp"
namespace armnn
{
class Pooling2dLayer : public LayerWithParameters<Pooling2dDescriptor>
{
public:
virtual std::unique_ptr<IWorkload> CreateWorkload(const Graph& graph,
const IWorkloadFactory& factory) const override;
Pooling2dLayer* Clone(Graph& graph) const override;
void ValidateTensorShapesFromInputs() override;
protected:
Pooling2dLayer(const Pooling2dDescriptor& param, const char* name);
~Pooling2dLayer() = default;
};
} // namespace
|
#ifndef _COVERTREE_HH_
#define _COVERTREE_HH_
/** \file
Implementation of the Cover Tree algorithm.
http://hunch.net/~jl/projects/cover_tree/cover_tree.html */
#include <algorithm>
#include <cmath>
#include <iterator>
#include <limits>
#include <map>
#include <utility>
#include <vector>
/** Container for data of type T that supports searches for nearest
neighbors, using a distance function object of type Metric. */
template <class T, class Metric>
class CoverTree {
protected:
/** Representation of an individual instance. */
struct Node {
/** Each child node has an associated level at which it first
appears. */
typedef std::pair<int, Node> Child;
/** Each node can have an unbounded number of children. */
typedef std::vector<Child> ChildContainer;
/** Comparator for sorting the children by depth. */
struct Compare: public std::binary_function<Child, Child, bool> {
bool operator()(const Child &a, const Child &b) const {
return a.first > b.first;
}
};
/** Construct a new Node with no children.
\param x The instance the node will contain. */
Node(const T &x): x(x) {}
T x;
ChildContainer children;
};
/** Object that tracks the iteration through a Node's list of
children. Some cover tree operations must iterate through
several Node's children simultaneously. */
struct LinkData {
/** Comparator that compares LinkData objects by the level of each
one's current Node. The current node at the front of a
priority queue using this comparator will have the highest
level among all nodes in the priority queue. */
struct Compare: public std::binary_function<LinkData,LinkData,bool> {
bool operator()(const LinkData &a, const LinkData &b) const {
return a.level() < b.level();
}
};
/** Construct a new LinkData iteration.
\param node The node through whose children to iterate.
\param d A distance from node->x that governs how long the
iteration is relevant to a particular query or
operation. */
LinkData(Node *node, double d):
it(node->children.begin()), end(node->children.end()), d(d) {}
/** The first level at which the current node in this iteration
appears. */
int level() const {
return it->first;
}
/** Whether any of the remaining nodes in this iteration is
relevant to an instance at distance (d + margin) from the node
that originated this LinkData. */
bool relevant(double margin = 0) const {
return it != end && d < margin + std::ldexp(1., level() + 1);
}
typename Node::ChildContainer::iterator it;
typename Node::ChildContainer::iterator end;
double d;
};
public:
/** \param duplicate Whether to add an instance that is at distance
0 from an existing instance. */
CoverTree(bool duplicate = false):
root(NULL), duplicate(duplicate)
{}
/** \param d The distance metric to use.
\param duplicate Whether to add an instance that is at distance
0 from an existing instance. */
CoverTree(const Metric &d, bool duplicate = false):
root(NULL), d(d), duplicate(duplicate)
{}
/** Copy constructor. Assumes that T and Metric are copyable. */
CoverTree(const CoverTree &other):
root(new Node(*other.root)),
d(other.d),
duplicate(other.duplicate)
{}
~CoverTree() {
delete root;
}
/** Assignment operator. Assumes that T and Metric are assignable. */
CoverTree &operator=(const CoverTree &other) {
delete root;
root = new Node(other->root);
d = other.d;
duplicate = other.duplicate;
}
/** Inserts a new point into the cover tree
\param x The point to insert
\return The inserted instance, or if this CoverTree does not
insert duplicates, an existing instance at distance 0
from x */
const T &insert(const T &x) {
return insert_node(x)->x;
}
/** Removes one point, if it exists. Assumes that T can be tested
for equality.
\return True if a point was removed */
bool remove(const T &x) {
if (root == NULL)
return false;
if (root->x == x) {
Node *old = root;
root = NULL;
move_children(*old); // Reinsert all descendents into tree.
delete old;
return true;
}
return remove_recursive(x, *root);
}
/** Find the k nearest neighbors (and their distances).
\param out An output iterator into which to write the results.
The value_type of this iterator must be
std::pair<double, T>.
\param x The instance whose neighbors to find
\param k The number of neighbors to find.
\return The output iterator incremented (and written) up to k
times. The nearest instance will be written first. */
template <class OutputIterator>
OutputIterator nearest(OutputIterator out, const T &x, unsigned k) {
if (root != NULL) {
// The k nearest instances found so far, initialized to the
// root, along with their distances from x.
std::vector<std::pair<double, Node *> > nearest;
nearest.reserve(k);
nearest.push_back(std::make_pair(d(x, root->x), root));
// A priority queue of iterators through all the nodes relevant
// to this search, initialized to the first child of the root.
std::vector<LinkData> pqueue;
LinkData front = LinkData(nearest.front().second, nearest.front().first);
pqueue.push_back(front);
typename LinkData::Compare cmp;
// Traverse the cover tree by order of level, pruning branches
// that are too far from x to be a nearest neighbor.
while (!pqueue.empty()) {
const int level = pqueue.front().level();
// If a node is farther away from x than this threshold, then
// none of its children can be one of the k nearest neighbors.
const double threshold =
nearest.back().first + std::ldexp(1., level + 1);
// Search one entire level at a time.
while (!pqueue.empty() && pqueue.front().level() == level) {
front = pqueue.front();
std::pop_heap(pqueue.begin(), pqueue.end(), cmp);
pqueue.pop_back();
// Look at all of this LinkData's children that joined the
// tree at this level.
while (front.it != front.end && front.level() == level) {
if (front.d < threshold) {
// The current child may be a nearest neighbor or an
// ancestor of one.
Node *node = &front.it->second;
const double dist = d(x, node->x);
// If this node is nearer than the last node in nearest (or
// if nearest is not yet at k instances), then add it to
// our results.
if (dist < nearest.back().first || nearest.size() < k) {
while (nearest.size() >= k)
nearest.pop_back();
std::pair<double, Node *> val = std::make_pair(dist,node);
nearest.insert(std::lower_bound(nearest.begin(),
nearest.end(),
val),
val);
}
// Try adding the children of this node to the queue.
LinkData child = LinkData(node, dist);
if (child.relevant(nearest.back().first)) {
pqueue.push_back(child);
std::push_heap(pqueue.begin(), pqueue.end(), cmp);
}
}
++front.it;
}
// The level of the next child in this LinkData has
// decreased. See if it's still relevant to our search.
if (front.relevant(nearest.back().first)) {
pqueue.push_back(front);
std::push_heap(pqueue.begin(), pqueue.end(), cmp);
}
}
}
// Output the results.
typename std::vector<std::pair<double, Node *> >::const_iterator it;
for (it = nearest.begin(); it != nearest.end(); ++it)
*out++ = std::make_pair(it->first, it->second->x);
}
return out;
}
/** Find all instances within a certain radius.
\param out An output iterator into which to write the results.
The value_type of this iterator must be
std::pair<double, T>.
\param x The instance whose neighbors to find
\param margin The search radius.
\return The output iterator incremented (and written) once for
each instance with the search radius. The instances are
not written in any guaranteed order. */
template <class OutputIterator>
OutputIterator neighbors(OutputIterator out,
const T &x,
double margin) const
{
if (root != NULL)
out = recursive_neighbors(out, x, margin, *root);
return out;
}
/** Output all the instances in the cover tree.
\param out An output iterator into which to write the results.
The value_type of this iterator must be T. */
template <class OutputIterator>
OutputIterator contents(OutputIterator out) const {
return recursive_contents(out, *root);
}
/** Write the tree structure to an output stream. Each line of the
output will contain three tab-separated entries, describing a
link in the tree. The first entry is the level at which the
link occurs. The second and third entries give the parent and
child instance values, respectively. This method therefore
outputs n - 1 lines, where n is the number of instances. It
assumes that operator<< is defined for T. */
void print(std::ostream &out) const {
if (root != NULL) {
print(out, root);
}
}
/** Remove all instances from the tree. */
void clear() {
delete root;
root = NULL;
}
protected:
/** Inserts a new point into the cover tree
\param x The point to insert */
Node *insert_node(const T &x) {
Node *retval;
if (root == NULL) {
root = new Node(x);
retval = root;
} else {
// Keep track of closest valid parent instance for x, as well as
// its distance from x.
double min = d(x, root->x);
Node *parent = root;
// Search the tree by iterating through each node's children, in
// order of level, while each child list contains instances that
// may be the closest node (and are therefore relevant).
std::vector<LinkData> pqueue; // x.relevant() for all x in pqueue
const LinkData rootdata(parent, min);
int level;
if (rootdata.relevant()) {
level = rootdata.level();
pqueue.push_back(rootdata);
}
typename LinkData::Compare cmp;
// Look for the first level such that x is very far from every
// point at that level, while also tracking the closest covering
// point
while (!pqueue.empty() && min < std::ldexp(1., level + 1) && min > 0) {
level = pqueue.front().level();
// Search one full level at atime.
while (!pqueue.empty() && pqueue.front().level() == level) {
LinkData current = pqueue.front();
std::pop_heap(pqueue.begin(), pqueue.end(), cmp);
pqueue.pop_back();
// Check all children in this LinkData that join the tree at
// this level.
while (current.it != current.end && current.level() == level) {
Node *node = ¤t.it->second;
const double dist = d(x, node->x);
if (min > dist && dist < std::ldexp(1., level - 1)) {
// This node is now the closest valid parent so far.
min = dist;
parent = node;
}
// Add this node's children to the queue, if relevant.
LinkData child(node, dist);
if (child.relevant()) {
pqueue.push_back(child);
std::push_heap(pqueue.begin(), pqueue.end(), cmp);
}
++current.it;
}
// Add the remaining children of this LinkData back to the
// queue, if relevant.
if (current.relevant()) {
pqueue.push_back(current);
std::push_heap(pqueue.begin(), pqueue.end(), cmp);
}
}
}
if (min > 0 || duplicate) {
// Insert x if it has positive distance from all existing
// instances or if we allow duplicates.
if (min > 0)
std::frexp(min, &level); // Level at which x joins the tree
else
level = std::numeric_limits<int>::min(); // For duplicates
typename Node::Child val(level, Node(x));
typename Node::ChildContainer::iterator pos =
std::lower_bound(parent->children.begin(), parent->children.end(),
val, typename Node::Compare());
pos = parent->children.insert(pos, val);
retval = &pos->second;
} else
retval = parent;
}
return retval;
}
/** Add back to the tree the children of a just-deleted node. */
void move_children(Node &parent) {
typename Node::ChildContainer::iterator it = parent.children.begin();
while (it != parent.children.end()) {
Node &child = it->second;
insert_node(child.x);
move_children(child);
++it;
}
}
/** Remove an instance from a subtree.
\param x The instance to remove
\param node The root of the subtree to search.
\return Whether x was a descendant of node (and was removed) */
bool remove_recursive(const T &x, Node &node) {
const double dist = d(x, node.x);
typename Node::ChildContainer::iterator it = node.children.begin();
if (dist == 0) {
// We assume node.x != x, so x must be a direct child of this node.
while (it != node.children.end()) {
if (it->second.x == x) {
node.children.erase(it);
return true;
}
++it;
}
return false;
}
// Check the children of this node, and recurse if the children are
// close enough to contain x.
while (it != node.children.end() && dist < std::ldexp(1, 1 + it->first)) {
Node &child = it->second;
if (x == child.x) {
Node copy(x); // x is just a convenient value, we won't be keeping this
copy.children.swap(child.children);
node.children.erase(it); // child ref now invalid!
move_children(copy);
return true;
}
if (remove_recursive(x, child))
return true;
++it;
}
return false;
}
template <class OutputIterator>
OutputIterator recursive_neighbors(OutputIterator out,
const T &x,
double margin,
const Node &node) const
{
const double dist = d(x, node.x);
if (dist < margin)
*out++ = std::make_pair(dist, node.x);
typename Node::ChildContainer::const_iterator it = node.children.begin();
while (it != node.children.end()
&& dist < margin + std::ldexp(1., 1 + it->first)) {
out = recursive_neighbors(out, x, margin, it->second);
++it;
}
return out;
}
template <class OutputIterator>
OutputIterator recursive_contents(OutputIterator out, const Node &node) const{
*out++ = node.x;
typename Node::ChildContainer::const_iterator it = node.children.begin();
while (it != node.children.end()) {
out = recursive_contents(out, it->second);
++it;
}
return out;
}
static void print(std::ostream &out, const Node *node) {
typename Node::ChildContainer::const_iterator it = node->children.begin();
while (it != node->children.end()) {
out << it->first << "\t"
<< node->x << "\t"
<< it->second.x << "\n";
print(out, it->second);
++it;
}
}
private:
Node *root;
Metric d;
bool duplicate;
};
#endif
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
#include "WsRequestClientImpl.h"
namespace Huobi {
void WsRequestClientImpl::requestCandlestickEvent(
const char* symbols,
CandlestickInterval interval,
const std::function<void(const std::vector<CandlestickEvent>&) >& callback,
const std::function<void(HuobiApiException&)>& errorHandler) {
requestCandlestickEvent(true, symbols, interval, 0, 0, callback, errorHandler);
}
void WsRequestClientImpl::requestCandlestickEvent(
bool autoClose,
const char* symbols,
CandlestickInterval interval,
const std::function<void(const std::vector<CandlestickEvent>&) >& callback,
const std::function<void(HuobiApiException&)>& errorHandler) {
requestCandlestickEvent(autoClose, symbols, interval, 0, 0, callback, errorHandler);
}
void WsRequestClientImpl::requestCandlestickEvent(
const char* symbols,
CandlestickInterval interval,
long startTime,
long endTime,
const std::function<void(const std::vector<CandlestickEvent>&) >& callback,
const std::function<void(HuobiApiException&)>& errorHandler) {
requestCandlestickEvent(true, symbols, interval, startTime, endTime, callback, errorHandler);
}
void WsRequestClientImpl::requestCandlestickEvent(
bool autoClose,
const char* symbols,
CandlestickInterval interval,
long startTime,
long endTime,
const std::function<void(const std::vector<CandlestickEvent>&) >& callback,
const std::function<void(HuobiApiException&)>& errorHandler) {
//WebSocketRequest* req = impl->requestCandlestickEvent(autoClose, symbols, interval, startTime, endTime, callback, errorHandler);
impl->requestCandlestickEvent(autoClose, symbols, interval, startTime, endTime, callback, errorHandler);
}
void WsRequestClientImpl::requestPriceDepthEvent(
const char* symbols,
DepthStep step,
const std::function<void(const PriceDepthEvent&) >& callback,
const std::function<void(HuobiApiException&)>& errorHandler) {
requestPriceDepthEvent(true, symbols, step, callback, errorHandler);
}
void WsRequestClientImpl::requestPriceDepthEvent(
bool autoClose,
const char* symbols,
DepthStep step,
const std::function<void(const PriceDepthEvent&) >& callback,
const std::function<void(HuobiApiException&)>& errorHandler) {
WebSocketRequest* req = impl->requestPriceDepthEvent(autoClose, symbols, step, callback, errorHandler);
impl->startReq(req);
}
void WsRequestClientImpl::requestPriceDepthEvent(
const char* symbols,
const std::function<void(const PriceDepthEvent&) >& callback,
const std::function<void(HuobiApiException&)>& errorHandler) {
requestPriceDepthEvent(true, symbols, DepthStep::step0, callback, errorHandler);
}
void WsRequestClientImpl::requestPriceDepthEvent(
bool autoClose,
const char* symbols,
const std::function<void(const PriceDepthEvent&) >& callback,
const std::function<void(HuobiApiException&)>& errorHandler) {
requestPriceDepthEvent(autoClose, symbols, DepthStep::step0, callback, errorHandler);
}
void WsRequestClientImpl::requestTradeEvent(
const char* symbols,
const std::function<void(const TradeEvent&) >& callback,
const std::function<void(HuobiApiException&)>& errorHandler) {
requestTradeEvent(true, symbols, callback, errorHandler);
}
void WsRequestClientImpl::requestTradeEvent(
bool autoClose,
const char* symbols,
const std::function<void(const TradeEvent&) >& callback,
const std::function<void(HuobiApiException&)>& errorHandler) {
WebSocketRequest* req = impl->requestTradeEvent(autoClose, symbols, callback, errorHandler);
impl->startReq(req);
}
void WsRequestClientImpl::request24HTradeStatistics(
const char* symbols,
const std::function<void(const TradeStatisticsEvent&) >& callback,
const std::function<void(HuobiApiException&)>& errorHandler) {
request24HTradeStatistics(true, symbols, callback, errorHandler);
}
void WsRequestClientImpl::request24HTradeStatistics(
bool autoClose,
const char* symbols,
const std::function<void(const TradeStatisticsEvent&) >& callback,
const std::function<void(HuobiApiException&)>& errorHandler) {
WebSocketRequest* req = impl->request24HTradeStatisticsEvent(autoClose, symbols, callback, errorHandler);
impl->startReq(req);
}
void WsRequestClientImpl::requestAccountList(
const std::function<void(const AccountListEvent&) >& callback,
const std::function<void(HuobiApiException&)>& errorHandler) {
requestAccountList(true, callback, errorHandler);
}
void WsRequestClientImpl::requestAccountList(
bool autoClose,
const std::function<void(const AccountListEvent&) >& callback,
const std::function<void(HuobiApiException&)>& errorHandler) {
WebSocketRequest* req = impl->requestAccountList(autoClose, callback, errorHandler);
impl->startReq(req);
}
void WsRequestClientImpl::requestOrdertListEvent(
bool autoClose,
OrderListEventRequest req,
const std::function<void(const OrderListEvent&) >& callback,
const std::function<void(HuobiApiException&)>& errorHandler) {
WebSocketRequest* request = impl->requestOrdertListEvent(autoClose, req, callback, errorHandler);
impl->startReq(request);
}
void WsRequestClientImpl::requestOrdertListEvent(
OrderListEventRequest req,
const std::function<void(const OrderListEvent&) >& callback,
const std::function<void(HuobiApiException&)>& errorHandler) {
requestOrdertListEvent(true, req, callback, errorHandler);
}
void WsRequestClientImpl::requestOrdertDetailEvent(
long orderId,
const std::function<void(const OrderDetailEvent&) >& callback,
const std::function<void(HuobiApiException&)>& errorHandler) {
requestOrdertDetailEvent(true, orderId, callback, errorHandler);
}
void WsRequestClientImpl::requestOrdertDetailEvent(
bool autoClose,
long orderId,
const std::function<void(const OrderDetailEvent&) >& callback,
const std::function<void(HuobiApiException&)>& errorHandler) {
WebSocketRequest* request = impl->requestOrdertDetailEvent(autoClose, orderId, callback, errorHandler);
impl->startReq(request);
}
void WsRequestClientImpl::requestMarketDepthMBPEvent(
const char* symbols,
MBPLevel level,
const std::function<void(const MarketDepthMBPEvent&) >& callback,
const std::function<void(HuobiApiException&)>& errorHandler) {
requestMarketDepthMBPEvent(true, symbols, level, callback, errorHandler);
}
void WsRequestClientImpl::requestMarketDepthMBPEvent(
bool autoClose,
const char* symbols,
MBPLevel level,
const std::function<void(const MarketDepthMBPEvent&) >& callback,
const std::function<void(HuobiApiException&)>& errorHandler) {
WebSocketRequest* request = impl->requestMarketDepthMBPEvent(autoClose, symbols, level, callback, errorHandler);
impl->startReq(request);
}
}
|
/**
* @file missing_policy.hpp
* @author Keon Kim
*
* Missing map policy for dataset info.
*/
#ifndef MLPACK_CORE_DATA_MAP_POLICIES_MISSING_POLICY_HPP
#define MLPACK_CORE_DATA_MAP_POLICIES_MISSING_POLICY_HPP
#include <mlpack/core.hpp>
#include <unordered_map>
#include <boost/bimap.hpp>
#include <mlpack/core/data/map_policies/datatype.hpp>
#include <limits>
namespace mlpack {
namespace data {
/**
* MissingPolicy is used as a helper class for DatasetMapper. It tells how the
* strings should be mapped. Purpose of this policy is to map all user-defined
* missing variables into maps so that users can decide what to do with the
* corrupted data. User-defined missing variables are given by the missingSet.
* Note that MissingPolicy does not change type of features.
*/
class MissingPolicy
{
public:
// typedef of MappedType
using MappedType = double;
MissingPolicy()
{
// Nothing to initialize here.
}
/**
* Create the MissingPolicy object with the given missingSet. Note that the
* missingSet cannot be changed later; you will have to create a new
* MissingPolicy object.
*
* @param missingSet Set of strings that should be mapped.
*/
explicit MissingPolicy(std::set<std::string> missingSet) :
missingSet(std::move(missingSet))
{
// Nothing to initialize here.
}
/**
* Given the string and the dimension to which it belongs by the user, and
* the maps and types given by the DatasetMapper class, returns its numeric
* mapping. If no mapping yet exists and the string is included in the
* missingSet, the string is added to the list of mappings for the given
* dimension. This function is used as a helper function for DatasetMapper
* class.
*
* @tparam MapType Type of unordered_map that contains mapped value pairs
* @param string String to find/create mapping for.
* @param dimension Index of the dimension of the string.
* @param maps Unordered map given by the DatasetMapper.
* @param types Vector containing the type information about each dimensions.
*/
template <typename MapType>
MappedType MapString(const std::string& string,
const size_t dimension,
MapType& maps,
std::vector<Datatype>& types)
{
// mute the unused parameter warning (does nothing here.)
(void)types;
// If this condition is true, either we have no mapping for the given string
// or we have no mappings for the given dimension at all. In either case,
// we create a mapping.
const double NaN = std::numeric_limits<double>::quiet_NaN();
if (missingSet.count(string) != 0 &&
(maps.count(dimension) == 0 ||
maps[dimension].first.left.count(string) == 0))
{
// This string does not exist yet.
typedef boost::bimap<std::string, MappedType>::value_type PairType;
maps[dimension].first.insert(PairType(string, NaN));
size_t& numMappings = maps[dimension].second;
++numMappings;
return NaN;
}
else
{
// This string already exists in the mapping
// or not included in missingSet.
// Unlike IncrementPolicy, MissingPolicy counts all mapped values.
size_t& numMappings = maps[dimension].second;
++numMappings;
return NaN;
}
}
/**
* MapTokens turns vector of strings into numeric variables and puts them
* into a given matrix. It is used as a helper function when trying to load
* files. Each dimension's tokens are given in to this function. If one of the
* tokens turns out to be a string or one of the missingSet's variables, only
* the token responsible for it should be mapped using the MapString()
* funciton.
*
* @tparam eT Type of armadillo matrix.
* @tparam MapType Type of unordered_map that contains mapped value pairs.
* @param tokens Vector of variables inside a dimension.
* @param row Position of the given tokens.
* @param matrix Matrix to save the data into.
* @param maps Maps given by the DatasetMapper class.
* @param types Types of each dimensions given by the DatasetMapper class.
*/
template <typename eT, typename MapType>
void MapTokens(const std::vector<std::string>& tokens,
size_t& row,
arma::Mat<eT>& matrix,
MapType& maps,
std::vector<Datatype>& types)
{
// MissingPolicy allows double type matrix only, because it uses NaN.
static_assert(std::is_same<eT, double>::value, "You must use double type "
" matrix in order to apply MissingPolicy");
std::stringstream token;
for (size_t i = 0; i != tokens.size(); ++i)
{
token.str(tokens[i]);
token>>matrix.at(row, i);
// if the token is not number, map it.
// or if token is a number, but is included in the missingSet, map it.
if (token.fail() || missingSet.find(tokens[i]) != std::end(missingSet))
{
const eT val = static_cast<eT>(this->MapString(tokens[i], row, maps,
types));
matrix.at(row, i) = val;
}
token.clear();
}
}
private:
// Note that missingSet and maps are different.
// missingSet specifies which value/string should be mapped.
std::set<std::string> missingSet;
}; // class MissingPolicy
} // namespace data
} // namespace mlpack
#endif
|
/*
Copyright(c) 2016-2020 Panos Karabelas
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.
*/
//= IMPLEMENTATION ===============
#ifdef API_GRAPHICS_VULKAN
#include "../RHI_Implementation.h"
//================================
//= INCLUDES ========================
#include "../RHI_Pipeline.h"
#include "../RHI_Device.h"
#include "../RHI_Shader.h"
#include "../RHI_BlendState.h"
#include "../RHI_InputLayout.h"
#include "../RHI_CommandList.h"
#include "../RHI_DescriptorCache.h"
#include "../RHI_PipelineState.h"
#include "../RHI_RasterizerState.h"
#include "../RHI_DepthStencilState.h"
#include "../../Logging/Log.h"
//===================================
//= NAMESPACES =====
using namespace std;
//==================
namespace Spartan
{
RHI_Pipeline::RHI_Pipeline(const RHI_Device* rhi_device, RHI_PipelineState& pipeline_state, void* descriptor_set_layout)
{
m_rhi_device = rhi_device;
m_state = pipeline_state;
m_state.CreateFrameResources(rhi_device);
// Viewport & Scissor
vector<VkDynamicState> dynamic_states;
VkPipelineDynamicStateCreateInfo dynamic_state = {};
VkViewport vkViewport = {};
VkRect2D scissor = {};
VkPipelineViewportStateCreateInfo viewport_state = {};
{
// If no viewport has been provided, assume dynamic
if (!m_state.viewport.IsDefined())
{
dynamic_states.emplace_back(VK_DYNAMIC_STATE_VIEWPORT);
}
if (m_state.dynamic_scissor)
{
dynamic_states.emplace_back(VK_DYNAMIC_STATE_SCISSOR);
}
// Dynamic states
dynamic_state.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
dynamic_state.pNext = nullptr;
dynamic_state.flags = 0;
dynamic_state.dynamicStateCount = static_cast<uint32_t>(dynamic_states.size());
dynamic_state.pDynamicStates = dynamic_states.data();
// Viewport
vkViewport.x = m_state.viewport.x;
vkViewport.y = m_state.viewport.y;
vkViewport.width = m_state.viewport.width;
vkViewport.height = m_state.viewport.height;
vkViewport.minDepth = m_state.viewport.depth_min;
vkViewport.maxDepth = m_state.viewport.depth_max;
// Scissor
if (!m_state.scissor.IsDefined())
{
scissor.offset = { 0, 0 };
scissor.extent.width = static_cast<uint32_t>(vkViewport.width);
scissor.extent.height = static_cast<uint32_t>(vkViewport.height);
}
else
{
scissor.offset = { static_cast<int32_t>(m_state.scissor.left), static_cast<int32_t>(m_state.scissor.top) };
scissor.extent.width = static_cast<uint32_t>(m_state.scissor.Width());
scissor.extent.height = static_cast<uint32_t>(m_state.scissor.Height());
}
// Viewport state
viewport_state.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
viewport_state.viewportCount = 1;
viewport_state.pViewports = &vkViewport;
viewport_state.scissorCount = 1;
viewport_state.pScissors = &scissor;
}
// Shader stages
vector<VkPipelineShaderStageCreateInfo> shader_stages;
// Vertex shader
if (m_state.shader_vertex)
{
if (!m_state.shader_vertex->GetResource() || !m_state.shader_vertex->GetEntryPoint())
{
LOG_ERROR("Vertex shader is invalid");
return;
}
VkPipelineShaderStageCreateInfo shader_vertex_stage_info = {};
shader_vertex_stage_info.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
shader_vertex_stage_info.stage = VK_SHADER_STAGE_VERTEX_BIT;
shader_vertex_stage_info.module = static_cast<VkShaderModule>(m_state.shader_vertex->GetResource());
shader_vertex_stage_info.pName = m_state.shader_vertex->GetEntryPoint();
shader_stages.push_back(shader_vertex_stage_info);
}
else
{
LOG_ERROR("Vertex shader is invalid");
return;
}
// Pixel shader
if (m_state.shader_pixel)
{
if (!m_state.shader_pixel->GetResource() || !m_state.shader_pixel->GetEntryPoint())
{
LOG_ERROR("Pixel shader is invalid");
return;
}
VkPipelineShaderStageCreateInfo shader_pixel_stage_info = {};
shader_pixel_stage_info.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
shader_pixel_stage_info.stage = VK_SHADER_STAGE_FRAGMENT_BIT;
shader_pixel_stage_info.module = static_cast<VkShaderModule>(m_state.shader_pixel->GetResource());
shader_pixel_stage_info.pName = m_state.shader_pixel->GetEntryPoint();
shader_stages.push_back(shader_pixel_stage_info);
}
// Binding description
VkVertexInputBindingDescription binding_description = {};
binding_description.binding = 0;
binding_description.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
binding_description.stride = m_state.vertex_buffer_stride;
// Vertex attributes description
vector<VkVertexInputAttributeDescription> vertex_attribute_descs;
if (m_state.shader_vertex)
{
if (RHI_InputLayout* input_layout = m_state.shader_vertex->GetInputLayout().get())
{
vertex_attribute_descs.reserve(input_layout->GetAttributeDescriptions().size());
for (const auto& desc : input_layout->GetAttributeDescriptions())
{
vertex_attribute_descs.push_back
({
desc.location, // location
desc.binding, // binding
vulkan_format[desc.format], // format
desc.offset // offset
});
}
}
}
// Vertex input state
VkPipelineVertexInputStateCreateInfo vertex_input_state = {};
{
vertex_input_state.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
vertex_input_state.vertexBindingDescriptionCount = 1;
vertex_input_state.pVertexBindingDescriptions = &binding_description;
vertex_input_state.vertexAttributeDescriptionCount = static_cast<uint32_t>(vertex_attribute_descs.size());
vertex_input_state.pVertexAttributeDescriptions = vertex_attribute_descs.data();
}
// Input assembly
VkPipelineInputAssemblyStateCreateInfo input_assembly_state = {};
{
input_assembly_state.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
input_assembly_state.topology = vulkan_primitive_topology[m_state.primitive_topology];
input_assembly_state.primitiveRestartEnable = VK_FALSE;
}
// Rasterizer state
VkPipelineRasterizationStateCreateInfo rasterizer_state = {};
VkPipelineRasterizationDepthClipStateCreateInfoEXT rasterizer_state_depth_clip = {};
{
rasterizer_state_depth_clip.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_DEPTH_CLIP_STATE_CREATE_INFO_EXT;
rasterizer_state_depth_clip.pNext = nullptr;
rasterizer_state_depth_clip.flags = 0;
rasterizer_state_depth_clip.depthClipEnable = m_state.rasterizer_state->GetDepthClipEnabled();
rasterizer_state.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
rasterizer_state.pNext = &rasterizer_state_depth_clip;
rasterizer_state.depthClampEnable = VK_FALSE;
rasterizer_state.rasterizerDiscardEnable = VK_FALSE;
rasterizer_state.polygonMode = vulkan_polygon_mode[m_state.rasterizer_state->GetFillMode()];
rasterizer_state.lineWidth = m_rhi_device->GetContextRhi()->device_features.wideLines ? m_state.rasterizer_state->GetLineWidth() : 1.0f;
rasterizer_state.cullMode = vulkan_cull_mode[m_state.rasterizer_state->GetCullMode()];
rasterizer_state.frontFace = VK_FRONT_FACE_CLOCKWISE;
rasterizer_state.depthBiasEnable = VK_FALSE;
rasterizer_state.depthBiasConstantFactor = 0.0f;
rasterizer_state.depthBiasClamp = 0.0f;
rasterizer_state.depthBiasSlopeFactor = 0.0f;
}
// Mutlisampling
VkPipelineMultisampleStateCreateInfo multisampling_state = {};
{
multisampling_state.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
multisampling_state.sampleShadingEnable = m_state.rasterizer_state->GetMultiSampleEnabled() ? VK_TRUE : VK_FALSE;
multisampling_state.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
}
VkPipelineColorBlendStateCreateInfo color_blend_state = {};
vector<VkPipelineColorBlendAttachmentState> blend_state_attachments;
{
// Blend state attachments
{
// Same blend state for all
VkPipelineColorBlendAttachmentState blend_state_attachment = {};
blend_state_attachment.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;
blend_state_attachment.blendEnable = m_state.blend_state->GetBlendEnabled() ? VK_TRUE : VK_FALSE;
blend_state_attachment.srcColorBlendFactor = vulkan_blend_factor[m_state.blend_state->GetSourceBlend()];
blend_state_attachment.dstColorBlendFactor = vulkan_blend_factor[m_state.blend_state->GetDestBlend()];
blend_state_attachment.colorBlendOp = vulkan_blend_operation[m_state.blend_state->GetBlendOp()];
blend_state_attachment.srcAlphaBlendFactor = vulkan_blend_factor[m_state.blend_state->GetSourceBlendAlpha()];
blend_state_attachment.dstAlphaBlendFactor = vulkan_blend_factor[m_state.blend_state->GetDestBlendAlpha()];
blend_state_attachment.alphaBlendOp = vulkan_blend_operation[m_state.blend_state->GetBlendOpAlpha()];
// Swapchain
if (m_state.render_target_swapchain)
{
blend_state_attachments.push_back(blend_state_attachment);
}
// Render target(s)
for (uint32_t i = 0; i < state_max_render_target_count; i++)
{
if (m_state.render_target_color_textures[i] != nullptr)
{
blend_state_attachments.push_back(blend_state_attachment);
}
}
}
color_blend_state.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
color_blend_state.logicOpEnable = VK_FALSE;
color_blend_state.logicOp = VK_LOGIC_OP_COPY;
color_blend_state.attachmentCount = static_cast<uint32_t>(blend_state_attachments.size());
color_blend_state.pAttachments = blend_state_attachments.data();
color_blend_state.blendConstants[0] = m_state.blend_state->GetBlendFactor();
color_blend_state.blendConstants[1] = m_state.blend_state->GetBlendFactor();
color_blend_state.blendConstants[2] = m_state.blend_state->GetBlendFactor();
color_blend_state.blendConstants[3] = m_state.blend_state->GetBlendFactor();
}
// Depth-stencil state
VkPipelineDepthStencilStateCreateInfo depth_stencil_state = {};
{
depth_stencil_state.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
depth_stencil_state.depthTestEnable = m_state.depth_stencil_state->GetDepthTestEnabled();
depth_stencil_state.depthWriteEnable = m_state.depth_stencil_state->GetDepthWriteEnabled();
depth_stencil_state.depthCompareOp = vulkan_compare_operator[m_state.depth_stencil_state->GetDepthFunction()];
depth_stencil_state.stencilTestEnable = m_state.depth_stencil_state->GetStencilTestEnabled();
depth_stencil_state.front.compareOp = vulkan_compare_operator[m_state.depth_stencil_state->GetStencilFunction()];
depth_stencil_state.front.failOp = vulkan_stencil_operation[m_state.depth_stencil_state->GetStencilFailOperation()];
depth_stencil_state.front.depthFailOp = vulkan_stencil_operation[m_state.depth_stencil_state->GetStencilDepthFailOperation()];
depth_stencil_state.front.passOp = vulkan_stencil_operation[m_state.depth_stencil_state->GetStencilPassOperation()];
depth_stencil_state.back = depth_stencil_state.front;
}
// Pipeline layout
VkPipelineLayoutCreateInfo pipeline_layout_info = {};
{
pipeline_layout_info.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
pipeline_layout_info.pushConstantRangeCount = 0;
pipeline_layout_info.setLayoutCount = 1;
pipeline_layout_info.pSetLayouts = reinterpret_cast<VkDescriptorSetLayout*>(&descriptor_set_layout);
if (!vulkan_utility::error::check(vkCreatePipelineLayout(m_rhi_device->GetContextRhi()->device, &pipeline_layout_info, nullptr, reinterpret_cast<VkPipelineLayout*>(&m_pipeline_layout))))
return;
}
// Pipeline
VkGraphicsPipelineCreateInfo pipeline_info = {};
{
pipeline_info.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
pipeline_info.stageCount = static_cast<uint32_t>(shader_stages.size());
pipeline_info.pStages = shader_stages.data();
pipeline_info.pVertexInputState = &vertex_input_state;
pipeline_info.pInputAssemblyState = &input_assembly_state;
pipeline_info.pDynamicState = dynamic_states.empty() ? nullptr : &dynamic_state;
pipeline_info.pViewportState = &viewport_state;
pipeline_info.pRasterizationState = &rasterizer_state;
pipeline_info.pMultisampleState = &multisampling_state;
pipeline_info.pColorBlendState = &color_blend_state;
pipeline_info.pDepthStencilState = &depth_stencil_state;
pipeline_info.layout = static_cast<VkPipelineLayout>(m_pipeline_layout);
pipeline_info.renderPass = static_cast<VkRenderPass>(m_state.GetRenderPass());
auto pipeline = reinterpret_cast<VkPipeline*>(&m_pipeline);
vulkan_utility::error::check(vkCreateGraphicsPipelines(m_rhi_device->GetContextRhi()->device, nullptr, 1, &pipeline_info, nullptr, pipeline));
// Set pipeline name
string name = (m_state.shader_vertex ? m_state.shader_vertex->GetName() : "null") + "-" + (m_state.shader_pixel ? m_state.shader_pixel->GetName() : "null");
vulkan_utility::debug::set_pipeline_name(*pipeline, name.c_str());
}
}
RHI_Pipeline::~RHI_Pipeline()
{
// Wait in case the buffer is still in use
m_rhi_device->Queue_WaitAll();
vkDestroyPipeline(m_rhi_device->GetContextRhi()->device, static_cast<VkPipeline>(m_pipeline), nullptr);
m_pipeline = nullptr;
vkDestroyPipelineLayout(m_rhi_device->GetContextRhi()->device, static_cast<VkPipelineLayout>(m_pipeline_layout), nullptr);
m_pipeline_layout = nullptr;
}
}
#endif
|
#include <QtGlobal>
// Automatically generated by extract_strings.py
#ifdef __GNUC__
#define UNUSED __attribute__((unused))
#else
#define UNUSED
#endif
static const char UNUSED *bitcoin_strings[] = {
QT_TRANSLATE_NOOP("globalboost-y-core", ""
"%s, you must set a rpcpassword in the configuration file:\n"
"%s\n"
"It is recommended you use the following random password:\n"
"rpcuser=globalboostrpc\n"
"rpcpassword=%s\n"
"(you do not need to remember this password)\n"
"The username and password MUST NOT be the same.\n"
"If the file does not exist, create it with owner-readable-only file "
"permissions.\n"
"It is also recommended to set alertnotify so you are notified of problems;\n"
"for example: alertnotify=echo %%s | mail -s \"Globalboost Alert\" globalboostwallet@gmx.com\n"),
QT_TRANSLATE_NOOP("globalboost-y-core", ""
"Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:"
"@STRENGTH)"),
QT_TRANSLATE_NOOP("globalboost-y-core", ""
"An error occurred while setting up the RPC port %u for listening on IPv4: %s"),
QT_TRANSLATE_NOOP("globalboost-y-core", ""
"An error occurred while setting up the RPC port %u for listening on IPv6, "
"falling back to IPv4: %s"),
QT_TRANSLATE_NOOP("globalboost-y-core", ""
"Bind to given address and always listen on it. Use [host]:port notation for "
"IPv6"),
QT_TRANSLATE_NOOP("globalboost-y-core", ""
"Cannot obtain a lock on data directory %s. Globalboost is probably already "
"running."),
QT_TRANSLATE_NOOP("globalboost-y-core", ""
"Error: The transaction was rejected! This might happen if some of the coins "
"in your wallet were already spent, such as if you used a copy of wallet.dat "
"and coins were spent in the copy but not marked as spent here."),
QT_TRANSLATE_NOOP("globalboost-y-core", ""
"Error: This transaction requires a transaction fee of at least %s because of "
"its amount, complexity, or use of recently received funds!"),
QT_TRANSLATE_NOOP("globalboost-y-core", ""
"Execute command when a relevant alert is received (%s in cmd is replaced by "
"message)"),
QT_TRANSLATE_NOOP("globalboost-y-core", ""
"Execute command when a wallet transaction changes (%s in cmd is replaced by "
"TxID)"),
QT_TRANSLATE_NOOP("globalboost-y-core", ""
"Execute command when the best block changes (%s in cmd is replaced by block "
"hash)"),
QT_TRANSLATE_NOOP("globalboost-y-core", ""
"Listen for JSON-RPC connections on <port> (default: 9332 or testnet: 19332)"),
QT_TRANSLATE_NOOP("globalboost-y-core", ""
"Number of seconds to keep misbehaving peers from reconnecting (default: "
"86400)"),
QT_TRANSLATE_NOOP("globalboost-y-core", ""
"Set maximum size of high-priority/low-fee transactions in bytes (default: "
"27000)"),
QT_TRANSLATE_NOOP("globalboost-y-core", ""
"Set the number of script verification threads (up to 16, 0 = auto, <0 = "
"leave that many cores free, default: 0)"),
QT_TRANSLATE_NOOP("globalboost-y-core", ""
"This is a pre-release test build - use at your own risk - do not use for "
"mining or merchant applications"),
QT_TRANSLATE_NOOP("globalboost-y-core", ""
"Unable to bind to %s on this computer. Globalboost is probably already running."),
QT_TRANSLATE_NOOP("globalboost-y-core", ""
"Warning: -paytxfee is set very high! This is the transaction fee you will "
"pay if you send a transaction."),
QT_TRANSLATE_NOOP("globalboost-y-core", ""
"Warning: Displayed transactions may not be correct! You may need to upgrade, "
"or other nodes may need to upgrade."),
QT_TRANSLATE_NOOP("globalboost-y-core", ""
"Warning: Please check that your computer's date and time are correct! If "
"your clock is wrong Globalboost will not work properly."),
QT_TRANSLATE_NOOP("globalboost-y-core", ""
"Warning: error reading wallet.dat! All keys read correctly, but transaction "
"data or address book entries might be missing or incorrect."),
QT_TRANSLATE_NOOP("globalboost-y-core", ""
"Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as "
"wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect "
"you should restore from a backup."),
QT_TRANSLATE_NOOP("globalboost-y-core", ""
"You must set rpcpassword=<password> in the configuration file:\n"
"%s\n"
"If the file does not exist, create it with owner-readable-only file "
"permissions."),
QT_TRANSLATE_NOOP("globalboost-y-core", "Accept command line and JSON-RPC commands"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Accept connections from outside (default: 1 if no -proxy or -connect)"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Add a node to connect to and attempt to keep the connection open"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Allow DNS lookups for -addnode, -seednode and -connect"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Allow JSON-RPC connections from specified IP address"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Attempt to recover private keys from a corrupt wallet.dat"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Globalboost version"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Block creation options:"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Cannot downgrade wallet"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Cannot resolve -bind address: '%s'"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Cannot resolve -externalip address: '%s'"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Cannot write default address"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Connect only to the specified node(s)"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Connect through socks proxy"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Connect to a node to retrieve peer addresses, and disconnect"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Corrupted block database detected"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Discover own IP address (default: 1 when listening and no -externalip)"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Do you want to rebuild the block database now?"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Done loading"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Error initializing block database"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Error initializing wallet database environment %s!"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Error loading block database"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Error loading wallet.dat"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Error loading wallet.dat: Wallet corrupted"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Error loading wallet.dat: Wallet requires newer version of Globalboost"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Error opening block database"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Error"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Error: Disk space is low!"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Error: Wallet locked, unable to create transaction!"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Error: system error: "),
QT_TRANSLATE_NOOP("globalboost-y-core", "Failed to listen on any port. Use -listen=0 if you want this."),
QT_TRANSLATE_NOOP("globalboost-y-core", "Failed to read block info"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Failed to read block"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Failed to sync block index"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Failed to write block index"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Failed to write block info"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Failed to write block"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Failed to write file info"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Failed to write to coin database"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Failed to write transaction index"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Failed to write undo data"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Fee per KB to add to transactions you send"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Find peers using DNS lookup (default: 1 unless -connect)"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Generate coins (default: 0)"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Get help for a command"),
QT_TRANSLATE_NOOP("globalboost-y-core", "How many blocks to check at startup (default: 288, 0 = all)"),
QT_TRANSLATE_NOOP("globalboost-y-core", "How thorough the block verification is (0-4, default: 3)"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Imports blocks from external blk000??.dat file"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Information"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Insufficient funds"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Invalid -proxy address: '%s'"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Invalid -tor address: '%s'"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Invalid amount for -minrelaytxfee=<amount>: '%s'"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Invalid amount for -mintxfee=<amount>: '%s'"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Invalid amount for -paytxfee=<amount>: '%s'"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Invalid amount"),
QT_TRANSLATE_NOOP("globalboost-y-core", "List commands"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Listen for connections on <port> (default: 9333 or testnet: 19333)"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Loading addresses..."),
QT_TRANSLATE_NOOP("globalboost-y-core", "Loading block index..."),
QT_TRANSLATE_NOOP("globalboost-y-core", "Loading wallet..."),
QT_TRANSLATE_NOOP("globalboost-y-core", "Maintain a full transaction index (default: 0)"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Maintain at most <n> connections to peers (default: 125)"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Not enough file descriptors available."),
QT_TRANSLATE_NOOP("globalboost-y-core", "Only accept block chain matching built-in checkpoints (default: 1)"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Only connect to nodes in network <net> (IPv4, IPv6 or Tor)"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Options:"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Output extra debugging information. Implies all other -debug* options"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Output extra network debugging information"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Password for JSON-RPC connections"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Prepend debug output with timestamp"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Rebuild block chain index from current blk000??.dat files"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Rescan the block chain for missing wallet transactions"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Rescanning..."),
QT_TRANSLATE_NOOP("globalboost-y-core", "Run in the background as a daemon and accept commands"),
QT_TRANSLATE_NOOP("globalboost-y-core", "SSL options: (see the Globalboost Wiki for SSL setup instructions)"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Select the version of socks proxy to use (4-5, default: 5)"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Send command to -server or globalboostd"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Send commands to node running on <ip> (default: 127.0.0.1)"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Send trace/debug info to console instead of debug.log file"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Send trace/debug info to debugger"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Server certificate file (default: server.cert)"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Server private key (default: server.pem)"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Set database cache size in megabytes (default: 25)"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Set key pool size to <n> (default: 100)"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Set maximum block size in bytes (default: 250000)"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Set minimum block size in bytes (default: 0)"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Set the number of threads to service RPC calls (default: 4)"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Shrink debug.log file on client startup (default: 1 when no -debug)"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Signing transaction failed"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Specify configuration file (default: globalboost.conf)"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Specify connection timeout in milliseconds (default: 5000)"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Specify data directory"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Specify pid file (default: globalboostd.pid)"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Specify your own public address"),
QT_TRANSLATE_NOOP("globalboost-y-core", "System error: "),
QT_TRANSLATE_NOOP("globalboost-y-core", "This help message"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Threshold for disconnecting misbehaving peers (default: 100)"),
QT_TRANSLATE_NOOP("globalboost-y-core", "To use the %s option"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Transaction amount too small"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Transaction amounts must be positive"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Transaction too large"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Unable to bind to %s on this computer (bind returned error %d, %s)"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Unknown -socks proxy version requested: %i"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Unknown network specified in -onlynet: '%s'"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Upgrade wallet to latest format"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Usage:"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Use OpenSSL (https) for JSON-RPC connections"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Use UPnP to map the listening port (default: 0)"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Use UPnP to map the listening port (default: 1 when listening)"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Use proxy to reach tor hidden services (default: same as -proxy)"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Use the test network"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Username for JSON-RPC connections"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Verifying blocks..."),
QT_TRANSLATE_NOOP("globalboost-y-core", "Verifying wallet..."),
QT_TRANSLATE_NOOP("globalboost-y-core", "Wallet needed to be rewritten: restart Globalboost to complete"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Warning"),
QT_TRANSLATE_NOOP("globalboost-y-core", "Warning: This version is obsolete, upgrade required!"),
QT_TRANSLATE_NOOP("globalboost-y-core", "You need to rebuild the database"),
QT_TRANSLATE_NOOP("globalboost-y-core", "wallet.dat corrupt, salvage failed"),
};
|
//
// (C) Copyright 1998-1999 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
//
#include "stdafx.h"
#include "ArxDbgReferenceFiler.h"
ACRX_CONS_DEFINE_MEMBERS(ArxDbgReferenceFiler, AcDbDwgFiler, 0);
/****************************************************************************
**
** ArxDbgReferenceFiler::writeHardOwnershipId
**
** **jma
**
*************************************/
Acad::ErrorStatus
ArxDbgReferenceFiler::writeHardOwnershipId(const AcDbHardOwnershipId& id)
{
if (id.isNull() == false)
m_hardOwnershipIds.append(id);
return Acad::eOk;
}
/****************************************************************************
**
** ArxDbgReferenceFiler::writeSoftOwnershipId
**
** **jma
**
*************************************/
Acad::ErrorStatus
ArxDbgReferenceFiler::writeSoftOwnershipId(const AcDbSoftOwnershipId& id)
{
if (id.isNull() == false)
m_softOwnershipIds.append(id);
return Acad::eOk;
}
/****************************************************************************
**
** ArxDbgReferenceFiler::writeHardPointerId
**
** **jma
**
*************************************/
Acad::ErrorStatus
ArxDbgReferenceFiler::writeHardPointerId(const AcDbHardPointerId& id)
{
if (id.isNull() == false)
m_hardPointerIds.append(id);
return Acad::eOk;
}
/****************************************************************************
**
** ArxDbgReferenceFiler::writeSoftPointerId
**
** **jma
**
*************************************/
Acad::ErrorStatus
ArxDbgReferenceFiler::writeSoftPointerId(const AcDbSoftPointerId& id)
{
if (id.isNull() == false)
m_softPointerIds.append(id);
return Acad::eOk;
}
/****************************************************************************
**
** ArxDbgReferenceFiler::reset
**
** **jma
**
*************************************/
void
ArxDbgReferenceFiler::reset()
{
m_hardPointerIds.setLogicalLength(0);
m_softPointerIds.setLogicalLength(0);
m_hardOwnershipIds.setLogicalLength(0);
m_softOwnershipIds.setLogicalLength(0);
}
|
// Copyright (c) 2011-2017 The Cryptonote developers
// Copyright (c) 2017-2018 The Circle Foundation & Conceal Devs
// Copyright (c) 2018-2021 Conceal Network & Conceal Devs
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "RpcServerConfig.h"
#include "Common/CommandLine.h"
#include "CryptoNoteConfig.h"
namespace cn {
namespace {
const std::string DEFAULT_RPC_IP = "127.0.0.1";
const uint16_t DEFAULT_RPC_PORT = RPC_DEFAULT_PORT;
const command_line::arg_descriptor<std::string> arg_rpc_bind_ip = { "rpc-bind-ip", "", DEFAULT_RPC_IP };
const command_line::arg_descriptor<uint16_t> arg_rpc_bind_port = { "rpc-bind-port", "", DEFAULT_RPC_PORT };
}
RpcServerConfig::RpcServerConfig() : bindIp(DEFAULT_RPC_IP), bindPort(DEFAULT_RPC_PORT) {
}
std::string RpcServerConfig::getBindAddress() const {
return bindIp + ":" + std::to_string(bindPort);
}
void RpcServerConfig::initOptions(boost::program_options::options_description& desc) {
command_line::add_arg(desc, arg_rpc_bind_ip);
command_line::add_arg(desc, arg_rpc_bind_port);
}
void RpcServerConfig::init(const boost::program_options::variables_map& vm) {
bindIp = command_line::get_arg(vm, arg_rpc_bind_ip);
bindPort = command_line::get_arg(vm, arg_rpc_bind_port);
}
}
|
// Copyright (c) 2017-2018 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/
#ifndef TAO_PEGTL_CONTRIB_TO_STRING_HPP
#define TAO_PEGTL_CONTRIB_TO_STRING_HPP
#include <string>
#include "../config.hpp"
namespace tao
{
namespace TAO_PEGTL_NAMESPACE
{
namespace internal
{
template< typename >
struct to_string;
template< template< char... > class X, char... Cs >
struct to_string< X< Cs... > >
{
static std::string get()
{
const char s[] = { Cs..., 0 };
return std::string( s, sizeof...( Cs ) );
}
};
} // namespace internal
template< typename T >
std::string to_string()
{
return internal::to_string< T >::get();
}
} // namespace TAO_PEGTL_NAMESPACE
} // namespace tao
#endif
|
// Copyright (c) 2021 The Orbit 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 "TranslationStack.h"
#include "OrbitBase/Logging.h"
void orbit_gl::TranslationStack::PushTranslation(float x, float y, float z) {
translation_stack_.push_back(current_translation_);
current_translation_.xy += Vec2(x, y);
current_translation_.z += z;
}
void orbit_gl::TranslationStack::PopTranslation() {
ORBIT_CHECK(!translation_stack_.empty());
current_translation_ = translation_stack_.back();
translation_stack_.pop_back();
}
|
#ifndef FSLSIMPLEUI_BASE_CONTROL_BUTTON_HPP
#define FSLSIMPLEUI_BASE_CONTROL_BUTTON_HPP
/****************************************************************************************************************************************************
* Copyright (c) 2015 Freescale Semiconductor, 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 the Freescale Semiconductor, 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************************************************************************************/
#include <FslSimpleUI/Base/Control/ContentControl.hpp>
namespace Fsl
{
namespace UI
{
//! A more generic implementation of a button
//! For most purposes the 'button' code is identical to the ButtonBase implementation
class Button : public ContentControl
{
bool m_isEnabled{true};
bool m_isDown{false};
public:
explicit Button(const std::shared_ptr<BaseWindowContext>& context);
virtual bool IsEnabled() const
{
return m_isEnabled;
}
virtual void SetEnabled(const bool enable);
protected:
void OnClickInput(const RoutedEventArgs& args, const std::shared_ptr<WindowInputClickEvent>& theEvent) override;
//! @brief Check if the button is down at the moment
bool IsDown() const
{
return m_isDown;
}
//! @brief Called when the button is pressed
virtual void Down()
{
}
//! @brief Called when the button is released
//! @param wasCanceled true if the press was canceled.
virtual void Up(bool wasCanceled)
{
FSL_PARAM_NOT_USED(wasCanceled);
}
};
}
}
#endif
|
// 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 "chrome/browser/chromeos/login/helper.h"
#include "ash/shell.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/chromeos/net/connectivity_state_helper.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "third_party/cros_system_api/dbus/service_constants.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/screen.h"
namespace chromeos {
gfx::Rect CalculateScreenBounds(const gfx::Size& size) {
gfx::Rect bounds(ash::Shell::GetScreen()->GetPrimaryDisplay().bounds());
if (!size.IsEmpty()) {
int horizontal_diff = bounds.width() - size.width();
int vertical_diff = bounds.height() - size.height();
bounds.Inset(horizontal_diff / 2, vertical_diff / 2);
}
return bounds;
}
string16 GetCurrentNetworkName() {
ConnectivityStateHelper* csh =
ConnectivityStateHelper::Get();
if (csh->IsConnectedType(flimflam::kTypeEthernet)) {
return l10n_util::GetStringUTF16(IDS_STATUSBAR_NETWORK_DEVICE_ETHERNET);
} else if (csh->IsConnectedType(flimflam::kTypeWifi)) {
return UTF8ToUTF16(csh->NetworkNameForType(flimflam::kTypeWifi));
} else if (csh->IsConnectedType(flimflam::kTypeCellular)) {
return UTF8ToUTF16(csh->NetworkNameForType(flimflam::kTypeCellular));
} else if (csh->IsConnectedType(flimflam::kTypeWimax)) {
return UTF8ToUTF16(csh->NetworkNameForType(flimflam::kTypeWimax));
} else if (csh->IsConnectingType(flimflam::kTypeEthernet)) {
return l10n_util::GetStringUTF16(IDS_STATUSBAR_NETWORK_DEVICE_ETHERNET);
} else if (csh->IsConnectingType(flimflam::kTypeWifi)) {
return UTF8ToUTF16(csh->NetworkNameForType(flimflam::kTypeWifi));
} else if (csh->IsConnectingType(flimflam::kTypeCellular)) {
return UTF8ToUTF16(csh->NetworkNameForType(flimflam::kTypeCellular));
} else if (csh->IsConnectingType(flimflam::kTypeWimax)) {
return UTF8ToUTF16(csh->NetworkNameForType(flimflam::kTypeWimax));
} else {
return string16();
}
}
int GetCurrentUserImageSize() {
// The biggest size that the profile picture is displayed at is currently
// 220px, used for the big preview on OOBE and Change Picture options page.
static const int kBaseUserImageSize = 220;
float scale_factor = gfx::Display::GetForcedDeviceScaleFactor();
if (scale_factor > 1.0f)
return static_cast<int>(scale_factor * kBaseUserImageSize);
return kBaseUserImageSize *
ui::GetScaleFactorScale(ui::GetMaxScaleFactor());
}
} // namespace chromeos
|
/*
* Copyright 2015 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define __STDC_LIMIT_MACROS
#include <folly/io/IOBuf.h>
#include <folly/Conv.h>
#include <folly/Likely.h>
#include <folly/Malloc.h>
#include <folly/Memory.h>
#include <folly/ScopeGuard.h>
#include <folly/SpookyHashV2.h>
#include <folly/io/Cursor.h>
#include <stdexcept>
#include <assert.h>
#include <stdint.h>
#include <stdlib.h>
using std::unique_ptr;
namespace {
enum : uint16_t {
kHeapMagic = 0xa5a5,
// This memory segment contains an IOBuf that is still in use
kIOBufInUse = 0x01,
// This memory segment contains buffer data that is still in use
kDataInUse = 0x02,
};
enum : uint64_t {
// When create() is called for buffers less than kDefaultCombinedBufSize,
// we allocate a single combined memory segment for the IOBuf and the data
// together. See the comments for createCombined()/createSeparate() for more
// details.
//
// (The size of 1k is largely just a guess here. We could could probably do
// benchmarks of real applications to see if adjusting this number makes a
// difference. Callers that know their exact use case can also explicitly
// call createCombined() or createSeparate().)
kDefaultCombinedBufSize = 1024
};
// Helper function for IOBuf::takeOwnership()
void takeOwnershipError(bool freeOnError, void* buf,
folly::IOBuf::FreeFunction freeFn,
void* userData) {
if (!freeOnError) {
return;
}
if (!freeFn) {
free(buf);
return;
}
try {
freeFn(buf, userData);
} catch (...) {
// The user's free function is not allowed to throw.
// (We are already in the middle of throwing an exception, so
// we cannot let this exception go unhandled.)
abort();
}
}
} // unnamed namespace
namespace folly {
struct IOBuf::HeapPrefix {
HeapPrefix(uint16_t flg)
: magic(kHeapMagic),
flags(flg) {}
~HeapPrefix() {
// Reset magic to 0 on destruction. This is solely for debugging purposes
// to help catch bugs where someone tries to use HeapStorage after it has
// been deleted.
magic = 0;
}
uint16_t magic;
std::atomic<uint16_t> flags;
};
struct IOBuf::HeapStorage {
HeapPrefix prefix;
// The IOBuf is last in the HeapStorage object.
// This way operator new will work even if allocating a subclass of IOBuf
// that requires more space.
folly::IOBuf buf;
};
struct IOBuf::HeapFullStorage {
// Make sure jemalloc allocates from the 64-byte class. Putting this here
// because HeapStorage is private so it can't be at namespace level.
static_assert(sizeof(HeapStorage) <= 64,
"IOBuf may not grow over 56 bytes!");
HeapStorage hs;
SharedInfo shared;
MaxAlign align;
};
IOBuf::SharedInfo::SharedInfo()
: freeFn(nullptr),
userData(nullptr) {
// Use relaxed memory ordering here. Since we are creating a new SharedInfo,
// no other threads should be referring to it yet.
refcount.store(1, std::memory_order_relaxed);
}
IOBuf::SharedInfo::SharedInfo(FreeFunction fn, void* arg)
: freeFn(fn),
userData(arg) {
// Use relaxed memory ordering here. Since we are creating a new SharedInfo,
// no other threads should be referring to it yet.
refcount.store(1, std::memory_order_relaxed);
}
void* IOBuf::operator new(size_t size) {
size_t fullSize = offsetof(HeapStorage, buf) + size;
auto* storage = static_cast<HeapStorage*>(malloc(fullSize));
// operator new is not allowed to return NULL
if (UNLIKELY(storage == nullptr)) {
throw std::bad_alloc();
}
new (&storage->prefix) HeapPrefix(kIOBufInUse);
return &(storage->buf);
}
void* IOBuf::operator new(size_t size, void* ptr) {
return ptr;
}
void IOBuf::operator delete(void* ptr) {
auto* storageAddr = static_cast<uint8_t*>(ptr) - offsetof(HeapStorage, buf);
auto* storage = reinterpret_cast<HeapStorage*>(storageAddr);
releaseStorage(storage, kIOBufInUse);
}
void IOBuf::releaseStorage(HeapStorage* storage, uint16_t freeFlags) {
CHECK_EQ(storage->prefix.magic, static_cast<uint16_t>(kHeapMagic));
// Use relaxed memory order here. If we are unlucky and happen to get
// out-of-date data the compare_exchange_weak() call below will catch
// it and load new data with memory_order_acq_rel.
auto flags = storage->prefix.flags.load(std::memory_order_acquire);
DCHECK_EQ((flags & freeFlags), freeFlags);
while (true) {
uint16_t newFlags = (flags & ~freeFlags);
if (newFlags == 0) {
// The storage space is now unused. Free it.
storage->prefix.HeapPrefix::~HeapPrefix();
free(storage);
return;
}
// This storage segment still contains portions that are in use.
// Just clear the flags specified in freeFlags for now.
auto ret = storage->prefix.flags.compare_exchange_weak(
flags, newFlags, std::memory_order_acq_rel);
if (ret) {
// We successfully updated the flags.
return;
}
// We failed to update the flags. Some other thread probably updated them
// and cleared some of the other bits. Continue around the loop to see if
// we are the last user now, or if we need to try updating the flags again.
}
}
void IOBuf::freeInternalBuf(void* buf, void* userData) {
auto* storage = static_cast<HeapStorage*>(userData);
releaseStorage(storage, kDataInUse);
}
IOBuf::IOBuf(CreateOp, uint64_t capacity)
: next_(this),
prev_(this),
data_(nullptr),
length_(0),
flagsAndSharedInfo_(0) {
SharedInfo* info;
allocExtBuffer(capacity, &buf_, &info, &capacity_);
setSharedInfo(info);
data_ = buf_;
}
IOBuf::IOBuf(CopyBufferOp op, const void* buf, uint64_t size,
uint64_t headroom, uint64_t minTailroom)
: IOBuf(CREATE, headroom + size + minTailroom) {
advance(headroom);
memcpy(writableData(), buf, size);
append(size);
}
IOBuf::IOBuf(CopyBufferOp op, ByteRange br,
uint64_t headroom, uint64_t minTailroom)
: IOBuf(op, br.data(), br.size(), headroom, minTailroom) {
}
unique_ptr<IOBuf> IOBuf::create(uint64_t capacity) {
// For smaller-sized buffers, allocate the IOBuf, SharedInfo, and the buffer
// all with a single allocation.
//
// We don't do this for larger buffers since it can be wasteful if the user
// needs to reallocate the buffer but keeps using the same IOBuf object.
// In this case we can't free the data space until the IOBuf is also
// destroyed. Callers can explicitly call createCombined() or
// createSeparate() if they know their use case better, and know if they are
// likely to reallocate the buffer later.
if (capacity <= kDefaultCombinedBufSize) {
return createCombined(capacity);
}
return createSeparate(capacity);
}
unique_ptr<IOBuf> IOBuf::createCombined(uint64_t capacity) {
// To save a memory allocation, allocate space for the IOBuf object, the
// SharedInfo struct, and the data itself all with a single call to malloc().
size_t requiredStorage = offsetof(HeapFullStorage, align) + capacity;
size_t mallocSize = goodMallocSize(requiredStorage);
auto* storage = static_cast<HeapFullStorage*>(malloc(mallocSize));
new (&storage->hs.prefix) HeapPrefix(kIOBufInUse | kDataInUse);
new (&storage->shared) SharedInfo(freeInternalBuf, storage);
uint8_t* bufAddr = reinterpret_cast<uint8_t*>(&storage->align);
uint8_t* storageEnd = reinterpret_cast<uint8_t*>(storage) + mallocSize;
size_t actualCapacity = storageEnd - bufAddr;
unique_ptr<IOBuf> ret(new (&storage->hs.buf) IOBuf(
InternalConstructor(), packFlagsAndSharedInfo(0, &storage->shared),
bufAddr, actualCapacity, bufAddr, 0));
return ret;
}
unique_ptr<IOBuf> IOBuf::createSeparate(uint64_t capacity) {
return make_unique<IOBuf>(CREATE, capacity);
}
unique_ptr<IOBuf> IOBuf::createChain(
size_t totalCapacity, uint64_t maxBufCapacity) {
unique_ptr<IOBuf> out = create(
std::min(totalCapacity, size_t(maxBufCapacity)));
size_t allocatedCapacity = out->capacity();
while (allocatedCapacity < totalCapacity) {
unique_ptr<IOBuf> newBuf = create(
std::min(totalCapacity - allocatedCapacity, size_t(maxBufCapacity)));
allocatedCapacity += newBuf->capacity();
out->prependChain(std::move(newBuf));
}
return out;
}
IOBuf::IOBuf(TakeOwnershipOp, void* buf, uint64_t capacity, uint64_t length,
FreeFunction freeFn, void* userData,
bool freeOnError)
: next_(this),
prev_(this),
data_(static_cast<uint8_t*>(buf)),
buf_(static_cast<uint8_t*>(buf)),
length_(length),
capacity_(capacity),
flagsAndSharedInfo_(packFlagsAndSharedInfo(kFlagFreeSharedInfo, nullptr)) {
try {
setSharedInfo(new SharedInfo(freeFn, userData));
} catch (...) {
takeOwnershipError(freeOnError, buf, freeFn, userData);
throw;
}
}
unique_ptr<IOBuf> IOBuf::takeOwnership(void* buf, uint64_t capacity,
uint64_t length,
FreeFunction freeFn,
void* userData,
bool freeOnError) {
try {
// TODO: We could allocate the IOBuf object and SharedInfo all in a single
// memory allocation. We could use the existing HeapStorage class, and
// define a new kSharedInfoInUse flag. We could change our code to call
// releaseStorage(kFlagFreeSharedInfo) when this kFlagFreeSharedInfo,
// rather than directly calling delete.
//
// Note that we always pass freeOnError as false to the constructor.
// If the constructor throws we'll handle it below. (We have to handle
// allocation failures from make_unique too.)
return make_unique<IOBuf>(TAKE_OWNERSHIP, buf, capacity, length,
freeFn, userData, false);
} catch (...) {
takeOwnershipError(freeOnError, buf, freeFn, userData);
throw;
}
}
IOBuf::IOBuf(WrapBufferOp, const void* buf, uint64_t capacity)
: IOBuf(InternalConstructor(), 0,
// We cast away the const-ness of the buffer here.
// This is okay since IOBuf users must use unshare() to create a copy
// of this buffer before writing to the buffer.
static_cast<uint8_t*>(const_cast<void*>(buf)), capacity,
static_cast<uint8_t*>(const_cast<void*>(buf)), capacity) {
}
IOBuf::IOBuf(WrapBufferOp op, ByteRange br)
: IOBuf(op, br.data(), br.size()) {
}
unique_ptr<IOBuf> IOBuf::wrapBuffer(const void* buf, uint64_t capacity) {
return make_unique<IOBuf>(WRAP_BUFFER, buf, capacity);
}
IOBuf::IOBuf() noexcept {
}
IOBuf::IOBuf(IOBuf&& other) noexcept {
*this = std::move(other);
}
IOBuf::IOBuf(InternalConstructor,
uintptr_t flagsAndSharedInfo,
uint8_t* buf,
uint64_t capacity,
uint8_t* data,
uint64_t length)
: next_(this),
prev_(this),
data_(data),
buf_(buf),
length_(length),
capacity_(capacity),
flagsAndSharedInfo_(flagsAndSharedInfo) {
assert(data >= buf);
assert(data + length <= buf + capacity);
}
IOBuf::~IOBuf() {
// Destroying an IOBuf destroys the entire chain.
// Users of IOBuf should only explicitly delete the head of any chain.
// The other elements in the chain will be automatically destroyed.
while (next_ != this) {
// Since unlink() returns unique_ptr() and we don't store it,
// it will automatically delete the unlinked element.
(void)next_->unlink();
}
decrementRefcount();
}
IOBuf& IOBuf::operator=(IOBuf&& other) noexcept {
if (this == &other) {
return *this;
}
// If we are part of a chain, delete the rest of the chain.
while (next_ != this) {
// Since unlink() returns unique_ptr() and we don't store it,
// it will automatically delete the unlinked element.
(void)next_->unlink();
}
// Decrement our refcount on the current buffer
decrementRefcount();
// Take ownership of the other buffer's data
data_ = other.data_;
buf_ = other.buf_;
length_ = other.length_;
capacity_ = other.capacity_;
flagsAndSharedInfo_ = other.flagsAndSharedInfo_;
// Reset other so it is a clean state to be destroyed.
other.data_ = nullptr;
other.buf_ = nullptr;
other.length_ = 0;
other.capacity_ = 0;
other.flagsAndSharedInfo_ = 0;
// If other was part of the chain, assume ownership of the rest of its chain.
// (It's only valid to perform move assignment on the head of a chain.)
if (other.next_ != &other) {
next_ = other.next_;
next_->prev_ = this;
other.next_ = &other;
prev_ = other.prev_;
prev_->next_ = this;
other.prev_ = &other;
}
// Sanity check to make sure that other is in a valid state to be destroyed.
DCHECK_EQ(other.prev_, &other);
DCHECK_EQ(other.next_, &other);
return *this;
}
bool IOBuf::empty() const {
const IOBuf* current = this;
do {
if (current->length() != 0) {
return false;
}
current = current->next_;
} while (current != this);
return true;
}
size_t IOBuf::countChainElements() const {
size_t numElements = 1;
for (IOBuf* current = next_; current != this; current = current->next_) {
++numElements;
}
return numElements;
}
uint64_t IOBuf::computeChainDataLength() const {
uint64_t fullLength = length_;
for (IOBuf* current = next_; current != this; current = current->next_) {
fullLength += current->length_;
}
return fullLength;
}
void IOBuf::prependChain(unique_ptr<IOBuf>&& iobuf) {
// Take ownership of the specified IOBuf
IOBuf* other = iobuf.release();
// Remember the pointer to the tail of the other chain
IOBuf* otherTail = other->prev_;
// Hook up prev_->next_ to point at the start of the other chain,
// and other->prev_ to point at prev_
prev_->next_ = other;
other->prev_ = prev_;
// Hook up otherTail->next_ to point at us,
// and prev_ to point back at otherTail,
otherTail->next_ = this;
prev_ = otherTail;
}
unique_ptr<IOBuf> IOBuf::clone() const {
unique_ptr<IOBuf> ret = make_unique<IOBuf>();
cloneInto(*ret);
return ret;
}
unique_ptr<IOBuf> IOBuf::cloneOne() const {
unique_ptr<IOBuf> ret = make_unique<IOBuf>();
cloneOneInto(*ret);
return ret;
}
void IOBuf::cloneInto(IOBuf& other) const {
IOBuf tmp;
cloneOneInto(tmp);
for (IOBuf* current = next_; current != this; current = current->next_) {
tmp.prependChain(current->cloneOne());
}
other = std::move(tmp);
}
void IOBuf::cloneOneInto(IOBuf& other) const {
SharedInfo* info = sharedInfo();
if (info) {
setFlags(kFlagMaybeShared);
}
other = IOBuf(InternalConstructor(),
flagsAndSharedInfo_, buf_, capacity_,
data_, length_);
if (info) {
info->refcount.fetch_add(1, std::memory_order_acq_rel);
}
}
void IOBuf::unshareOneSlow() {
// Allocate a new buffer for the data
uint8_t* buf;
SharedInfo* sharedInfo;
uint64_t actualCapacity;
allocExtBuffer(capacity_, &buf, &sharedInfo, &actualCapacity);
// Copy the data
// Maintain the same amount of headroom. Since we maintained the same
// minimum capacity we also maintain at least the same amount of tailroom.
uint64_t headlen = headroom();
memcpy(buf + headlen, data_, length_);
// Release our reference on the old buffer
decrementRefcount();
// Make sure kFlagMaybeShared and kFlagFreeSharedInfo are all cleared.
setFlagsAndSharedInfo(0, sharedInfo);
// Update the buffer pointers to point to the new buffer
data_ = buf + headlen;
buf_ = buf;
}
void IOBuf::unshareChained() {
// unshareChained() should only be called if we are part of a chain of
// multiple IOBufs. The caller should have already verified this.
assert(isChained());
IOBuf* current = this;
while (true) {
if (current->isSharedOne()) {
// we have to unshare
break;
}
current = current->next_;
if (current == this) {
// None of the IOBufs in the chain are shared,
// so return without doing anything
return;
}
}
// We have to unshare. Let coalesceSlow() do the work.
coalesceSlow();
}
void IOBuf::coalesceSlow() {
// coalesceSlow() should only be called if we are part of a chain of multiple
// IOBufs. The caller should have already verified this.
DCHECK(isChained());
// Compute the length of the entire chain
uint64_t newLength = 0;
IOBuf* end = this;
do {
newLength += end->length_;
end = end->next_;
} while (end != this);
coalesceAndReallocate(newLength, end);
// We should be only element left in the chain now
DCHECK(!isChained());
}
void IOBuf::coalesceSlow(size_t maxLength) {
// coalesceSlow() should only be called if we are part of a chain of multiple
// IOBufs. The caller should have already verified this.
DCHECK(isChained());
DCHECK_LT(length_, maxLength);
// Compute the length of the entire chain
uint64_t newLength = 0;
IOBuf* end = this;
while (true) {
newLength += end->length_;
end = end->next_;
if (newLength >= maxLength) {
break;
}
if (end == this) {
throw std::overflow_error("attempted to coalesce more data than "
"available");
}
}
coalesceAndReallocate(newLength, end);
// We should have the requested length now
DCHECK_GE(length_, maxLength);
}
void IOBuf::coalesceAndReallocate(size_t newHeadroom,
size_t newLength,
IOBuf* end,
size_t newTailroom) {
uint64_t newCapacity = newLength + newHeadroom + newTailroom;
// Allocate space for the coalesced buffer.
// We always convert to an external buffer, even if we happened to be an
// internal buffer before.
uint8_t* newBuf;
SharedInfo* newInfo;
uint64_t actualCapacity;
allocExtBuffer(newCapacity, &newBuf, &newInfo, &actualCapacity);
// Copy the data into the new buffer
uint8_t* newData = newBuf + newHeadroom;
uint8_t* p = newData;
IOBuf* current = this;
size_t remaining = newLength;
do {
assert(current->length_ <= remaining);
remaining -= current->length_;
memcpy(p, current->data_, current->length_);
p += current->length_;
current = current->next_;
} while (current != end);
assert(remaining == 0);
// Point at the new buffer
decrementRefcount();
// Make sure kFlagMaybeShared and kFlagFreeSharedInfo are all cleared.
setFlagsAndSharedInfo(0, newInfo);
capacity_ = actualCapacity;
buf_ = newBuf;
data_ = newData;
length_ = newLength;
// Separate from the rest of our chain.
// Since we don't store the unique_ptr returned by separateChain(),
// this will immediately delete the returned subchain.
if (isChained()) {
(void)separateChain(next_, current->prev_);
}
}
void IOBuf::decrementRefcount() {
// Externally owned buffers don't have a SharedInfo object and aren't managed
// by the reference count
SharedInfo* info = sharedInfo();
if (!info) {
return;
}
// Decrement the refcount
uint32_t newcnt = info->refcount.fetch_sub(
1, std::memory_order_acq_rel);
// Note that fetch_sub() returns the value before we decremented.
// If it is 1, we were the only remaining user; if it is greater there are
// still other users.
if (newcnt > 1) {
return;
}
// We were the last user. Free the buffer
freeExtBuffer();
// Free the SharedInfo if it was allocated separately.
//
// This is only used by takeOwnership().
//
// To avoid this special case handling in decrementRefcount(), we could have
// takeOwnership() set a custom freeFn() that calls the user's free function
// then frees the SharedInfo object. (This would require that
// takeOwnership() store the user's free function with its allocated
// SharedInfo object.) However, handling this specially with a flag seems
// like it shouldn't be problematic.
if (flags() & kFlagFreeSharedInfo) {
delete sharedInfo();
}
}
void IOBuf::reserveSlow(uint64_t minHeadroom, uint64_t minTailroom) {
size_t newCapacity = (size_t)length_ + minHeadroom + minTailroom;
DCHECK_LT(newCapacity, UINT32_MAX);
// reserveSlow() is dangerous if anyone else is sharing the buffer, as we may
// reallocate and free the original buffer. It should only ever be called if
// we are the only user of the buffer.
DCHECK(!isSharedOne());
// We'll need to reallocate the buffer.
// There are a few options.
// - If we have enough total room, move the data around in the buffer
// and adjust the data_ pointer.
// - If we're using an internal buffer, we'll switch to an external
// buffer with enough headroom and tailroom.
// - If we have enough headroom (headroom() >= minHeadroom) but not too much
// (so we don't waste memory), we can try one of two things, depending on
// whether we use jemalloc or not:
// - If using jemalloc, we can try to expand in place, avoiding a memcpy()
// - If not using jemalloc and we don't have too much to copy,
// we'll use realloc() (note that realloc might have to copy
// headroom + data + tailroom, see smartRealloc in folly/Malloc.h)
// - Otherwise, bite the bullet and reallocate.
if (headroom() + tailroom() >= minHeadroom + minTailroom) {
uint8_t* newData = writableBuffer() + minHeadroom;
memmove(newData, data_, length_);
data_ = newData;
return;
}
size_t newAllocatedCapacity = goodExtBufferSize(newCapacity);
uint8_t* newBuffer = nullptr;
uint64_t newHeadroom = 0;
uint64_t oldHeadroom = headroom();
// If we have a buffer allocated with malloc and we just need more tailroom,
// try to use realloc()/xallocx() to grow the buffer in place.
SharedInfo* info = sharedInfo();
if (info && (info->freeFn == nullptr) && length_ != 0 &&
oldHeadroom >= minHeadroom) {
if (usingJEMalloc()) {
size_t headSlack = oldHeadroom - minHeadroom;
// We assume that tailroom is more useful and more important than
// headroom (not least because realloc / xallocx allow us to grow the
// buffer at the tail, but not at the head) So, if we have more headroom
// than we need, we consider that "wasted". We arbitrarily define "too
// much" headroom to be 25% of the capacity.
if (headSlack * 4 <= newCapacity) {
size_t allocatedCapacity = capacity() + sizeof(SharedInfo);
void* p = buf_;
if (allocatedCapacity >= jemallocMinInPlaceExpandable) {
if (xallocx(p, newAllocatedCapacity, 0, 0) == newAllocatedCapacity) {
newBuffer = static_cast<uint8_t*>(p);
newHeadroom = oldHeadroom;
newAllocatedCapacity = newAllocatedCapacity;
}
// if xallocx failed, do nothing, fall back to malloc/memcpy/free
}
}
} else { // Not using jemalloc
size_t copySlack = capacity() - length_;
if (copySlack * 2 <= length_) {
void* p = realloc(buf_, newAllocatedCapacity);
if (UNLIKELY(p == nullptr)) {
throw std::bad_alloc();
}
newBuffer = static_cast<uint8_t*>(p);
newHeadroom = oldHeadroom;
}
}
}
// None of the previous reallocation strategies worked (or we're using
// an internal buffer). malloc/copy/free.
if (newBuffer == nullptr) {
void* p = malloc(newAllocatedCapacity);
if (UNLIKELY(p == nullptr)) {
throw std::bad_alloc();
}
newBuffer = static_cast<uint8_t*>(p);
memcpy(newBuffer + minHeadroom, data_, length_);
if (sharedInfo()) {
freeExtBuffer();
}
newHeadroom = minHeadroom;
}
uint64_t cap;
initExtBuffer(newBuffer, newAllocatedCapacity, &info, &cap);
if (flags() & kFlagFreeSharedInfo) {
delete sharedInfo();
}
setFlagsAndSharedInfo(0, info);
capacity_ = cap;
buf_ = newBuffer;
data_ = newBuffer + newHeadroom;
// length_ is unchanged
}
void IOBuf::freeExtBuffer() {
SharedInfo* info = sharedInfo();
DCHECK(info);
if (info->freeFn) {
try {
info->freeFn(buf_, info->userData);
} catch (...) {
// The user's free function should never throw. Otherwise we might
// throw from the IOBuf destructor. Other code paths like coalesce()
// also assume that decrementRefcount() cannot throw.
abort();
}
} else {
free(buf_);
}
}
void IOBuf::allocExtBuffer(uint64_t minCapacity,
uint8_t** bufReturn,
SharedInfo** infoReturn,
uint64_t* capacityReturn) {
size_t mallocSize = goodExtBufferSize(minCapacity);
uint8_t* buf = static_cast<uint8_t*>(malloc(mallocSize));
if (UNLIKELY(buf == nullptr)) {
throw std::bad_alloc();
}
initExtBuffer(buf, mallocSize, infoReturn, capacityReturn);
*bufReturn = buf;
}
size_t IOBuf::goodExtBufferSize(uint64_t minCapacity) {
// Determine how much space we should allocate. We'll store the SharedInfo
// for the external buffer just after the buffer itself. (We store it just
// after the buffer rather than just before so that the code can still just
// use free(buf_) to free the buffer.)
size_t minSize = static_cast<size_t>(minCapacity) + sizeof(SharedInfo);
// Add room for padding so that the SharedInfo will be aligned on an 8-byte
// boundary.
minSize = (minSize + 7) & ~7;
// Use goodMallocSize() to bump up the capacity to a decent size to request
// from malloc, so we can use all of the space that malloc will probably give
// us anyway.
return goodMallocSize(minSize);
}
void IOBuf::initExtBuffer(uint8_t* buf, size_t mallocSize,
SharedInfo** infoReturn,
uint64_t* capacityReturn) {
// Find the SharedInfo storage at the end of the buffer
// and construct the SharedInfo.
uint8_t* infoStart = (buf + mallocSize) - sizeof(SharedInfo);
SharedInfo* sharedInfo = new(infoStart) SharedInfo;
*capacityReturn = infoStart - buf;
*infoReturn = sharedInfo;
}
fbstring IOBuf::moveToFbString() {
// malloc-allocated buffers are just fine, everything else needs
// to be turned into one.
if (!sharedInfo() || // user owned, not ours to give up
sharedInfo()->freeFn || // not malloc()-ed
headroom() != 0 || // malloc()-ed block doesn't start at beginning
tailroom() == 0 || // no room for NUL terminator
isShared() || // shared
isChained()) { // chained
// We might as well get rid of all head and tailroom if we're going
// to reallocate; we need 1 byte for NUL terminator.
coalesceAndReallocate(0, computeChainDataLength(), this, 1);
}
// Ensure NUL terminated
*writableTail() = 0;
fbstring str(reinterpret_cast<char*>(writableData()),
length(), capacity(),
AcquireMallocatedString());
if (flags() & kFlagFreeSharedInfo) {
delete sharedInfo();
}
// Reset to a state where we can be deleted cleanly
flagsAndSharedInfo_ = 0;
buf_ = nullptr;
clear();
return str;
}
IOBuf::Iterator IOBuf::cbegin() const {
return Iterator(this, this);
}
IOBuf::Iterator IOBuf::cend() const {
return Iterator(nullptr, nullptr);
}
folly::fbvector<struct iovec> IOBuf::getIov() const {
folly::fbvector<struct iovec> iov;
iov.reserve(countChainElements());
appendToIov(&iov);
return iov;
}
void IOBuf::appendToIov(folly::fbvector<struct iovec>* iov) const {
IOBuf const* p = this;
do {
// some code can get confused by empty iovs, so skip them
if (p->length() > 0) {
iov->push_back({(void*)p->data(), folly::to<size_t>(p->length())});
}
p = p->next();
} while (p != this);
}
size_t IOBuf::fillIov(struct iovec* iov, size_t len) const {
IOBuf const* p = this;
size_t i = 0;
while (i < len) {
// some code can get confused by empty iovs, so skip them
if (p->length() > 0) {
iov[i].iov_base = const_cast<uint8_t*>(p->data());
iov[i].iov_len = p->length();
i++;
}
p = p->next();
if (p == this) {
return i;
}
}
return 0;
}
size_t IOBufHash::operator()(const IOBuf& buf) const {
folly::hash::SpookyHashV2 hasher;
hasher.Init(0, 0);
io::Cursor cursor(&buf);
for (;;) {
auto p = cursor.peek();
if (p.second == 0) {
break;
}
hasher.Update(p.first, p.second);
cursor.skip(p.second);
}
uint64_t h1;
uint64_t h2;
hasher.Final(&h1, &h2);
return h1;
}
bool IOBufEqual::operator()(const IOBuf& a, const IOBuf& b) const {
io::Cursor ca(&a);
io::Cursor cb(&b);
for (;;) {
auto pa = ca.peek();
auto pb = cb.peek();
if (pa.second == 0 && pb.second == 0) {
return true;
} else if (pa.second == 0 || pb.second == 0) {
return false;
}
size_t n = std::min(pa.second, pb.second);
DCHECK_GT(n, 0);
if (memcmp(pa.first, pb.first, n)) {
return false;
}
ca.skip(n);
cb.skip(n);
}
}
} // folly
|
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* 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 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. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``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 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 licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
/* ====================================================================
* Copyright (c) 1998-2007 The OpenSSL Project. 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. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED 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 OpenSSL PROJECT OR
* ITS 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.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
/* ====================================================================
* Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
*
* Portions of the attached software ("Contribution") are developed by
* SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project.
*
* The Contribution is licensed pursuant to the OpenSSL open source
* license provided above.
*
* ECC cipher suite support in OpenSSL originally written by
* Vipul Gupta and Sumit Gupta of Sun Microsystems Laboratories.
*
*/
/* ====================================================================
* Copyright 2005 Nokia. All rights reserved.
*
* The portions of the attached software ("Contribution") is developed by
* Nokia Corporation and is licensed pursuant to the OpenSSL open source
* license.
*
* The Contribution, originally written by Mika Kousa and Pasi Eronen of
* Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
* support (see RFC 4279) to OpenSSL.
*
* No patent licenses or other rights except those expressly stated in
* the OpenSSL open source license shall be deemed granted or received
* expressly, by implication, estoppel, or otherwise.
*
* No assurances are provided by Nokia that the Contribution does not
* infringe the patent or other intellectual property rights of any third
* party or that the license provides you with all the necessary rights
* to make use of the Contribution.
*
* THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
* ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
* SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
* OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
* OTHERWISE. */
#include <CNIOBoringSSL_ssl.h>
#include <assert.h>
#include <string.h>
#include <CNIOBoringSSL_digest.h>
#include <CNIOBoringSSL_err.h>
#include <CNIOBoringSSL_md5.h>
#include <CNIOBoringSSL_mem.h>
#include <CNIOBoringSSL_nid.h>
#include "../crypto/internal.h"
#include "internal.h"
BSSL_NAMESPACE_BEGIN
SSL3_STATE::SSL3_STATE()
: skip_early_data(false),
have_version(false),
v2_hello_done(false),
is_v2_hello(false),
has_message(false),
initial_handshake_complete(false),
session_reused(false),
delegated_credential_used(false),
send_connection_binding(false),
channel_id_valid(false),
key_update_pending(false),
wpend_pending(false),
early_data_accepted(false),
tls13_downgrade(false),
token_binding_negotiated(false),
pq_experiment_signal_seen(false),
alert_dispatch(false),
renegotiate_pending(false),
used_hello_retry_request(false) {}
SSL3_STATE::~SSL3_STATE() {}
bool ssl3_new(SSL *ssl) {
UniquePtr<SSL3_STATE> s3 = MakeUnique<SSL3_STATE>();
if (!s3) {
return false;
}
s3->aead_read_ctx = SSLAEADContext::CreateNullCipher(SSL_is_dtls(ssl));
s3->aead_write_ctx = SSLAEADContext::CreateNullCipher(SSL_is_dtls(ssl));
s3->hs = ssl_handshake_new(ssl);
if (!s3->aead_read_ctx || !s3->aead_write_ctx || !s3->hs) {
return false;
}
ssl->s3 = s3.release();
// Set the version to the highest supported version.
//
// TODO(davidben): Move this field into |s3|, have it store the normalized
// protocol version, and implement this pre-negotiation quirk in |SSL_version|
// at the API boundary rather than in internal state.
ssl->version = TLS1_2_VERSION;
return true;
}
void ssl3_free(SSL *ssl) {
if (ssl == NULL || ssl->s3 == NULL) {
return;
}
Delete(ssl->s3);
ssl->s3 = NULL;
}
BSSL_NAMESPACE_END
|
// This file was automatically generated on Fri May 15 11:57:42 2009
// by libs/config/tools/generate.cpp
// Copyright John Maddock 2002-4.
// Use, modification and distribution are subject to 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/config for the most recent version.//
// Revision $Id: no_0x_hdr_forward_list_fail.cpp 53445 2009-05-30 11:22:59Z bemandawes $
//
// Test file for macro BOOST_NO_0X_HDR_FORWARD_LIST
// This file should not compile, if it does then
// BOOST_NO_0X_HDR_FORWARD_LIST should not be defined.
// See file boost_no_0x_hdr_forward_list.ipp for details
// Must not have BOOST_ASSERT_CONFIG set; it defeats
// the objective of this file:
#ifdef BOOST_ASSERT_CONFIG
# undef BOOST_ASSERT_CONFIG
#endif
#include <boost/config.hpp>
#include "test.hpp"
#ifdef BOOST_NO_0X_HDR_FORWARD_LIST
#include "boost_no_0x_hdr_forward_list.ipp"
#else
#error "this file should not compile"
#endif
int main( int, char *[] )
{
return boost_no_0x_hdr_forward_list::test();
}
|
/*!
* @copyright
* Copyright (c) 2015-2019 Intel Corporation
*
* @copyright
* 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
*
* @copyright
* http://www.apache.org/licenses/LICENSE-2.0
*
* @copyright
* 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 "agent-framework/module/constants/rmm.hpp"
#include "agent-framework/module/requests/common.hpp"
#include "agent-framework/module/responses/common.hpp"
#include "psme/rest/endpoints/chassis/thermal.hpp"
#include "psme/rest/server/error/error_factory.hpp"
#include "psme/rest/utils/status_helpers.hpp"
#include "psme/rest/validators/json_validator.hpp"
#include "psme/rest/validators/schemas/thermal.hpp"
using namespace psme::rest;
using namespace psme::rest::constants;
using namespace psme::rest::validators;
namespace {
json::Json make_prototype() {
json::Json r(json::Json::value_t::object);
r[Common::ODATA_CONTEXT] = "/redfish/v1/$metadata#Thermal.Thermal";
r[Common::ODATA_ID] = json::Json::value_t::null;
r[Common::ODATA_TYPE] = "#Thermal.v1_1_0.Thermal";
r[Common::NAME] = "Thermal";
r[Common::DESCRIPTION] = "Thermal";
r[Common::ID] = "Thermal";
r[ThermalZone::TEMPERATURES] = json::Json::value_t::array;
r[ThermalZone::FANS] = json::Json::value_t::array;
r[Common::REDUNDANCY] = json::Json::value_t::array;
r[Common::STATUS][Common::STATE] = json::Json::value_t::null;
r[Common::STATUS][Common::HEALTH] = json::Json::value_t::null;
r[Common::STATUS][Common::HEALTH_ROLLUP] = json::Json::value_t::null;
json::Json rs = json::Json();
rs[Common::ODATA_TYPE] = "#Intel.Oem.Thermal";
rs[ThermalZone::DESIRED_SPEED_PWM] = json::Json::value_t::null;
rs[ThermalZone::VOLUMETRIC_AIRFLOW_CFM] = json::Json::value_t::null;
r[Common::OEM][Common::RACKSCALE] = std::move(rs);
return r;
}
json::Json make_fan_prototype() {
json::Json r(json::Json::value_t::object);
r[Common::ODATA_ID] = json::Json::value_t::null;
r[Common::ODATA_TYPE] = "#Thermal.v1_1_0.Fan";
r[Common::MEMBER_ID] = json::Json::value_t::null;
r[Common::NAME] = json::Json::value_t::null;
r[ThermalZone::READING] = json::Json::value_t::null;
r[ThermalZone::READING_UNITS] = json::Json::value_t::null;
r[ChassisSensor::UPPER_THRESHOLD_NON_CRITICAL] = json::Json::value_t::null;
r[ChassisSensor::UPPER_THRESHOLD_CRITICAL] = json::Json::value_t::null;
r[ChassisSensor::UPPER_THRESHOLD_FATAL] = json::Json::value_t::null;
r[ChassisSensor::LOWER_THRESHOLD_NON_CRITICAL] = json::Json::value_t::null;
r[ChassisSensor::LOWER_THRESHOLD_CRITICAL] = json::Json::value_t::null;
r[ChassisSensor::LOWER_THRESHOLD_FATAL] = json::Json::value_t::null;
r[ChassisSensor::MIN_READING_RANGE] = json::Json::value_t::null;
r[ChassisSensor::MAX_READING_RANGE] = json::Json::value_t::null;
r[ChassisSensor::PHYSICAL_CONTEXT] = json::Json::value_t::null;
r[Common::STATUS][Common::STATE] = json::Json::value_t::null;
r[Common::STATUS][Common::HEALTH] = json::Json::value_t::null;
r[Common::STATUS][Common::HEALTH_ROLLUP] = json::Json::value_t::null;
r[Common::REDUNDANCY] = json::Json::value_t::array;
r[Common::RELATED_ITEM] = json::Json::value_t::array;
return r;
}
json::Json make_temperature_prototype() {
json::Json r(json::Json::value_t::object);
r[Common::ODATA_ID] = json::Json::value_t::null;
r[Common::MEMBER_ID] = json::Json::value_t::null;
r[Common::NAME] = json::Json::value_t::null;
r[ChassisSensor::SENSOR_NUMBER] = json::Json::value_t::null;
r[ChassisSensor::READING_CELSIUS] = json::Json::value_t::null;
r[ChassisSensor::UPPER_THRESHOLD_NON_CRITICAL] = json::Json::value_t::null;
r[ChassisSensor::UPPER_THRESHOLD_CRITICAL] = json::Json::value_t::null;
r[ChassisSensor::UPPER_THRESHOLD_FATAL] = json::Json::value_t::null;
r[ChassisSensor::LOWER_THRESHOLD_NON_CRITICAL] = json::Json::value_t::null;
r[ChassisSensor::LOWER_THRESHOLD_CRITICAL] = json::Json::value_t::null;
r[ChassisSensor::LOWER_THRESHOLD_FATAL] = json::Json::value_t::null;
r[ChassisSensor::MIN_READING_RANGE_TEMP] = json::Json::value_t::null;
r[ChassisSensor::MAX_READING_RANGE_TEMP] = json::Json::value_t::null;
r[ChassisSensor::PHYSICAL_CONTEXT] = json::Json::value_t::null;
r[Common::STATUS][Common::STATE] = json::Json::value_t::null;
r[Common::STATUS][Common::HEALTH] = json::Json::value_t::null;
r[Common::STATUS][Common::HEALTH_ROLLUP] = json::Json::value_t::null;
r[Common::RELATED_ITEM] = json::Json::value_t::array;
return r;
}
void fill_related_items(const agent_framework::model::ThermalZone& thermal_zone, json::Json& r) {
// Find all chassis related to the current thermal zone
auto cooled_chassis = agent_framework::module::get_manager<agent_framework::model::Chassis>()
.get_keys([thermal_zone](const agent_framework::model::Chassis& ch) {
return ch.get_thermal_zone() == thermal_zone.get_uuid();
});
for (const auto& chassis_uuid : cooled_chassis) {
json::Json related_item = json::Json();
related_item[Common::ODATA_ID] = endpoint::utils::get_component_url(
agent_framework::model::enums::Component::Chassis, chassis_uuid);
r[Common::RELATED_ITEM].push_back(related_item);
}
}
void fill_fans(const agent_framework::model::ThermalZone& thermal_zone,
json::Json& json_response, const std::string& thermal_url) {
auto fans = agent_framework::module::get_manager<agent_framework::model::Fan>()
.get_keys(thermal_zone.get_uuid());
for (std::size_t index = 0; index < fans.size(); index++) {
auto fan = agent_framework::module::get_manager<agent_framework::model::Fan>()
.get_entry(fans[index]);
auto metrics = agent_framework::module::get_manager<agent_framework::model::Metric>().get_entries([&fan](
const agent_framework::model::Metric& metric) -> bool {
return metric.get_component_uuid() == fan.get_uuid();
});
if (metrics.size() != 1) {
log_warning("rest", "Fan " << fan.get_uuid() << " has " << metrics.size() << " assigned metrics.");
continue;
}
const auto& metric = metrics[0];
const auto definition = agent_framework::module::get_manager<agent_framework::model::MetricDefinition>()
.get_entry(metric.get_metric_definition_uuid());
auto f = ::make_fan_prototype();
f[Common::ODATA_ID] =
endpoint::PathBuilder(thermal_url + Common::HASH)
.append(ThermalZone::FANS)
.append(index)
.build();
f[Common::MEMBER_ID] = std::to_string(metric.get_id());
f[Common::NAME] = "BaseBoard System Fan " + std::to_string(index);
// fill Reading field:
endpoint::utils::populate_metrics(f, metrics);
f[ThermalZone::READING_UNITS] = definition.get_units();
f[ChassisSensor::MIN_READING_RANGE] = definition.get_min_reading_range();
f[ChassisSensor::MAX_READING_RANGE] = definition.get_max_reading_range();
f[ChassisSensor::PHYSICAL_CONTEXT] = definition.get_physical_context();
psme::rest::endpoint::status_to_json(fan, f);
::fill_related_items(thermal_zone, f);
json_response[ThermalZone::FANS].push_back(f);
}
}
void fill_temperatures(const agent_framework::model::ThermalZone& thermal_zone,
const std::vector<agent_framework::model::Metric>& temperature_readings,
json::Json& json_response, const std::string& thermal_url) {
for (std::size_t index = 0; index < temperature_readings.size(); index++) {
const auto& temperature_reading = temperature_readings[index];
const auto definition = agent_framework::module::get_manager<agent_framework::model::MetricDefinition>()
.get_entry(temperature_reading.get_metric_definition_uuid());
auto t = ::make_temperature_prototype();
t[Common::ODATA_ID] =
endpoint::PathBuilder(thermal_url + Common::HASH)
.append(ThermalZone::TEMPERATURES)
.append(index)
.build();
t[Common::MEMBER_ID] = std::to_string(temperature_reading.get_id());
t[ChassisSensor::SENSOR_NUMBER] = index;
// fill ReadingCelsius
endpoint::utils::populate_metrics(t, {temperature_reading});
t[Common::NAME] = definition.get_name();
t[ChassisSensor::MIN_READING_RANGE_TEMP] = definition.get_min_reading_range();
t[ChassisSensor::MAX_READING_RANGE_TEMP] = definition.get_max_reading_range();
t[ChassisSensor::PHYSICAL_CONTEXT] = definition.get_physical_context();
psme::rest::endpoint::status_to_json(temperature_reading, t);
::fill_related_items(thermal_zone, t);
json_response[ThermalZone::TEMPERATURES].push_back(t);
}
}
static const std::map<std::string, std::string> gami_to_rest_attributes = {
{agent_framework::model::literals::ThermalZone::DESIRED_SPEED_PWM,
endpoint::PathBuilder(constants::Common::OEM)
.append(constants::Common::RACKSCALE)
.append(constants::ThermalZone::DESIRED_SPEED_PWM)
.build()
}
};
void fill_patch_attributes(const json::Json& patch, agent_framework::model::attribute::Attributes& attributes) {
if (patch.count(constants::Common::OEM)) {
const auto& oem = patch[constants::Common::OEM];
if (oem.count(constants::Common::RACKSCALE)) {
const auto& rackscale = oem[constants::Common::RACKSCALE];
if (rackscale.count(constants::ThermalZone::DESIRED_SPEED_PWM)) {
attributes.set_value(agent_framework::model::literals::ThermalZone::DESIRED_SPEED_PWM,
rackscale[constants::ThermalZone::DESIRED_SPEED_PWM]
);
}
}
}
}
void check_response_errors(const agent_framework::model::responses::SetComponentAttributes& response) {
const auto& result_statuses = response.get_statuses();
if (!result_statuses.empty()) {
const auto& error = error::ErrorFactory::create_error_from_set_component_attributes_results(
result_statuses, ::gami_to_rest_attributes);
throw error::ServerException(error);
}
}
void update_model_after_patch(psme::core::agent::JsonAgentSPtr agent,
const agent_framework::model::ThermalZone& thermal_zone) {
psme::rest::model::handler::HandlerManager::get_instance()->get_handler(
agent_framework::model::enums::Component::ThermalZone)->
load(agent,
thermal_zone.get_parent_uuid(),
agent_framework::model::enums::Component::Chassis,
thermal_zone.get_uuid(),
true);
}
}
endpoint::Thermal::Thermal(const std::string& path) : EndpointBase(path) {}
endpoint::Thermal::~Thermal() {}
void endpoint::Thermal::get(const server::Request& request, server::Response& response) {
auto chassis = model::find<agent_framework::model::Chassis>(request.params).get();
auto thermal_zones = agent_framework::module::get_manager<agent_framework::model::ThermalZone>()
.get_keys(chassis.get_uuid());
auto r = ::make_prototype();
r[Common::ODATA_ID] = PathBuilder(request).build();
if (thermal_zones.empty()) {
throw error::ServerException(error::ErrorFactory::create_resource_missing_error(request.get_url()));
}
else {
auto thermal_zone = agent_framework::module::get_manager<agent_framework::model::ThermalZone>()
.get_entry(thermal_zones.front());
// Thermal Zone metrics:
// airflow metrics go into a property in the top-level json object
auto airflow_metrics = endpoint::utils::get_metrics(thermal_zone, ThermalZone::VOLUMETRIC_AIRFLOW_CFM_PATH);
endpoint::utils::populate_metrics(r, airflow_metrics);
// Thermal metrics go into a separate array in the top-level json object
auto temperature_metrics = endpoint::utils::get_metrics(thermal_zone, ChassisSensor::READING_CELSIUS_PATH);
fill_temperatures(thermal_zone, temperature_metrics, r, request.get_url());
psme::rest::endpoint::status_to_json(thermal_zone, r);
r[Common::OEM][Common::RACKSCALE][ThermalZone::DESIRED_SPEED_PWM] = thermal_zone.get_desired_speed_pwm();
fill_fans(thermal_zone, r, request.get_url());
}
set_response(response, r);
}
void endpoint::Thermal::patch(const server::Request& request, server::Response& response) {
static const constexpr char TRANSACTION_NAME[] = "PatchThermal";
auto chassis = model::find<agent_framework::model::Chassis>(request.params).get();
// Only RMM service has this action
if (!utils::has_resource_capability(chassis, Capability::RMM)) {
throw error::ServerException(
error::ErrorFactory::create_method_not_allowed_error(
"This action is allowed only for RMM service."));
}
auto thermal_zones = agent_framework::module::get_manager<agent_framework::model::ThermalZone>()
.get_keys(chassis.get_uuid());
if (!thermal_zones.empty()) {
auto thermal_zone = agent_framework::module::get_manager<agent_framework::model::ThermalZone>()
.get_entry(thermal_zones.front());
const auto json = JsonValidator::validate_request_body<schema::ThermalPatchSchema>(request);
agent_framework::model::attribute::Attributes attributes{};
::fill_patch_attributes(json, attributes);
if (!attributes.empty()) {
agent_framework::model::requests::SetComponentAttributes gami_request{thermal_zone.get_uuid(), attributes};
const auto& gami_agent = psme::core::agent::AgentManager::get_instance()->get_agent(thermal_zone.get_agent_id());
auto set_thermal_zone_attributes = [&, gami_agent] {
const auto& gami_response =
gami_agent->execute<agent_framework::model::responses::SetComponentAttributes>(gami_request);
::check_response_errors(gami_response);
::update_model_after_patch(gami_agent, thermal_zone);
};
gami_agent->execute_in_transaction(TRANSACTION_NAME, set_thermal_zone_attributes);
}
}
else {
auto message = std::string("PATCH operation on chassis of type ") +
chassis.get_type().to_string() + " is not allowed.";
throw error::ServerException(error::ErrorFactory::create_invalid_payload_error(message));
}
get(request, response);
}
|
#include <dfcio.bios/dfcio.bios.hpp>
DFCIO_ABI( dfcio::bios, (setpriv)(setalimits)(setglimits)(setprods)(setparams)(reqauth) )
|
// Merge.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <iostream>
using namespace std;
int *merge(int *a, int n, int *b, int m)
{
int i = 0, j = 0, k = 0;
int *c = new int[n + m];
while (i < n && j < m)
{
if (a[i] < b[j])
{
c[k] = a[i++];
}
else
{
c[k] = b[j++];
}
k++;
}
// copy any remaining elements
while (i < n)
c[k++] = a[i++];
while (j < m)
c[k++] = b[j++];
return c;
}
int main()
{
freopen("output.txt", "w", stdout);
freopen("input.txt", "r", stdin);
int n, m;
cin >> n >> m;
int *a = new int[n],
*b = new int[m];
for (int i = 0; i < n; i++)
cin >> a[i];
for (int i = 0; i < m; i++)
cin >> b[i];
int *merged = merge(a, n, b, m);
for (int i = 0; i < n + m; i++)
cout << merged[i] << " ";
delete[] a;
delete[] b;
delete[] merged;
return 0;
}
|
#include <cmath>
#include <cstdio>
#include <iostream>
using namespace std;
int seq[800005] = {};
struct set {
int l;
int r;
int current;
int& value;
set left() {
return set{l, (l + r) >> 1, current << 1, seq[current << 1]};
}
set right() {
return set{((l + r) >> 1) + 1, r, current << 1 | 1, seq[current << 1 | 1]};
}
bool isleaf() { return !(r - l); }
};
void buildtree(set s) {
if (s.isleaf()) {
scanf("%d", &(s.value));
return;
}
buildtree(s.left());
buildtree(s.right());
s.value = max(s.left().value, s.right().value);
return;
}
int query(int l, int r, set s) {
if (l <= s.l && s.r <= r) {
return s.value;
}
int mid = (s.l + s.r) >> 1;
int q1 = -1000, q2 = -1000;
if (l <= mid) {
q1 = query(l, r, s.left());
}
if (r > mid) {
q2 = query(l, r, s.right());
}
return max(q1, q2);
}
void update(int l, int r, set s) {
if (l < s.l || s.r < l) {
return;
}
if (s.isleaf()) {
s.value = r;
return;
}
int mid = (s.l + s.r) >> 1;
if (l <= mid) {
update(l, r, s.left());
} else {
update(l, r, s.right());
}
s.value = max(s.left().value, s.right().value);
return;
}
int main() {
//one group
int N, M;
char ch;
int l, r;
while (cin >> N >> M) {
buildtree(set{1, N, 1, seq[1]});
while (M--) {
scanf("\n%c %d %d", &ch, &l, &r);
switch (ch) {
case 'Q':
printf("%d\n", query(l, r, set{1, N, 1, seq[1]}));
break;
case 'U':
update(l, r, set{1, N, 1, seq[1]});
}
}
}
return 0;
}
|
#include "Fast_klt.h"
void myKLT(const cv::Mat source, const cv::Mat target, vector<cv::Point2f> &sourceFeatures, vector<cv::Point2f> &targetFeatures){
cv::Mat img0Gray = cv::Mat::zeros(source.rows, source.cols, CV_8UC1);
cv::Mat curImgGray = cv::Mat::zeros(target.rows, target.cols, CV_8UC1);
cvtColor(source, img0Gray, CV_RGB2GRAY);
cvtColor(target, curImgGray, CV_RGB2GRAY);
vector<cv::Point2f> featurePtSet0;
int maxNum = 10000;
goodFeaturesToTrack(img0Gray, featurePtSet0, maxNum, 0.05, 5);
cornerSubPix(img0Gray, featurePtSet0, cv::Size(15, 15), cv::Size(-1, -1), cvTermCriteria(CV_TERMCRIT_ITER | CV_TERMCRIT_EPS, 20, 0.03));
vector<cv::Point2f> curfeaturePtSet;
vector<uchar> curFlag;
vector<float> curErrSet;
calcOpticalFlowPyrLK(img0Gray, curImgGray, featurePtSet0, curfeaturePtSet, curFlag, curErrSet, cv::Size(15, 15));
for (int p = 0; p < curErrSet.size(); p++)
if (curErrSet[p] > 100 || curfeaturePtSet[p].x < 0 || curfeaturePtSet[p].y < 0 || curfeaturePtSet[p].x > img0Gray.cols || curfeaturePtSet[p].y > img0Gray.rows)
curFlag[p] = 0;
for (int i = 0; i<curFlag.size(); i++){
if (curFlag.at(i) == 1){
sourceFeatures.push_back(featurePtSet0.at(i));
targetFeatures.push_back(curfeaturePtSet.at(i));
}
}
}
|
#include "SoundContent.h"
#include "FatalError.h"
void SoundContent::Initialize()
{
BaseContent::Initialize();
}
bool SoundContent::Load(const std::string path)
{
alGenSources((ALuint)1, &mSoundId);
AlutError();
mSoundBuffer = alutCreateBufferFromFile(path.c_str());
AlutError();
alSourcei(mSoundId, AL_BUFFER, mSoundBuffer);
AlutError();
alSourcef(mSoundId, AL_PITCH, 1);
AlutError();
alSource3f(mSoundId, AL_POSITION, 0, 0, 0);
AlutError();
alSource3f(mSoundId, AL_VELOCITY, 0, 0, 0);
AlutError();
return true;
}
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 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 "txdb.h"
#include "walletdb.h"
#include "bitcoinrpc.h"
#include "net.h"
#include "init.h"
#include "util.h"
#include "ui_interface.h"
#include "checkpoints.h"
#include "zerocoin/ZeroTest.h"
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/filesystem/convenience.hpp>
#include <boost/interprocess/sync/file_lock.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <openssl/crypto.h>
#ifndef WIN32
#include <signal.h>
#endif
using namespace std;
using namespace boost;
CWallet* pwalletMain;
CClientUIInterface uiInterface;
bool fConfChange;
bool fEnforceCanonical;
unsigned int nNodeLifespan;
unsigned int nDerivationMethodIndex;
unsigned int nMinerSleep;
bool fUseFastIndex;
enum Checkpoints::CPMode CheckpointsMode;
//////////////////////////////////////////////////////////////////////////////
//
// Shutdown
//
void ExitTimeout(void* parg)
{
#ifdef WIN32
MilliSleep(5000);
ExitProcess(0);
#endif
}
void StartShutdown()
{
#ifdef QT_GUI
// ensure we leave the Qt main loop for a clean GUI exit (Shutdown() is called in bitcoin.cpp afterwards)
uiInterface.QueueShutdown();
#else
// Without UI, Shutdown() can simply be started in a new thread
NewThread(Shutdown, NULL);
#endif
}
void Shutdown(void* parg)
{
static CCriticalSection cs_Shutdown;
static bool fTaken;
// Make this thread recognisable as the shutdown thread
RenameThread("pay2c-shutoff");
bool fFirstThread = false;
{
TRY_LOCK(cs_Shutdown, lockShutdown);
if (lockShutdown)
{
fFirstThread = !fTaken;
fTaken = true;
}
}
static bool fExit;
if (fFirstThread)
{
fShutdown = true;
nTransactionsUpdated++;
// CTxDB().Close();
bitdb.Flush(false);
StopNode();
bitdb.Flush(true);
boost::filesystem::remove(GetPidFile());
UnregisterWallet(pwalletMain);
delete pwalletMain;
NewThread(ExitTimeout, NULL);
MilliSleep(50);
printf("Pay2c exited\n\n");
fExit = true;
#ifndef QT_GUI
// ensure non-UI client gets exited here, but let Bitcoin-Qt reach 'return 0;' in bitcoin.cpp
exit(0);
#endif
}
else
{
while (!fExit)
MilliSleep(500);
MilliSleep(100);
ExitThread(0);
}
}
void HandleSIGTERM(int)
{
fRequestShutdown = true;
}
void HandleSIGHUP(int)
{
fReopenDebugLog = true;
}
//////////////////////////////////////////////////////////////////////////////
//
// Start
//
#if !defined(QT_GUI)
bool AppInit(int argc, char* argv[])
{
bool fRet = false;
try
{
//
// Parameters
//
// If Qt is used, parameters/bitcoin.conf are parsed in qt/bitcoin.cpp's main()
ParseParameters(argc, argv);
if (!boost::filesystem::is_directory(GetDataDir(false)))
{
fprintf(stderr, "Error: Specified directory does not exist\n");
Shutdown(NULL);
}
ReadConfigFile(mapArgs, mapMultiArgs);
if (mapArgs.count("-?") || mapArgs.count("--help"))
{
// First part of help message is specific to bitcoind / RPC client
std::string strUsage = _("Pay2c version") + " " + FormatFullVersion() + "\n\n" +
_("Usage:") + "\n" +
" pay2cd [options] " + "\n" +
" pay2cd [options] <command> [params] " + _("Send command to -server or pay2cd") + "\n" +
" pay2cd [options] help " + _("List commands") + "\n" +
" pay2cd [options] help <command> " + _("Get help for a command") + "\n";
strUsage += "\n" + HelpMessage();
fprintf(stdout, "%s", strUsage.c_str());
return false;
}
// Command-line RPC
for (int i = 1; i < argc; i++)
if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], "pay2c:"))
fCommandLine = true;
if (fCommandLine)
{
int ret = CommandLineRPC(argc, argv);
exit(ret);
}
fRet = AppInit2();
}
catch (std::exception& e) {
PrintException(&e, "AppInit()");
} catch (...) {
PrintException(NULL, "AppInit()");
}
if (!fRet)
Shutdown(NULL);
return fRet;
}
extern void noui_connect();
int main(int argc, char* argv[])
{
bool fRet = false;
// Connect bitcoind signal handlers
noui_connect();
fRet = AppInit(argc, argv);
if (fRet && fDaemon)
return 0;
return 1;
}
#endif
bool static InitError(const std::string &str)
{
uiInterface.ThreadSafeMessageBox(str, _("Pay2c"), CClientUIInterface::OK | CClientUIInterface::MODAL);
return false;
}
bool static InitWarning(const std::string &str)
{
uiInterface.ThreadSafeMessageBox(str, _("Pay2c"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
return true;
}
bool static Bind(const CService &addr, bool fError = true) {
if (IsLimited(addr))
return false;
std::string strError;
if (!BindListenPort(addr, strError)) {
if (fError)
return InitError(strError);
return false;
}
return true;
}
// Core-specific options shared between UI and daemon
std::string HelpMessage()
{
string strUsage = _("Options:") + "\n" +
" -? " + _("This help message") + "\n" +
" -conf=<file> " + _("Specify configuration file (default: pay2c.conf)") + "\n" +
" -pid=<file> " + _("Specify pid file (default: pay2cd.pid)") + "\n" +
" -datadir=<dir> " + _("Specify data directory") + "\n" +
" -wallet=<dir> " + _("Specify wallet file (within data directory)") + "\n" +
" -dbcache=<n> " + _("Set database cache size in megabytes (default: 25)") + "\n" +
" -dblogsize=<n> " + _("Set database disk log size in megabytes (default: 100)") + "\n" +
" -timeout=<n> " + _("Specify connection timeout in milliseconds (default: 5000)") + "\n" +
" -proxy=<ip:port> " + _("Connect through socks proxy") + "\n" +
" -socks=<n> " + _("Select the version of socks proxy to use (4-5, default: 5)") + "\n" +
" -tor=<ip:port> " + _("Use proxy to reach tor hidden services (default: same as -proxy)") + "\n"
" -dns " + _("Allow DNS lookups for -addnode, -seednode and -connect") + "\n" +
" -port=<port> " + _("Listen for connections on <port> (default: 39527 or testnet: 49527)") + "\n" +
" -maxconnections=<n> " + _("Maintain at most <n> connections to peers (default: 125)") + "\n" +
" -addnode=<ip> " + _("Add a node to connect to and attempt to keep the connection open") + "\n" +
" -connect=<ip> " + _("Connect only to the specified node(s)") + "\n" +
" -seednode=<ip> " + _("Connect to a node to retrieve peer addresses, and disconnect") + "\n" +
" -externalip=<ip> " + _("Specify your own public address") + "\n" +
" -onlynet=<net> " + _("Only connect to nodes in network <net> (IPv4, IPv6 or Tor)") + "\n" +
" -discover " + _("Discover own IP address (default: 1 when listening and no -externalip)") + "\n" +
" -irc " + _("Find peers using internet relay chat (default: 0)") + "\n" +
" -listen " + _("Accept connections from outside (default: 1 if no -proxy or -connect)") + "\n" +
" -bind=<addr> " + _("Bind to given address. Use [host]:port notation for IPv6") + "\n" +
" -dnsseed " + _("Find peers using DNS lookup (default: 1)") + "\n" +
" -staking " + _("Stake your coins to support network and gain reward (default: 1)") + "\n" +
" -synctime " + _("Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)") + "\n" +
" -cppolicy " + _("Sync checkpoints policy (default: strict)") + "\n" +
" -banscore=<n> " + _("Threshold for disconnecting misbehaving peers (default: 100)") + "\n" +
" -bantime=<n> " + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)") + "\n" +
" -maxreceivebuffer=<n> " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)") + "\n" +
" -maxsendbuffer=<n> " + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)") + "\n" +
#ifdef USE_UPNP
#if USE_UPNP
" -upnp " + _("Use UPnP to map the listening port (default: 1 when listening)") + "\n" +
#else
" -upnp " + _("Use UPnP to map the listening port (default: 0)") + "\n" +
#endif
#endif
" -paytxfee=<amt> " + _("Fee per KB to add to transactions you send") + "\n" +
" -mininput=<amt> " + _("When creating transactions, ignore inputs with value less than this (default: 0.01)") + "\n" +
#ifdef QT_GUI
" -server " + _("Accept command line and JSON-RPC commands") + "\n" +
#endif
#if !defined(WIN32) && !defined(QT_GUI)
" -daemon " + _("Run in the background as a daemon and accept commands") + "\n" +
#endif
" -testnet " + _("Use the test network") + "\n" +
" -debug " + _("Output extra debugging information. Implies all other -debug* options") + "\n" +
" -debugnet " + _("Output extra network debugging information") + "\n" +
" -logtimestamps " + _("Prepend debug output with timestamp") + "\n" +
" -shrinkdebugfile " + _("Shrink debug.log file on client startup (default: 1 when no -debug)") + "\n" +
" -printtoconsole " + _("Send trace/debug info to console instead of debug.log file") + "\n" +
#ifdef WIN32
" -printtodebugger " + _("Send trace/debug info to debugger") + "\n" +
#endif
" -rpcuser=<user> " + _("Username for JSON-RPC connections") + "\n" +
" -rpcpassword=<pw> " + _("Password for JSON-RPC connections") + "\n" +
" -rpcport=<port> " + _("Listen for JSON-RPC connections on <port> (default: 39528 or testnet: 49528)") + "\n" +
" -rpcallowip=<ip> " + _("Allow JSON-RPC connections from specified IP address") + "\n" +
" -rpcconnect=<ip> " + _("Send commands to node running on <ip> (default: 127.0.0.1)") + "\n" +
" -blocknotify=<cmd> " + _("Execute command when the best block changes (%s in cmd is replaced by block hash)") + "\n" +
" -walletnotify=<cmd> " + _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)") + "\n" +
" -confchange " + _("Require a confirmations for change (default: 0)") + "\n" +
" -enforcecanonical " + _("Enforce transaction scripts to use canonical PUSH operators (default: 1)") + "\n" +
" -alertnotify=<cmd> " + _("Execute command when a relevant alert is received (%s in cmd is replaced by message)") + "\n" +
" -upgradewallet " + _("Upgrade wallet to latest format") + "\n" +
" -keypool=<n> " + _("Set key pool size to <n> (default: 100)") + "\n" +
" -rescan " + _("Rescan the block chain for missing wallet transactions") + "\n" +
" -salvagewallet " + _("Attempt to recover private keys from a corrupt wallet.dat") + "\n" +
" -checkblocks=<n> " + _("How many blocks to check at startup (default: 2500, 0 = all)") + "\n" +
" -checklevel=<n> " + _("How thorough the block verification is (0-6, default: 1)") + "\n" +
" -loadblock=<file> " + _("Imports blocks from external blk000?.dat file") + "\n" +
"\n" + _("Block creation options:") + "\n" +
" -blockminsize=<n> " + _("Set minimum block size in bytes (default: 0)") + "\n" +
" -blockmaxsize=<n> " + _("Set maximum block size in bytes (default: 250000)") + "\n" +
" -blockprioritysize=<n> " + _("Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)") + "\n" +
"\n" + _("SSL options: (see the Bitcoin Wiki for SSL setup instructions)") + "\n" +
" -rpcssl " + _("Use OpenSSL (https) for JSON-RPC connections") + "\n" +
" -rpcsslcertificatechainfile=<file.cert> " + _("Server certificate file (default: server.cert)") + "\n" +
" -rpcsslprivatekeyfile=<file.pem> " + _("Server private key (default: server.pem)") + "\n" +
" -rpcsslciphers=<ciphers> " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)") + "\n";
return strUsage;
}
/** Sanity checks
* Ensure that Bitcoin is running in a usable environment with all
* necessary library support.
*/
bool InitSanityCheck(void)
{
if(!ECC_InitSanityCheck()) {
InitError("OpenSSL appears to lack support for elliptic curve cryptography. For more "
"information, visit https://en.bitcoin.it/wiki/OpenSSL_and_EC_Libraries");
return false;
}
// TODO: remaining sanity checks, see #4081
return true;
}
/** Initialize bitcoin.
* @pre Parameters should be parsed and config file should be read.
*/
bool AppInit2()
{
// ********************************************************* Step 1: setup
#ifdef _MSC_VER
// Turn off Microsoft heap dump noise
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
#endif
#if _MSC_VER >= 1400
// Disable confusing "helpful" text message on abort, Ctrl-C
_set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
#endif
#ifdef WIN32
// Enable Data Execution Prevention (DEP)
// Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008
// A failure is non-critical and needs no further attention!
#ifndef PROCESS_DEP_ENABLE
// We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7),
// which is not correct. Can be removed, when GCCs winbase.h is fixed!
#define PROCESS_DEP_ENABLE 0x00000001
#endif
typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD);
PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy");
if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE);
#endif
#ifndef WIN32
umask(077);
// Clean shutdown on SIGTERM
struct sigaction sa;
sa.sa_handler = HandleSIGTERM;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sigaction(SIGTERM, &sa, NULL);
sigaction(SIGINT, &sa, NULL);
// Reopen debug.log on SIGHUP
struct sigaction sa_hup;
sa_hup.sa_handler = HandleSIGHUP;
sigemptyset(&sa_hup.sa_mask);
sa_hup.sa_flags = 0;
sigaction(SIGHUP, &sa_hup, NULL);
#endif
// ********************************************************* Step 2: parameter interactions
nNodeLifespan = GetArg("-addrlifespan", 7);
fUseFastIndex = GetBoolArg("-fastindex", true);
nMinerSleep = GetArg("-minersleep", 500);
CheckpointsMode = Checkpoints::STRICT;
std::string strCpMode = GetArg("-cppolicy", "strict");
if(strCpMode == "strict")
CheckpointsMode = Checkpoints::STRICT;
if(strCpMode == "advisory")
CheckpointsMode = Checkpoints::ADVISORY;
if(strCpMode == "permissive")
CheckpointsMode = Checkpoints::PERMISSIVE;
nDerivationMethodIndex = 0;
fTestNet = GetBoolArg("-testnet");
if (fTestNet) {
SoftSetBoolArg("-irc", true);
}
if (mapArgs.count("-bind")) {
// when specifying an explicit binding address, you want to listen on it
// even when -connect or -proxy is specified
SoftSetBoolArg("-listen", true);
}
if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) {
// when only connecting to trusted nodes, do not seed via DNS, or listen by default
SoftSetBoolArg("-dnsseed", false);
SoftSetBoolArg("-listen", false);
}
if (mapArgs.count("-proxy")) {
// to protect privacy, do not listen by default if a proxy server is specified
SoftSetBoolArg("-listen", false);
}
if (!GetBoolArg("-listen", true)) {
// do not map ports or try to retrieve public IP when not listening (pointless)
SoftSetBoolArg("-upnp", false);
SoftSetBoolArg("-discover", false);
}
if (mapArgs.count("-externalip")) {
// if an explicit public IP is specified, do not try to find others
SoftSetBoolArg("-discover", false);
}
if (GetBoolArg("-salvagewallet")) {
// Rewrite just private keys: rescan to find transactions
SoftSetBoolArg("-rescan", true);
}
// ********************************************************* Step 3: parameter-to-internal-flags
fDebug = GetBoolArg("-debug");
// -debug implies fDebug*
if (fDebug)
fDebugNet = true;
else
fDebugNet = GetBoolArg("-debugnet");
#if !defined(WIN32) && !defined(QT_GUI)
fDaemon = GetBoolArg("-daemon");
#else
fDaemon = false;
#endif
if (fDaemon)
fServer = true;
else
fServer = GetBoolArg("-server");
/* force fServer when running without GUI */
#if !defined(QT_GUI)
fServer = true;
#endif
fPrintToConsole = GetBoolArg("-printtoconsole");
fPrintToDebugger = GetBoolArg("-printtodebugger");
fLogTimestamps = GetBoolArg("-logtimestamps");
if (mapArgs.count("-timeout"))
{
int nNewTimeout = GetArg("-timeout", 5000);
if (nNewTimeout > 0 && nNewTimeout < 600000)
nConnectTimeout = nNewTimeout;
}
if (mapArgs.count("-paytxfee"))
{
if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s'"), mapArgs["-paytxfee"].c_str()));
if (nTransactionFee > 0.25 * COIN)
InitWarning(_("Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction."));
}
fConfChange = GetBoolArg("-confchange", false);
fEnforceCanonical = GetBoolArg("-enforcecanonical", true);
if (mapArgs.count("-mininput"))
{
if (!ParseMoney(mapArgs["-mininput"], nMinimumInputValue))
return InitError(strprintf(_("Invalid amount for -mininput=<amount>: '%s'"), mapArgs["-mininput"].c_str()));
}
// ********************************************************* Step 4: application initialization: dir lock, daemonize, pidfile, debug log
// Sanity check
if (!InitSanityCheck())
return InitError(_("Initialization sanity check failed. Pay2c is shutting down."));
std::string strDataDir = GetDataDir().string();
std::string strWalletFileName = GetArg("-wallet", "wallet.dat");
// strWalletFileName must be a plain filename without a directory
if (strWalletFileName != boost::filesystem::basename(strWalletFileName) + boost::filesystem::extension(strWalletFileName))
return InitError(strprintf(_("Wallet %s resides outside data directory %s."), strWalletFileName.c_str(), strDataDir.c_str()));
// Make sure only a single Bitcoin process is using the data directory.
boost::filesystem::path pathLockFile = GetDataDir() / ".lock";
FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist.
if (file) fclose(file);
static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
if (!lock.try_lock())
return InitError(strprintf(_("Cannot obtain a lock on data directory %s. Pay2c is probably already running."), strDataDir.c_str()));
#if !defined(WIN32) && !defined(QT_GUI)
if (fDaemon)
{
// Daemonize
pid_t pid = fork();
if (pid < 0)
{
fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
return false;
}
if (pid > 0)
{
CreatePidFile(GetPidFile(), pid);
return true;
}
pid_t sid = setsid();
if (sid < 0)
fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
}
#endif
if (GetBoolArg("-shrinkdebugfile", !fDebug))
ShrinkDebugFile();
printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
printf("Pay2c version %s (%s)\n", FormatFullVersion().c_str(), CLIENT_DATE.c_str());
printf("Using OpenSSL version %s\n", SSLeay_version(SSLEAY_VERSION));
if (!fLogTimestamps)
printf("Startup time: %s\n", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
printf("Default data directory %s\n", GetDefaultDataDir().string().c_str());
printf("Used data directory %s\n", strDataDir.c_str());
std::ostringstream strErrors;
if (fDaemon)
fprintf(stdout, "Pay2c server starting\n");
int64_t nStart;
// ********************************************************* Step 5: verify database integrity
uiInterface.InitMessage(_("Verifying database integrity..."));
if (!bitdb.Open(GetDataDir()))
{
string msg = strprintf(_("Error initializing database environment %s!"
" To recover, BACKUP THAT DIRECTORY, then remove"
" everything from it except for wallet.dat."), strDataDir.c_str());
return InitError(msg);
}
if (GetBoolArg("-salvagewallet"))
{
// Recover readable keypairs:
if (!CWalletDB::Recover(bitdb, strWalletFileName, true))
return false;
}
if (filesystem::exists(GetDataDir() / strWalletFileName))
{
CDBEnv::VerifyResult r = bitdb.Verify(strWalletFileName, CWalletDB::Recover);
if (r == CDBEnv::RECOVER_OK)
{
string msg = strprintf(_("Warning: wallet.dat corrupt, data salvaged!"
" Original wallet.dat saved as wallet.{timestamp}.bak in %s; if"
" your balance or transactions are incorrect you should"
" restore from a backup."), strDataDir.c_str());
uiInterface.ThreadSafeMessageBox(msg, _("Pay2c"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
}
if (r == CDBEnv::RECOVER_FAIL)
return InitError(_("wallet.dat corrupt, salvage failed"));
}
// ********************************************************* Step 6: network initialization
int nSocksVersion = GetArg("-socks", 5);
if (nSocksVersion != 4 && nSocksVersion != 5)
return InitError(strprintf(_("Unknown -socks proxy version requested: %i"), nSocksVersion));
if (mapArgs.count("-onlynet")) {
std::set<enum Network> nets;
BOOST_FOREACH(std::string snet, mapMultiArgs["-onlynet"]) {
enum Network net = ParseNetwork(snet);
if (net == NET_UNROUTABLE)
return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet.c_str()));
nets.insert(net);
}
for (int n = 0; n < NET_MAX; n++) {
enum Network net = (enum Network)n;
if (!nets.count(net))
SetLimited(net);
}
}
CService addrProxy;
bool fProxy = false;
if (mapArgs.count("-proxy")) {
addrProxy = CService(mapArgs["-proxy"], 9050);
if (!addrProxy.IsValid())
return InitError(strprintf(_("Invalid -proxy address: '%s'"), mapArgs["-proxy"].c_str()));
if (!IsLimited(NET_IPV4))
SetProxy(NET_IPV4, addrProxy, nSocksVersion);
if (nSocksVersion > 4) {
if (!IsLimited(NET_IPV6))
SetProxy(NET_IPV6, addrProxy, nSocksVersion);
SetNameProxy(addrProxy, nSocksVersion);
}
fProxy = true;
}
// -tor can override normal proxy, -notor disables tor entirely
if (!(mapArgs.count("-tor") && mapArgs["-tor"] == "0") && (fProxy || mapArgs.count("-tor"))) {
CService addrOnion;
if (!mapArgs.count("-tor"))
addrOnion = addrProxy;
else
addrOnion = CService(mapArgs["-tor"], 9050);
if (!addrOnion.IsValid())
return InitError(strprintf(_("Invalid -tor address: '%s'"), mapArgs["-tor"].c_str()));
SetProxy(NET_TOR, addrOnion, 5);
SetReachable(NET_TOR);
}
// see Step 2: parameter interactions for more information about these
fNoListen = !GetBoolArg("-listen", true);
fDiscover = GetBoolArg("-discover", true);
fNameLookup = GetBoolArg("-dns", true);
#ifdef USE_UPNP
fUseUPnP = GetBoolArg("-upnp", USE_UPNP);
#endif
bool fBound = false;
if (!fNoListen)
{
std::string strError;
if (mapArgs.count("-bind")) {
BOOST_FOREACH(std::string strBind, mapMultiArgs["-bind"]) {
CService addrBind;
if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false))
return InitError(strprintf(_("Cannot resolve -bind address: '%s'"), strBind.c_str()));
fBound |= Bind(addrBind);
}
} else {
struct in_addr inaddr_any;
inaddr_any.s_addr = INADDR_ANY;
if (!IsLimited(NET_IPV6))
fBound |= Bind(CService(in6addr_any, GetListenPort()), false);
if (!IsLimited(NET_IPV4))
fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound);
}
if (!fBound)
return InitError(_("Failed to listen on any port. Use -listen=0 if you want this."));
}
if (mapArgs.count("-externalip"))
{
BOOST_FOREACH(string strAddr, mapMultiArgs["-externalip"]) {
CService addrLocal(strAddr, GetListenPort(), fNameLookup);
if (!addrLocal.IsValid())
return InitError(strprintf(_("Cannot resolve -externalip address: '%s'"), strAddr.c_str()));
AddLocal(CService(strAddr, GetListenPort(), fNameLookup), LOCAL_MANUAL);
}
}
if (mapArgs.count("-reservebalance")) // ppcoin: reserve balance amount
{
if (!ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
{
InitError(_("Invalid amount for -reservebalance=<amount>"));
return false;
}
}
if (mapArgs.count("-checkpointkey")) // ppcoin: checkpoint master priv key
{
if (!Checkpoints::SetCheckpointPrivKey(GetArg("-checkpointkey", "")))
InitError(_("Unable to sign checkpoint, wrong checkpointkey?\n"));
}
BOOST_FOREACH(string strDest, mapMultiArgs["-seednode"])
AddOneShot(strDest);
// ********************************************************* Step 7: load blockchain
if (!bitdb.Open(GetDataDir()))
{
string msg = strprintf(_("Error initializing database environment %s!"
" To recover, BACKUP THAT DIRECTORY, then remove"
" everything from it except for wallet.dat."), strDataDir.c_str());
return InitError(msg);
}
if (GetBoolArg("-loadblockindextest"))
{
CTxDB txdb("r");
txdb.LoadBlockIndex();
PrintBlockTree();
return false;
}
uiInterface.InitMessage(_("Loading block index..."));
printf("Loading block index...\n");
nStart = GetTimeMillis();
if (!LoadBlockIndex())
return InitError(_("Error loading blkindex.dat"));
// as LoadBlockIndex can take several minutes, it's possible the user
// requested to kill bitcoin-qt during the last operation. If so, exit.
// As the program has not fully started yet, Shutdown() is possibly overkill.
if (fRequestShutdown)
{
printf("Shutdown requested. Exiting.\n");
return false;
}
printf(" block index %15"PRId64"ms\n", GetTimeMillis() - nStart);
if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
{
PrintBlockTree();
return false;
}
if (mapArgs.count("-printblock"))
{
string strMatch = mapArgs["-printblock"];
int nFound = 0;
for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
{
uint256 hash = (*mi).first;
if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
{
CBlockIndex* pindex = (*mi).second;
CBlock block;
block.ReadFromDisk(pindex);
block.BuildMerkleTree();
block.print();
printf("\n");
nFound++;
}
}
if (nFound == 0)
printf("No blocks matching %s were found\n", strMatch.c_str());
return false;
}
// ********************************************************* Testing Zerocoin
if (GetBoolArg("-zerotest", false))
{
printf("\n=== ZeroCoin tests start ===\n");
Test_RunAllTests();
printf("=== ZeroCoin tests end ===\n\n");
}
// ********************************************************* Step 8: load wallet
uiInterface.InitMessage(_("Loading wallet..."));
printf("Loading wallet...\n");
nStart = GetTimeMillis();
bool fFirstRun = true;
pwalletMain = new CWallet(strWalletFileName);
DBErrors nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
if (nLoadWalletRet != DB_LOAD_OK)
{
if (nLoadWalletRet == DB_CORRUPT)
strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
{
string msg(_("Warning: error reading wallet.dat! All keys read correctly, but transaction data"
" or address book entries might be missing or incorrect."));
uiInterface.ThreadSafeMessageBox(msg, _("Pay2c"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
}
else if (nLoadWalletRet == DB_TOO_NEW)
strErrors << _("Error loading wallet.dat: Wallet requires newer version of Pay2c") << "\n";
else if (nLoadWalletRet == DB_NEED_REWRITE)
{
strErrors << _("Wallet needed to be rewritten: restart Pay2c to complete") << "\n";
printf("%s", strErrors.str().c_str());
return InitError(strErrors.str());
}
else
strErrors << _("Error loading wallet.dat") << "\n";
}
if (GetBoolArg("-upgradewallet", fFirstRun))
{
int nMaxVersion = GetArg("-upgradewallet", 0);
if (nMaxVersion == 0) // the -upgradewallet without argument case
{
printf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
nMaxVersion = CLIENT_VERSION;
pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
}
else
printf("Allowing wallet upgrade up to %i\n", nMaxVersion);
if (nMaxVersion < pwalletMain->GetVersion())
strErrors << _("Cannot downgrade wallet") << "\n";
pwalletMain->SetMaxVersion(nMaxVersion);
}
if (fFirstRun)
{
// Create new keyUser and set as default key
RandAddSeedPerfmon();
CPubKey newDefaultKey;
if (pwalletMain->GetKeyFromPool(newDefaultKey, false)) {
pwalletMain->SetDefaultKey(newDefaultKey);
if (!pwalletMain->SetAddressBookName(pwalletMain->vchDefaultKey.GetID(), ""))
strErrors << _("Cannot write default address") << "\n";
}
}
printf("%s", strErrors.str().c_str());
printf(" wallet %15"PRId64"ms\n", GetTimeMillis() - nStart);
RegisterWallet(pwalletMain);
CBlockIndex *pindexRescan = pindexBest;
if (GetBoolArg("-rescan"))
pindexRescan = pindexGenesisBlock;
else
{
CWalletDB walletdb(strWalletFileName);
CBlockLocator locator;
if (walletdb.ReadBestBlock(locator))
pindexRescan = locator.GetBlockIndex();
}
if (pindexBest != pindexRescan && pindexBest && pindexRescan && pindexBest->nHeight > pindexRescan->nHeight)
{
uiInterface.InitMessage(_("Rescanning..."));
printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
nStart = GetTimeMillis();
pwalletMain->ScanForWalletTransactions(pindexRescan, true);
printf(" rescan %15"PRId64"ms\n", GetTimeMillis() - nStart);
}
// ********************************************************* Step 9: import blocks
if (mapArgs.count("-loadblock"))
{
uiInterface.InitMessage(_("Importing blockchain data file."));
BOOST_FOREACH(string strFile, mapMultiArgs["-loadblock"])
{
FILE *file = fopen(strFile.c_str(), "rb");
if (file)
LoadExternalBlockFile(file);
}
exit(0);
}
filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat";
if (filesystem::exists(pathBootstrap)) {
uiInterface.InitMessage(_("Importing bootstrap blockchain data file."));
FILE *file = fopen(pathBootstrap.string().c_str(), "rb");
if (file) {
filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
LoadExternalBlockFile(file);
RenameOver(pathBootstrap, pathBootstrapOld);
}
}
// ********************************************************* Step 10: load peers
uiInterface.InitMessage(_("Loading addresses..."));
printf("Loading addresses...\n");
nStart = GetTimeMillis();
{
CAddrDB adb;
if (!adb.Read(addrman))
printf("Invalid or missing peers.dat; recreating\n");
}
printf("Loaded %i addresses from peers.dat %"PRId64"ms\n",
addrman.size(), GetTimeMillis() - nStart);
// ********************************************************* Step 11: start node
if (!CheckDiskSpace())
return false;
RandAddSeedPerfmon();
//// debug print
printf("mapBlockIndex.size() = %"PRIszu"\n", mapBlockIndex.size());
printf("nBestHeight = %d\n", nBestHeight);
printf("setKeyPool.size() = %"PRIszu"\n", pwalletMain->setKeyPool.size());
printf("mapWallet.size() = %"PRIszu"\n", pwalletMain->mapWallet.size());
printf("mapAddressBook.size() = %"PRIszu"\n", pwalletMain->mapAddressBook.size());
if (!NewThread(StartNode, NULL))
InitError(_("Error: could not start node"));
if (fServer)
NewThread(ThreadRPCServer, NULL);
// ********************************************************* Step 12: finished
uiInterface.InitMessage(_("Done loading"));
printf("Done loading\n");
if (!strErrors.str().empty())
return InitError(strErrors.str());
// Add wallet transactions that aren't already in a block to mapTransactions
pwalletMain->ReacceptWalletTransactions();
#if !defined(QT_GUI)
// Loop until process is exit()ed from shutdown() function,
// called from ThreadRPCServer thread when a "stop" command is received.
while (1)
MilliSleep(5000);
#endif
return true;
}
|
#include "ui/graphics/light.hpp"
#include <SDL2/SDL2_gfxPrimitives.h>
#include "main.hpp"
void light(int power, int x, int y, int r, int g, int b){
for (int i=0; i<power; i+=5){
if (i > power / 3){
filledCircleRGBA(RENDERER, x, y, i, r, g, b, 10);
}
}
}
void projectedLight(int angle, int range, int x, int y, int r, int g, int b, int a, int radius){
for (int i=0; i<range/2; i++){
int rx, ry;
setAngleM(&rx, &ry, radius, i+angle+(range/2));
int lx, ly;
setAngleM(&lx, &ly, radius, i+angle-(range));
filledTrigonRGBA(RENDERER, x, y, rx+x, ry+y, lx+x, ly+y, r, g, b, a);
}
}
Light_type::Light_type(){
if (IS_LOG_OPEN) LOG << "Light_type::Light_type()" << endl;
texture = NULL;
}
Light_type::~Light_type(){
if (IS_LOG_OPEN) LOG << "~Light_type::Light_type()" << endl;
if (texture) SDL_DestroyTexture(texture);
}
bool Light_type::load(XMLNode* node){
if (IS_LOG_OPEN) LOG << "Light_type::load()";
if (!node){
if (IS_ERR_OPEN) ERR << "ERROR :: Light_type::load, reason : cannot load a light type from a null xml node" << endl;
if (IS_LOG_OPEN) LOG << endl;
return false;
}
for (int a=0; a<node->attributes.size; a++){
XMLAttribute attr = node->attributes.data[a];
if (!strcmp(attr.key, "name")){
name = attr.value;
if (IS_LOG_OPEN) LOG << " : '" << name << "'" << endl;
} else {
if (IS_ERR_OPEN) ERR << "WARNING :: light, reason : cannot reconize '" << attr.value << " light attribute" << endl;
}
}
for (int c=0; c<node->children.size; c++){
XMLNode* child = XMLNode_child(node, c);
if (!strcmp(child->tag, "texture")){
for (int a=0; a<child->attributes.size; a++){
XMLAttribute attr = child->attributes.data[a];
if (!strcmp(attr.key, "path")){
texture = loadTexture(attr.value, &size);
} else if (!strcmp(attr.key, "w")){
sscanf(attr.value, "%d", &size.w);
} else if (!strcmp(attr.key, "h")){
sscanf(attr.value, "%d", &size.h);
} else {
if (IS_ERR_OPEN) ERR << "WARNING :: light, texture, reason : cannot reconize '" << attr.key << "' texture attribute" << endl;
}
}
center.x = size.w / 2;
center.y = size.h / 2;
} else if (!strcmp(child->tag, "center")){
for (int a=0; a<child->attributes.size; a++){
XMLAttribute attr = child->attributes.data[a];
if (!strcmp(attr.key, "x")){
sscanf(attr.value, "%d", ¢er.x);
} else if (!strcmp(attr.key, "y")){
sscanf(attr.value, "%d", ¢er.y);
} else {
if (IS_ERR_OPEN) ERR << "WARNING :: light, center, reason : cannot reconize '" << attr.key << "' center attribute" << endl;
}
}
} else {
if (IS_ERR_OPEN) ERR << "WARNING :: light, reason : cannot reconize '" << child->tag << "' light attribute" << endl;
}
}
return true;
}
string Light_type::getName(void){
return name;
}
SDL_Rect Light_type::getSize(void){
return size;
}
SDL_Texture* Light_type::getTexture(void){
return texture;
}
SDL_Point* Light_type::getCenter(void){
return ¢er;
}
Light::Light(){
type = nullptr;
angle = 0;
}
Light::~Light(){
type = nullptr;
}
bool Light::set(string name){
type = searchLight(name);
if (!type){
if (IS_ERR_OPEN) ERR << "ERROR :: cannot found, '" << name << "' light name" << endl;
return false;
}
resetSize();
return true;
}
bool Light::draw(int z){
if (!type) return false;
if (z != this->z) return true;
SDL_Rect rect = {this->rect.x - type->getCenter()->x, this->rect.y - type->getCenter()->y, this->rect.w, this->rect.h};
if (SDL_RenderCopyEx(RENDERER, type->getTexture(), NULL, &rect, angle, type->getCenter(), SDL_FLIP_NONE)){
if (IS_ERR_OPEN) ERR << "ERROR :: SDL_RenderCopyEX, reason : " << SDL_GetError() << endl;
return false;
}
return true;
}
void Light::setPos(int x, int y){
rect.x = x;
rect.y = y;
}
void Light::setSize(int w, int h){
rect.w = w;
rect.h = h;
}
void Light::resetSize(void){
if (!type) return;
rect.w = type->getSize().w;
rect.h = type->getSize().h;
}
void Light::setAngle(int angle){
this->angle = angle;
}
void Light::setZ(int z){
this->z = z;
}
Light_type* searchLight(string name){
for (Light_type* t : LIGHT_TYPES){
if (t->getName() == name){
return t;
}
}
return nullptr;
}
void pushLight_type(XMLNode* node){
Light_type* type = new Light_type();
if (type->load(node)){
LIGHT_TYPES.push_back(type);
} else {
delete type;
}
}
void clearLights(void){
for (Light_type* type : LIGHT_TYPES){
delete type;
}
LIGHT_TYPES.clear();
}
Light* newLight(void){
return new Light();
}
|
/******************************************************************************
*
* Project: PlanetLabs scene driver
* Purpose: Implements OGRPLScenesDataV1Layer
* Author: Even Rouault, even dot rouault at spatialys.com
*
******************************************************************************
* Copyright (c) 2017, Planet Labs
*
* 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_plscenes.h"
#include "ogrgeojsonreader.h"
#include <algorithm>
CPL_CVSID("$Id: ogrplscenesdatav1layer.cpp 6659c4d5c910df313ac451cd5ca687862eef040b 2020-10-01 15:37:53 +0200 Even Rouault $")
/************************************************************************/
/* GetFieldCount() */
/************************************************************************/
int OGRPLScenesDataV1FeatureDefn::GetFieldCount() const
{
if( nFieldCount == 0 && m_poLayer != nullptr )
m_poLayer->EstablishLayerDefn();
return nFieldCount;
}
/************************************************************************/
/* OGRPLScenesDataV1Layer() */
/************************************************************************/
OGRPLScenesDataV1Layer::OGRPLScenesDataV1Layer( OGRPLScenesDataV1Dataset* poDS,
const char* pszName ) :
m_poDS(poDS),
m_bFeatureDefnEstablished(false),
m_poSRS(new OGRSpatialReference(SRS_WKT_WGS84_LAT_LONG)),
m_nTotalFeatures(-1),
m_nNextFID(1),
m_bEOF(false),
m_bStillInFirstPage(true),
m_nPageSize(atoi(CPLGetConfigOption("PLSCENES_PAGE_SIZE", "250"))),
m_bInFeatureCountOrGetExtent(false),
m_poPageObj(nullptr),
m_poFeatures(nullptr),
m_nFeatureIdx(0),
m_poAttributeFilter(nullptr),
m_bFilterMustBeClientSideEvaluated(false)
{
m_poSRS->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
// Cannot be moved to initializer list because of use of this, which MSVC 2008 doesn't like
m_poFeatureDefn = new OGRPLScenesDataV1FeatureDefn(this, pszName);
SetDescription(pszName);
m_poFeatureDefn->SetGeomType(wkbMultiPolygon);
m_poFeatureDefn->Reference();
m_poFeatureDefn->GetGeomFieldDefn(0)->SetSpatialRef(m_poSRS);
OGRPLScenesDataV1Layer::ResetReading();
}
/************************************************************************/
/* ~OGRPLScenesDataV1Layer() */
/************************************************************************/
OGRPLScenesDataV1Layer::~OGRPLScenesDataV1Layer()
{
m_poFeatureDefn->DropRefToLayer();
m_poFeatureDefn->Release();
m_poSRS->Release();
if( m_poPageObj != nullptr )
json_object_put(m_poPageObj);
if( m_poAttributeFilter != nullptr )
json_object_put(m_poAttributeFilter);
}
/************************************************************************/
/* GetLayerDefn() */
/************************************************************************/
OGRFeatureDefn* OGRPLScenesDataV1Layer::GetLayerDefn()
{
return m_poFeatureDefn;
}
/************************************************************************/
/* RegisterField() */
/************************************************************************/
void OGRPLScenesDataV1Layer::RegisterField(OGRFieldDefn* poFieldDefn,
const char* pszQueriableJSonName,
const char* pszPrefixedJSonName)
{
const int nIdx = m_poFeatureDefn->GetFieldCount();
m_oMapPrefixedJSonFieldNameToFieldIdx[pszPrefixedJSonName] = nIdx;
if( pszQueriableJSonName )
{
m_oMapFieldIdxToQueriableJSonFieldName[nIdx] = pszQueriableJSonName;
}
m_poFeatureDefn->AddFieldDefn(poFieldDefn);
}
/************************************************************************/
/* EstablishLayerDefn() */
/************************************************************************/
void OGRPLScenesDataV1Layer::EstablishLayerDefn()
{
if( m_bFeatureDefnEstablished )
return;
m_bFeatureDefnEstablished = true;
const char* pszConfFile = CPLFindFile("gdal", "plscenesconf.json");
if( pszConfFile == nullptr )
{
CPLError(CE_Failure, CPLE_AppDefined, "Cannot find plscenesconf.json");
return;
}
GByte* pabyRet = nullptr;
if( !VSIIngestFile( nullptr, pszConfFile, &pabyRet, nullptr, -1 ) )
{
return;
}
json_object* poRoot = nullptr;
const char* pzText = reinterpret_cast<char*>(pabyRet);
if( !OGRJSonParse( pzText, &poRoot ) )
{
VSIFree(pabyRet);
return;
}
VSIFree(pabyRet);
json_object* poV1Data = CPL_json_object_object_get(poRoot, "v1_data");
if( poV1Data == nullptr || json_object_get_type(poV1Data) != json_type_object )
{
CPLError(CE_Failure, CPLE_AppDefined,
"Cannot find v1_data object in plscenesconf.json");
json_object_put(poRoot);
return;
}
json_object* poItemType = CPL_json_object_object_get(poV1Data,
GetDescription());
if( poItemType == nullptr ||
json_object_get_type(poItemType) != json_type_object )
{
CPLError(CE_Failure, CPLE_AppDefined,
"Cannot find v1_data.%s object in plscenesconf.json",
GetDescription());
json_object_put(poRoot);
return;
}
json_object* poFields = CPL_json_object_object_get(poItemType, "fields");
if( poFields == nullptr ||
json_object_get_type(poFields) != json_type_array )
{
CPLError(CE_Failure, CPLE_AppDefined,
"Cannot find v1_data.%s.fields object in plscenesconf.json",
GetDescription());
json_object_put(poRoot);
return;
}
{
OGRFieldDefn oFieldDefn("id", OFTString);
RegisterField(&oFieldDefn, "id", "id");
}
const auto nFields = json_object_array_length(poFields);
for( auto i=decltype(nFields){0}; i<nFields; i++ )
{
json_object* poField = json_object_array_get_idx(poFields, i);
if( poField && json_object_get_type(poField) == json_type_object )
{
json_object* poName = CPL_json_object_object_get(poField, "name");
json_object* poType = CPL_json_object_object_get(poField, "type");
if( poName && json_object_get_type(poName) == json_type_string &&
poType && json_object_get_type(poType) == json_type_string )
{
const char* pszName = json_object_get_string(poName);
const char* pszType = json_object_get_string(poType);
OGRFieldType eType(OFTString);
OGRFieldSubType eSubType(OFSTNone);
if( EQUAL(pszType, "datetime") )
eType = OFTDateTime;
else if( EQUAL(pszType, "double") )
eType = OFTReal;
else if( EQUAL(pszType, "int") )
eType = OFTInteger;
else if( EQUAL(pszType, "string") )
eType = OFTString;
else if( EQUAL(pszType, "boolean") )
{
eType = OFTInteger;
eSubType = OFSTBoolean;
}
else
{
CPLError(CE_Warning, CPLE_AppDefined,
"Unrecognized field type %s for field %s",
pszType, pszName);
}
OGRFieldDefn oFieldDefn(pszName, eType);
oFieldDefn.SetSubType(eSubType);
RegisterField(&oFieldDefn, pszName,
(CPLString("properties.") + pszName).c_str());
}
}
}
{
OGRFieldDefn oFieldDefn("self_link", OFTString);
RegisterField(&oFieldDefn, nullptr, "_links._self");
}
{
OGRFieldDefn oFieldDefn("assets_link", OFTString);
RegisterField(&oFieldDefn, nullptr, "_links.assets");
}
{
OGRFieldDefn oFieldDefn("permissions", OFTStringList);
RegisterField(&oFieldDefn, nullptr, "_permissions");
}
if( m_poDS->DoesFollowLinks() )
{
json_object* poAssets = CPL_json_object_object_get(poItemType, "assets");
if( poAssets == nullptr ||
json_object_get_type(poAssets) != json_type_array )
{
CPLError(CE_Failure, CPLE_AppDefined,
"Cannot find v1_data.%s.assets object in plscenesconf.json",
GetDescription());
json_object_put(poRoot);
return;
}
const auto nAssets = json_object_array_length(poAssets);
for( auto i=decltype(nAssets){0}; i<nAssets; i++ )
{
json_object* poAsset = json_object_array_get_idx(poAssets, i);
if( poAsset && json_object_get_type(poAsset) == json_type_string )
{
const char* pszAsset = json_object_get_string(poAsset);
m_oSetAssets.insert(pszAsset);
{
CPLString osName("asset_");
osName += pszAsset;
osName += "_self_link";
OGRFieldDefn oFieldDefn(osName, OFTString);
RegisterField(&oFieldDefn, nullptr,
CPLSPrintf("/assets.%s._links._self", pszAsset));
}
{
CPLString osName("asset_");
osName += pszAsset;
osName += "_activate_link";
OGRFieldDefn oFieldDefn(osName, OFTString);
RegisterField(&oFieldDefn, nullptr,
CPLSPrintf("/assets.%s._links.activate", pszAsset));
}
{
CPLString osName("asset_");
osName += pszAsset;
osName += "_permissions";
OGRFieldDefn oFieldDefn(osName, OFTStringList);
RegisterField(&oFieldDefn, nullptr,
CPLSPrintf("/assets.%s._permissions", pszAsset));
}
{
CPLString osName("asset_");
osName += pszAsset;
osName += "_expires_at";
OGRFieldDefn oFieldDefn(osName, OFTDateTime);
RegisterField(&oFieldDefn, nullptr,
CPLSPrintf("/assets.%s.expires_at", pszAsset));
}
{
CPLString osName("asset_");
osName += pszAsset;
osName += "_location";
OGRFieldDefn oFieldDefn(osName, OFTString);
RegisterField(&oFieldDefn, nullptr,
CPLSPrintf("/assets.%s.location", pszAsset));
}
{
CPLString osName("asset_");
osName += pszAsset;
osName += "_status";
OGRFieldDefn oFieldDefn(osName, OFTString);
RegisterField(&oFieldDefn, nullptr,
CPLSPrintf("/assets.%s.status", pszAsset));
}
}
}
}
json_object_put(poRoot);
}
/************************************************************************/
/* GetMetadata() */
/************************************************************************/
char **OGRPLScenesDataV1Layer::GetMetadata( const char * pszDomain )
{
if( pszDomain == nullptr || EQUAL(pszDomain, "") )
{
EstablishLayerDefn();
}
return OGRLayer::GetMetadata(pszDomain);
}
/************************************************************************/
/* GetMetadataItem() */
/************************************************************************/
const char *OGRPLScenesDataV1Layer::GetMetadataItem( const char * pszName, const char* pszDomain )
{
if( pszDomain == nullptr || EQUAL(pszDomain, "") )
{
EstablishLayerDefn();
}
return OGRLayer::GetMetadataItem(pszName, pszDomain);
}
/************************************************************************/
/* GetNextPage() */
/************************************************************************/
bool OGRPLScenesDataV1Layer::GetNextPage()
{
if( m_poPageObj != nullptr )
json_object_put(m_poPageObj);
m_poPageObj = nullptr;
m_poFeatures = nullptr;
m_nFeatureIdx = 0;
if( m_osRequestURL.empty() )
{
m_bEOF = true;
return false;
}
json_object* poObj;
if (m_osRequestURL.find(m_poDS->GetBaseURL() + "quick-search?_page_size") == 0 )
{
CPLString osFilter(m_poDS->GetFilter());
if( osFilter.empty() )
{
json_object* poFilterRoot = json_object_new_object();
json_object* poItemTypes = json_object_new_array();
json_object_array_add(poItemTypes,
json_object_new_string(GetName()));
json_object_object_add(poFilterRoot, "item_types", poItemTypes);
json_object* poFilter = json_object_new_object();
json_object_object_add(poFilterRoot, "filter", poFilter);
json_object_object_add(poFilter, "type",
json_object_new_string("AndFilter"));
json_object* poConfig = json_object_new_array();
json_object_object_add(poFilter, "config", poConfig);
if( m_poFilterGeom != nullptr )
{
json_object* poGeomFilter = json_object_new_object();
json_object_array_add(poConfig, poGeomFilter);
json_object_object_add(poGeomFilter, "type",
json_object_new_string("GeometryFilter"));
json_object_object_add(poGeomFilter, "field_name",
json_object_new_string("geometry"));
OGRGeoJSONWriteOptions oOptions;
json_object* poGeoJSONGeom =
OGRGeoJSONWriteGeometry( m_poFilterGeom, oOptions );
json_object_object_add(poGeomFilter, "config",
poGeoJSONGeom);
}
if( m_poAttributeFilter != nullptr )
{
json_object_get(m_poAttributeFilter);
json_object_array_add(poConfig, m_poAttributeFilter);
}
osFilter = json_object_to_json_string_ext(poFilterRoot, 0);
json_object_put(poFilterRoot);
}
poObj = m_poDS->RunRequest(m_osRequestURL, FALSE, "POST", true,
osFilter);
}
else
{
poObj = m_poDS->RunRequest(m_osRequestURL);
}
if( poObj == nullptr )
{
m_bEOF = true;
return false;
}
json_object* poFeatures = CPL_json_object_object_get(poObj, "features");
if( poFeatures == nullptr ||
json_object_get_type(poFeatures) != json_type_array ||
json_object_array_length(poFeatures) == 0 )
{
// If this is a single item, then wrap it in a features array
json_object* poProperties = CPL_json_object_object_get(poObj, "properties");
if( poProperties != nullptr )
{
m_poPageObj = json_object_new_object();
poFeatures = json_object_new_array();
json_object_array_add(poFeatures, poObj);
json_object_object_add(m_poPageObj, "features", poFeatures);
poObj = m_poPageObj;
}
else
{
json_object_put(poObj);
m_bEOF = true;
return false;
}
}
m_poPageObj = poObj;
m_poFeatures = poFeatures;
// Get URL of next page
m_osNextURL = "";
json_object* poLinks = CPL_json_object_object_get(poObj, "_links");
if( poLinks && json_object_get_type(poLinks) == json_type_object )
{
json_object* poNext = CPL_json_object_object_get(poLinks, "_next");
if( poNext && json_object_get_type(poNext) == json_type_string )
{
m_osNextURL = json_object_get_string(poNext);
}
}
return true;
}
/************************************************************************/
/* ResetReading() */
/************************************************************************/
void OGRPLScenesDataV1Layer::ResetReading()
{
m_bEOF = false;
if( m_poFeatures != nullptr && m_bStillInFirstPage )
m_nFeatureIdx = 0;
else
m_poFeatures = nullptr;
m_nNextFID = 1;
m_bStillInFirstPage = true;
m_osRequestURL = m_poDS->GetBaseURL() +
CPLSPrintf("quick-search?_page_size=%d", m_nPageSize);
}
/************************************************************************/
/* SetSpatialFilter() */
/************************************************************************/
void OGRPLScenesDataV1Layer::SetSpatialFilter( OGRGeometry *poGeomIn )
{
m_poFeatures = nullptr;
if( poGeomIn )
{
OGREnvelope sEnvelope;
poGeomIn->getEnvelope(&sEnvelope);
if( sEnvelope.MinX == sEnvelope.MaxX && sEnvelope.MinY == sEnvelope.MaxY )
{
OGRPoint p(sEnvelope.MinX, sEnvelope.MinY);
InstallFilter(&p);
}
else
InstallFilter( poGeomIn );
}
else
InstallFilter( poGeomIn );
ResetReading();
}
/************************************************************************/
/* OGRPLScenesDataV1ParseDateTime() */
/************************************************************************/
static bool OGRPLScenesDataV1ParseDateTime(const char* pszValue,
int& nYear, int &nMonth, int &nDay,
int& nHour, int &nMinute, int &nSecond)
{
return ( sscanf(pszValue,"%04d/%02d/%02d %02d:%02d:%02d",
&nYear, &nMonth, &nDay, &nHour, &nMinute, &nSecond) >= 3 ||
sscanf(pszValue,"%04d-%02d-%02dT%02d:%02d:%02d",
&nYear, &nMonth, &nDay, &nHour, &nMinute, &nSecond) >= 3 );
}
/************************************************************************/
/* IsSimpleComparison() */
/************************************************************************/
bool OGRPLScenesDataV1Layer::IsSimpleComparison(const swq_expr_node* poNode)
{
return poNode->eNodeType == SNT_OPERATION &&
(poNode->nOperation == SWQ_EQ ||
poNode->nOperation == SWQ_NE ||
poNode->nOperation == SWQ_LT ||
poNode->nOperation == SWQ_LE ||
poNode->nOperation == SWQ_GT ||
poNode->nOperation == SWQ_GE) &&
poNode->nSubExprCount == 2 &&
poNode->papoSubExpr[0]->eNodeType == SNT_COLUMN &&
poNode->papoSubExpr[1]->eNodeType == SNT_CONSTANT &&
m_oMapFieldIdxToQueriableJSonFieldName.find(
poNode->papoSubExpr[0]->field_index) !=
m_oMapFieldIdxToQueriableJSonFieldName.end();
}
/************************************************************************/
/* GetOperatorText() */
/************************************************************************/
static const char* GetOperatorText(swq_op nOp)
{
if( nOp == SWQ_LT )
return "lt";
if( nOp == SWQ_LE )
return "lte";
if( nOp == SWQ_GT )
return "gt";
if( nOp == SWQ_GE )
return "gte";
CPLAssert(false);
return "";
}
/************************************************************************/
/* BuildFilter() */
/************************************************************************/
json_object* OGRPLScenesDataV1Layer::BuildFilter(swq_expr_node* poNode)
{
if( poNode->eNodeType == SNT_OPERATION &&
poNode->nOperation == SWQ_AND && poNode->nSubExprCount == 2 )
{
// For AND, we can deal with a failure in one of the branch
// since client-side will do that extra filtering
json_object* poFilter1 = BuildFilter(poNode->papoSubExpr[0]);
json_object* poFilter2 = BuildFilter(poNode->papoSubExpr[1]);
if( poFilter1 && poFilter2 )
{
json_object* poFilter = json_object_new_object();
json_object_object_add(poFilter, "type",
json_object_new_string("AndFilter"));
json_object* poConfig = json_object_new_array();
json_object_object_add(poFilter, "config", poConfig);
json_object_array_add(poConfig, poFilter1);
json_object_array_add(poConfig, poFilter2);
return poFilter;
}
else if( poFilter1 )
return poFilter1;
else
return poFilter2;
}
else if( poNode->eNodeType == SNT_OPERATION &&
poNode->nOperation == SWQ_OR && poNode->nSubExprCount == 2 )
{
// For OR, we need both members to be valid
json_object* poFilter1 = BuildFilter(poNode->papoSubExpr[0]);
json_object* poFilter2 = BuildFilter(poNode->papoSubExpr[1]);
if( poFilter1 && poFilter2 )
{
json_object* poFilter = json_object_new_object();
json_object_object_add(poFilter, "type",
json_object_new_string("OrFilter"));
json_object* poConfig = json_object_new_array();
json_object_object_add(poFilter, "config", poConfig);
json_object_array_add(poConfig, poFilter1);
json_object_array_add(poConfig, poFilter2);
return poFilter;
}
else
{
if( poFilter1 )
json_object_put(poFilter1);
if( poFilter2 )
json_object_put(poFilter2);
return nullptr;
}
}
else if( poNode->eNodeType == SNT_OPERATION &&
poNode->nOperation == SWQ_NOT && poNode->nSubExprCount == 1 )
{
json_object* poFilter1 = BuildFilter(poNode->papoSubExpr[0]);
if( poFilter1 )
{
json_object* poFilter = json_object_new_object();
json_object_object_add(poFilter, "type",
json_object_new_string("NotFilter"));
json_object_object_add(poFilter, "config", poFilter1);
return poFilter;
}
else
{
return nullptr;
}
}
else if( IsSimpleComparison(poNode) )
{
int nYear = 0, nMonth = 0, nDay = 0, nHour = 0, nMinute = 0, nSecond = 0;
const int nFieldIdx = poNode->papoSubExpr[0]->field_index;
if( poNode->nOperation == SWQ_NE )
{
poNode->nOperation = SWQ_EQ;
json_object* poFilter1 = BuildFilter(poNode);
poNode->nOperation = SWQ_NE;
if( poFilter1 )
{
json_object* poFilter = json_object_new_object();
json_object_object_add(poFilter, "type",
json_object_new_string("NotFilter"));
json_object_object_add(poFilter, "config", poFilter1);
return poFilter;
}
else
{
return nullptr;
}
}
else if( poNode->nOperation == SWQ_EQ &&
(m_poFeatureDefn->GetFieldDefn(nFieldIdx)->GetType() == OFTInteger ||
m_poFeatureDefn->GetFieldDefn(nFieldIdx)->GetType() == OFTReal) &&
(poNode->papoSubExpr[1]->field_type == SWQ_INTEGER ||
poNode->papoSubExpr[1]->field_type == SWQ_FLOAT) )
{
json_object* poFilter = json_object_new_object();
if( m_poFeatureDefn->GetFieldDefn(nFieldIdx)->GetType() == OFTReal )
{
json_object_object_add(poFilter, "type",
json_object_new_string("RangeFilter"));
json_object_object_add(poFilter, "field_name",
json_object_new_string(
m_oMapFieldIdxToQueriableJSonFieldName[nFieldIdx]));
json_object* poConfig = json_object_new_object();
const double EPS = 1e-8;
json_object_object_add(poConfig, "gte",
(poNode->papoSubExpr[1]->field_type == SWQ_INTEGER) ?
json_object_new_double(poNode->papoSubExpr[1]->int_value - EPS) :
json_object_new_double(poNode->papoSubExpr[1]->float_value - EPS));
json_object_object_add(poConfig, "lte",
(poNode->papoSubExpr[1]->field_type == SWQ_INTEGER) ?
json_object_new_double(poNode->papoSubExpr[1]->int_value + EPS) :
json_object_new_double(poNode->papoSubExpr[1]->float_value + EPS));
json_object_object_add(poFilter, "config", poConfig);
}
else
{
json_object_object_add(poFilter, "type",
json_object_new_string("NumberInFilter"));
json_object_object_add(poFilter, "field_name",
json_object_new_string(
m_oMapFieldIdxToQueriableJSonFieldName[nFieldIdx]));
json_object* poConfig = json_object_new_array();
json_object_array_add(poConfig,
(poNode->papoSubExpr[1]->field_type == SWQ_INTEGER) ?
json_object_new_int64(poNode->papoSubExpr[1]->int_value) :
json_object_new_double(poNode->papoSubExpr[1]->float_value));
json_object_object_add(poFilter, "config", poConfig);
}
return poFilter;
}
else if( poNode->nOperation == SWQ_EQ &&
m_poFeatureDefn->GetFieldDefn(nFieldIdx)->GetType() == OFTString &&
poNode->papoSubExpr[1]->field_type == SWQ_STRING )
{
json_object* poFilter = json_object_new_object();
json_object_object_add(poFilter, "type",
json_object_new_string("StringInFilter"));
json_object_object_add(poFilter, "field_name",
json_object_new_string(
m_oMapFieldIdxToQueriableJSonFieldName[nFieldIdx]));
json_object* poConfig = json_object_new_array();
json_object_array_add(poConfig,
json_object_new_string(poNode->papoSubExpr[1]->string_value));
json_object_object_add(poFilter, "config", poConfig);
return poFilter;
}
else if( (poNode->nOperation == SWQ_LT ||
poNode->nOperation == SWQ_LE ||
poNode->nOperation == SWQ_GT ||
poNode->nOperation == SWQ_GE) &&
(m_poFeatureDefn->GetFieldDefn(nFieldIdx)->GetType() == OFTInteger ||
m_poFeatureDefn->GetFieldDefn(nFieldIdx)->GetType() == OFTReal) &&
(poNode->papoSubExpr[1]->field_type == SWQ_INTEGER ||
poNode->papoSubExpr[1]->field_type == SWQ_FLOAT) )
{
json_object* poFilter = json_object_new_object();
json_object_object_add(poFilter, "type",
json_object_new_string("RangeFilter"));
json_object_object_add(poFilter, "field_name",
json_object_new_string(
m_oMapFieldIdxToQueriableJSonFieldName[nFieldIdx]));
json_object* poConfig = json_object_new_object();
json_object_object_add(poConfig,
GetOperatorText(poNode->nOperation),
(poNode->papoSubExpr[1]->field_type == SWQ_INTEGER) ?
json_object_new_int64(poNode->papoSubExpr[1]->int_value) :
json_object_new_double(poNode->papoSubExpr[1]->float_value));
json_object_object_add(poFilter, "config", poConfig);
return poFilter;
}
else if( (poNode->nOperation == SWQ_LT ||
poNode->nOperation == SWQ_LE ||
poNode->nOperation == SWQ_GT ||
poNode->nOperation == SWQ_GE) &&
m_poFeatureDefn->GetFieldDefn(nFieldIdx)->GetType() == OFTDateTime &&
poNode->papoSubExpr[1]->field_type == SWQ_TIMESTAMP &&
OGRPLScenesDataV1ParseDateTime(poNode->papoSubExpr[1]->string_value,
nYear, nMonth, nDay, nHour, nMinute, nSecond) )
{
json_object* poFilter = json_object_new_object();
json_object_object_add(poFilter, "type",
json_object_new_string("DateRangeFilter"));
json_object_object_add(poFilter, "field_name",
json_object_new_string(
m_oMapFieldIdxToQueriableJSonFieldName[nFieldIdx]));
json_object* poConfig = json_object_new_object();
json_object_object_add(poConfig,
GetOperatorText(poNode->nOperation),
json_object_new_string(
CPLSPrintf("%04d-%02d-%02dT%02d:%02d:%02dZ",
nYear, nMonth, nDay, nHour, nMinute, nSecond)));
json_object_object_add(poFilter, "config", poConfig);
return poFilter;
}
}
else if ( poNode->eNodeType == SNT_OPERATION &&
poNode->nOperation == SWQ_IN &&
poNode->nSubExprCount >= 2 &&
poNode->papoSubExpr[0]->eNodeType == SNT_COLUMN &&
m_oMapFieldIdxToQueriableJSonFieldName.find(
poNode->papoSubExpr[0]->field_index) !=
m_oMapFieldIdxToQueriableJSonFieldName.end() )
{
const int nFieldIdx = poNode->papoSubExpr[0]->field_index;
if( m_poFeatureDefn->GetFieldDefn(nFieldIdx)->GetType() == OFTString )
{
json_object* poFilter = json_object_new_object();
json_object_object_add(poFilter, "type",
json_object_new_string("StringInFilter"));
json_object_object_add(poFilter, "field_name",
json_object_new_string(
m_oMapFieldIdxToQueriableJSonFieldName[nFieldIdx]));
json_object* poConfig = json_object_new_array();
json_object_object_add(poFilter, "config", poConfig);
for( int i=1; i<poNode->nSubExprCount;i++)
{
if( poNode->papoSubExpr[i]->eNodeType != SNT_CONSTANT ||
poNode->papoSubExpr[i]->field_type != SWQ_STRING )
{
json_object_put(poFilter);
m_bFilterMustBeClientSideEvaluated = true;
return nullptr;
}
json_object_array_add(poConfig, json_object_new_string(
poNode->papoSubExpr[i]->string_value));
}
return poFilter;
}
else if( m_poFeatureDefn->GetFieldDefn(nFieldIdx)->GetType() == OFTInteger )
{
json_object* poFilter = json_object_new_object();
json_object_object_add(poFilter, "type",
json_object_new_string("NumberInFilter"));
json_object_object_add(poFilter, "field_name",
json_object_new_string(
m_oMapFieldIdxToQueriableJSonFieldName[nFieldIdx]));
json_object* poConfig = json_object_new_array();
json_object_object_add(poFilter, "config", poConfig);
for( int i=1; i<poNode->nSubExprCount;i++)
{
if( poNode->papoSubExpr[i]->eNodeType != SNT_CONSTANT ||
poNode->papoSubExpr[i]->field_type != SWQ_INTEGER )
{
json_object_put(poFilter);
m_bFilterMustBeClientSideEvaluated = true;
return nullptr;
}
json_object_array_add(poConfig, json_object_new_int64(
poNode->papoSubExpr[i]->int_value));
}
return poFilter;
}
}
else if( poNode->eNodeType == SNT_OPERATION &&
poNode->nOperation == SWQ_EQ &&
poNode->nSubExprCount == 2 &&
poNode->papoSubExpr[0]->eNodeType == SNT_COLUMN &&
poNode->papoSubExpr[1]->eNodeType == SNT_CONSTANT &&
poNode->papoSubExpr[0]->field_index ==
m_poFeatureDefn->GetFieldIndex("permissions") &&
poNode->papoSubExpr[1]->field_type == SWQ_STRING )
{
json_object* poFilter = json_object_new_object();
json_object_object_add(poFilter, "type",
json_object_new_string("PermissionFilter"));
json_object* poConfig = json_object_new_array();
json_object_object_add(poFilter, "config", poConfig);
json_object_array_add(poConfig, json_object_new_string(
poNode->papoSubExpr[1]->string_value));
return poFilter;
}
else if( poNode->eNodeType == SNT_OPERATION &&
poNode->nOperation == SWQ_IN &&
poNode->nSubExprCount >= 2 &&
poNode->papoSubExpr[0]->eNodeType == SNT_COLUMN &&
poNode->papoSubExpr[0]->field_index ==
m_poFeatureDefn->GetFieldIndex("permissions") )
{
json_object* poFilter = json_object_new_object();
json_object_object_add(poFilter, "type",
json_object_new_string("PermissionFilter"));
json_object* poConfig = json_object_new_array();
json_object_object_add(poFilter, "config", poConfig);
for( int i=1; i<poNode->nSubExprCount;i++)
{
if( poNode->papoSubExpr[i]->eNodeType != SNT_CONSTANT ||
poNode->papoSubExpr[i]->field_type != SWQ_STRING )
{
json_object_put(poFilter);
m_bFilterMustBeClientSideEvaluated = true;
return nullptr;
}
json_object_array_add(poConfig, json_object_new_string(
poNode->papoSubExpr[i]->string_value));
}
return poFilter;
}
m_bFilterMustBeClientSideEvaluated = true;
return nullptr;
}
/************************************************************************/
/* SetAttributeFilter() */
/************************************************************************/
OGRErr OGRPLScenesDataV1Layer::SetAttributeFilter( const char *pszQuery )
{
m_poFeatures = nullptr;
OGRErr eErr = OGRLayer::SetAttributeFilter(pszQuery);
if( m_poAttributeFilter )
json_object_put(m_poAttributeFilter);
m_poAttributeFilter = nullptr;
m_bFilterMustBeClientSideEvaluated = false;
if( m_poAttrQuery != nullptr )
{
swq_expr_node* poNode = (swq_expr_node*) m_poAttrQuery->GetSWQExpr();
poNode->ReplaceBetweenByGEAndLERecurse();
m_poAttributeFilter = BuildFilter(poNode);
if( m_poAttributeFilter == nullptr )
{
CPLDebug("PLSCENES",
"Full filter will be evaluated on client side.");
}
else if( m_bFilterMustBeClientSideEvaluated )
{
CPLDebug("PLSCENES",
"Only part of the filter will be evaluated on server side.");
}
}
ResetReading();
return eErr;
}
/************************************************************************/
/* GetNextFeature() */
/************************************************************************/
OGRFeature *OGRPLScenesDataV1Layer::GetNextFeature()
{
while( true )
{
OGRFeature *poFeature = GetNextRawFeature();
if (poFeature == nullptr)
return nullptr;
if( m_poAttrQuery == nullptr ||
!m_bFilterMustBeClientSideEvaluated ||
m_poAttrQuery->Evaluate( poFeature ) )
{
return poFeature;
}
else
{
delete poFeature;
}
}
}
/************************************************************************/
/* GetNextRawFeature() */
/************************************************************************/
OGRFeature* OGRPLScenesDataV1Layer::GetNextRawFeature()
{
EstablishLayerDefn();
if( m_bEOF )
return nullptr;
if( m_poFeatures == nullptr )
{
if( !GetNextPage() )
return nullptr;
}
if( m_nFeatureIdx == static_cast<int>(json_object_array_length(m_poFeatures)) )
{
if( m_nFeatureIdx < m_nPageSize &&
m_poDS->GetBaseURL().find("/vsimem/") != 0 )
{
return nullptr;
}
m_osRequestURL = m_osNextURL;
m_bStillInFirstPage = false;
if( !GetNextPage() )
return nullptr;
}
json_object* poJSonFeature = json_object_array_get_idx(m_poFeatures, m_nFeatureIdx);
m_nFeatureIdx ++;
if( poJSonFeature == nullptr || json_object_get_type(poJSonFeature) != json_type_object )
{
m_bEOF = true;
return nullptr;
}
OGRFeature* poFeature = new OGRFeature(m_poFeatureDefn);
poFeature->SetFID(m_nNextFID++);
json_object* poJSonGeom = CPL_json_object_object_get(poJSonFeature, "geometry");
if( poJSonGeom != nullptr && json_object_get_type(poJSonGeom) == json_type_object )
{
OGRGeometry* poGeom = OGRGeoJSONReadGeometry(poJSonGeom);
if( poGeom != nullptr )
{
if( poGeom->getGeometryType() == wkbPolygon )
{
OGRMultiPolygon* poMP = new OGRMultiPolygon();
poMP->addGeometryDirectly(poGeom);
poGeom = poMP;
}
poGeom->assignSpatialReference(m_poSRS);
poFeature->SetGeometryDirectly(poGeom);
}
}
json_object* poId = CPL_json_object_object_get(poJSonFeature, "id");
if( poId != nullptr && json_object_get_type(poId) == json_type_string )
{
std::map<CPLString, int>::const_iterator oIter =
m_oMapPrefixedJSonFieldNameToFieldIdx.find("id");
if( oIter != m_oMapPrefixedJSonFieldNameToFieldIdx.end() )
{
const int iField = oIter->second;
poFeature->SetField(iField, json_object_get_string(poId));
}
}
json_object* poPermissions =
CPL_json_object_object_get(poJSonFeature, "_permissions");
if( poPermissions != nullptr &&
json_object_get_type(poPermissions) == json_type_array )
{
std::map<CPLString, int>::const_iterator oIter =
m_oMapPrefixedJSonFieldNameToFieldIdx.find("_permissions");
if( oIter != m_oMapPrefixedJSonFieldNameToFieldIdx.end() )
{
const int iField = oIter->second;
const auto nStrings = json_object_array_length(poPermissions);
char** papszPermissions =
static_cast<char**>(CPLCalloc(nStrings+1, sizeof(char*)));
for(auto i=decltype(nStrings){0}, j=decltype(nStrings){0};
i<nStrings;i++)
{
json_object* poPerm = json_object_array_get_idx(poPermissions,i);
if( poPerm && json_object_get_type(poPerm) == json_type_string )
{
papszPermissions[j++] =
CPLStrdup(json_object_get_string(poPerm));
}
}
poFeature->SetField(iField, papszPermissions);
CSLDestroy(papszPermissions);
}
}
for(int i=0;i<2;i++)
{
const char* pszFeaturePart = (i == 0) ? "properties": "_links";
json_object* poProperties =
CPL_json_object_object_get(poJSonFeature, pszFeaturePart);
if( poProperties != nullptr &&
json_object_get_type(poProperties) == json_type_object )
{
json_object_iter it;
it.key = nullptr;
it.val = nullptr;
it.entry = nullptr;
json_object_object_foreachC( poProperties, it )
{
CPLString osPrefixedJSonFieldName(pszFeaturePart);
osPrefixedJSonFieldName += ".";
osPrefixedJSonFieldName += it.key;
if( !SetFieldFromPrefixedJSonFieldName(
poFeature, osPrefixedJSonFieldName, it.val) )
{
if( i == 0 &&
m_oSetUnregisteredFields.find(osPrefixedJSonFieldName)
== m_oSetUnregisteredFields.end() )
{
CPLError(CE_Warning, CPLE_AppDefined,
"Field %s found in data but not "
"in configuration",
osPrefixedJSonFieldName.c_str());
m_oSetUnregisteredFields.insert(
osPrefixedJSonFieldName);
}
}
}
}
}
json_object* poAssets = nullptr;
if( m_poDS->DoesFollowLinks() &&
(!m_bInFeatureCountOrGetExtent || m_poAttrQuery != nullptr) )
{
std::map<CPLString, int>::const_iterator oIter =
m_oMapPrefixedJSonFieldNameToFieldIdx.find("_links.assets");
if( oIter != m_oMapPrefixedJSonFieldNameToFieldIdx.end() )
{
const int iField = oIter->second;
if( poFeature->IsFieldSetAndNotNull( iField ) )
{
const char* pszAssetURL = poFeature->GetFieldAsString( iField );
poAssets = m_poDS->RunRequest(pszAssetURL);
}
}
}
if( poAssets != nullptr )
{
json_object_iter itAsset;
itAsset.key = nullptr;
itAsset.val = nullptr;
itAsset.entry = nullptr;
json_object_object_foreachC( poAssets, itAsset )
{
if( m_oSetAssets.find(itAsset.key) == m_oSetAssets.end() )
{
if( m_oSetUnregisteredAssets.find(itAsset.key) ==
m_oSetUnregisteredAssets.end() )
{
CPLError(CE_Warning, CPLE_AppDefined,
"Asset %s found in data but "
"not in configuration",
itAsset.key);
m_oSetUnregisteredAssets.insert(itAsset.key);
}
continue;
}
json_object* poAsset = itAsset.val;
if( poAsset != nullptr &&
json_object_get_type(poAsset) == json_type_object )
{
json_object_iter it;
it.key = nullptr;
it.val = nullptr;
it.entry = nullptr;
json_object_object_foreachC( poAsset, it )
{
if( it.val == nullptr ) continue;
CPLString osPrefixedJSonFieldName(
"/assets." + CPLString(itAsset.key));
osPrefixedJSonFieldName += "." + CPLString(it.key);
if( strcmp(it.key, "_links") == 0 &&
json_object_get_type(it.val) == json_type_object )
{
if( CPL_json_object_object_get(it.val, "_self") != nullptr )
{
CPLString osPrefixedJSonFieldNameNew(
osPrefixedJSonFieldName + "._self");
SetFieldFromPrefixedJSonFieldName(
poFeature, osPrefixedJSonFieldNameNew,
CPL_json_object_object_get(it.val, "_self"));
}
if( CPL_json_object_object_get(it.val, "activate") != nullptr )
{
CPLString osPrefixedJSonFieldNameNew(
osPrefixedJSonFieldName + ".activate");
SetFieldFromPrefixedJSonFieldName(
poFeature, osPrefixedJSonFieldNameNew,
CPL_json_object_object_get(it.val, "activate"));
}
}
else
{
SetFieldFromPrefixedJSonFieldName(
poFeature, osPrefixedJSonFieldName, it.val);
}
}
}
}
json_object_put(poAssets);
}
return poFeature;
}
/************************************************************************/
/* SetFieldFromPrefixedJSonFieldName() */
/************************************************************************/
bool OGRPLScenesDataV1Layer::SetFieldFromPrefixedJSonFieldName(
OGRFeature* poFeature,
const CPLString& osPrefixedJSonFieldName,
json_object* poVal )
{
std::map<CPLString, int>::const_iterator oIter =
m_oMapPrefixedJSonFieldNameToFieldIdx.find(osPrefixedJSonFieldName);
if( poVal != nullptr && oIter != m_oMapPrefixedJSonFieldNameToFieldIdx.end() )
{
const int iField = oIter->second;
json_type eJSonType = json_object_get_type(poVal);
if( eJSonType == json_type_int )
{
poFeature->SetField(iField,
static_cast<GIntBig>(json_object_get_int64(poVal)));
}
else if( eJSonType == json_type_double )
{
poFeature->SetField(iField, json_object_get_double(poVal));
}
else if( eJSonType == json_type_string )
{
poFeature->SetField(iField, json_object_get_string(poVal));
}
else if( eJSonType == json_type_boolean )
{
poFeature->SetField(iField, json_object_get_boolean(poVal));
}
else
{
poFeature->SetField(iField, json_object_to_json_string_ext( poVal, 0 ));
}
return true;
}
return false;
}
/************************************************************************/
/* GetFeatureCount() */
/************************************************************************/
GIntBig OGRPLScenesDataV1Layer::GetFeatureCount(int bForce)
{
if( m_poDS->GetFilter().empty() )
{
if( m_nTotalFeatures >= 0 &&
m_poFilterGeom == nullptr && m_poAttrQuery == nullptr )
{
return m_nTotalFeatures;
}
json_object* poFilterRoot = json_object_new_object();
json_object* poItemTypes = json_object_new_array();
json_object_array_add(poItemTypes,
json_object_new_string(GetName()));
json_object_object_add(poFilterRoot, "interval",
json_object_new_string("year"));
json_object_object_add(poFilterRoot, "item_types", poItemTypes);
json_object* poFilter = json_object_new_object();
json_object_object_add(poFilterRoot, "filter", poFilter);
json_object_object_add(poFilter, "type",
json_object_new_string("AndFilter"));
json_object* poConfig = json_object_new_array();
json_object_object_add(poFilter, "config", poConfig);
// We need to put a dummy filter
if( m_poFilterGeom == nullptr && m_poAttributeFilter == nullptr )
{
json_object* poRangeFilter = json_object_new_object();
json_object_array_add(poConfig, poRangeFilter);
json_object_object_add(poRangeFilter, "type",
json_object_new_string("RangeFilter"));
json_object_object_add(poRangeFilter, "field_name",
json_object_new_string("cloud_cover"));
json_object* poRangeFilterConfig = json_object_new_object();
json_object_object_add(poRangeFilterConfig, "gte",
json_object_new_double(0.0));
json_object_object_add(poRangeFilter, "config",
poRangeFilterConfig);
}
if( m_poFilterGeom != nullptr )
{
json_object* poGeomFilter = json_object_new_object();
json_object_array_add(poConfig, poGeomFilter);
json_object_object_add(poGeomFilter, "type",
json_object_new_string("GeometryFilter"));
json_object_object_add(poGeomFilter, "field_name",
json_object_new_string("geometry"));
OGRGeoJSONWriteOptions oOptions;
json_object* poGeoJSONGeom =
OGRGeoJSONWriteGeometry( m_poFilterGeom, oOptions );
json_object_object_add(poGeomFilter, "config",
poGeoJSONGeom);
}
if( m_poAttributeFilter != nullptr )
{
json_object_get(m_poAttributeFilter);
json_object_array_add(poConfig, m_poAttributeFilter);
}
CPLString osFilter = json_object_to_json_string_ext(poFilterRoot, 0);
json_object_put(poFilterRoot);
json_object* poObj = m_poDS->RunRequest(
(m_poDS->GetBaseURL() + "stats").c_str(),
FALSE, "POST", true,
osFilter);
if( poObj != nullptr )
{
json_object* poBuckets =
CPL_json_object_object_get(poObj, "buckets");
if( poBuckets && json_object_get_type(poBuckets) ==
json_type_array )
{
GIntBig nRes = 0;
const auto nBuckets = json_object_array_length(poBuckets);
for( auto i=decltype(nBuckets){0}; i<nBuckets;i++ )
{
json_object* poBucket =
json_object_array_get_idx(poBuckets, i);
if( poBucket && json_object_get_type(poBucket) ==
json_type_object )
{
json_object* poCount =
CPL_json_object_object_get(poBucket, "count");
if( poCount && json_object_get_type(poCount) ==
json_type_int )
{
nRes += json_object_get_int64(poCount);
}
}
}
if( m_poFilterGeom == nullptr && m_poAttrQuery == nullptr )
m_nTotalFeatures = nRes;
json_object_put(poObj);
return nRes;
}
json_object_put(poObj);
}
}
m_bInFeatureCountOrGetExtent = true;
GIntBig nRes = OGRLayer::GetFeatureCount(bForce);
m_bInFeatureCountOrGetExtent = false;
return nRes;
}
/************************************************************************/
/* GetExtent() */
/************************************************************************/
OGRErr OGRPLScenesDataV1Layer::GetExtent( OGREnvelope *psExtent, int bForce )
{
if( m_poFilterGeom != nullptr )
{
m_bInFeatureCountOrGetExtent = true;
OGRErr eErr = OGRLayer::GetExtentInternal(0, psExtent, bForce);
m_bInFeatureCountOrGetExtent = false;
return eErr;
}
psExtent->MinX = -180;
psExtent->MinY = -90;
psExtent->MaxX = 180;
psExtent->MaxY = 90;
return OGRERR_NONE;
}
/************************************************************************/
/* TestCapability() */
/************************************************************************/
int OGRPLScenesDataV1Layer::TestCapability(const char* pszCap)
{
if( EQUAL(pszCap, OLCFastFeatureCount) )
return !m_bFilterMustBeClientSideEvaluated;
if( EQUAL(pszCap, OLCStringsAsUTF8) )
return TRUE;
return FALSE;
}
|
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Copyright (c) 2016-22, Lawrence Livermore National Security, LLC
// and RAJA project contributors. See the RAJA/LICENSE file for details.
//
// SPDX-License-Identifier: (BSD-3-Clause)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
#ifndef __TEST_WARP_THREAD_RESOURCE_WARPLOOP_HPP__
#define __TEST_WARP_THREAD_RESOURCE_WARPLOOP_HPP__
#include "warp-thread-WarpLoop-impl.hpp"
//
//
// Setup the Warp Reduction WarpLoop g-tests.
//
//
TYPED_TEST_SUITE_P(KernelWarpThreadWarpLoopTest);
template <typename T>
class KernelWarpThreadWarpLoopTest : public ::testing::Test {};
TYPED_TEST_P(KernelWarpThreadWarpLoopTest, WarpThreadWarpLoopKernel) {
using WORKING_RES = typename camp::at<TypeParam, camp::num<0>>::type;
using REDUCE_POL = typename camp::at<TypeParam, camp::num<1>>::type;
using EXEC_POL_DATA = typename camp::at<TypeParam, camp::num<2>>::type;
// Attain the loop depth type from execpol data.
using LOOP_TYPE = typename EXEC_POL_DATA::LoopType;
// Get List of loop exec policies.
using LOOP_POLS = typename EXEC_POL_DATA::type;
// Build proper basic kernel exec policy type.
using EXEC_POLICY = typename WarpThreadExec<LOOP_TYPE, REDUCE_POL, LOOP_POLS>::type;
constexpr bool USE_RES = true;
// For double nested loop tests the third arg is ignored.
KernelWarpThreadTest<WORKING_RES, EXEC_POLICY, REDUCE_POL, USE_RES>( LOOP_TYPE(), 2345 );
}
REGISTER_TYPED_TEST_SUITE_P(KernelWarpThreadWarpLoopTest,
WarpThreadWarpLoopKernel);
#endif // __TEST_WARP_THREAD_RESOURCE_WARPLOOP_HPP__
|
//
// Copyright (c) 2019-2020 Ivan Baidakou (basiliscos) (the dot dmol at gmail dot com)
//
// Distributed under the MIT Software License
//
#include "catch.hpp"
#include "rotor.hpp"
#include "rotor/ev.hpp"
#include <ev.h>
#include "access.h"
namespace r = rotor;
namespace re = rotor::ev;
namespace pt = boost::posix_time;
namespace rt = r::test;
struct sample_res_t {};
struct sample_req_t {
using response_t = sample_res_t;
};
using traits_t = r::request_traits_t<sample_req_t>;
struct bad_actor_t : public r::actor_base_t {
using r::actor_base_t::actor_base_t;
std::error_code ec;
void configure(r::plugin::plugin_base_t &plugin) noexcept override {
r::actor_base_t::configure(plugin);
plugin.with_casted<r::plugin::starter_plugin_t>([](auto &p) { p.subscribe_actor(&bad_actor_t::on_response); });
}
void on_start() noexcept override {
r::actor_base_t::on_start();
request<traits_t::request::type>(address).send(r::pt::milliseconds(1));
}
void on_response(traits_t::response::message_t &msg) noexcept {
ec = msg.payload.ec;
supervisor->do_shutdown();
}
};
TEST_CASE("timer", "[supervisor][ev]") {
auto *loop = ev_loop_new(0);
auto system_context = r::intrusive_ptr_t<re::system_context_ev_t>{new re::system_context_ev_t()};
auto timeout = r::pt::milliseconds{10};
auto sup = system_context->create_supervisor<re::supervisor_ev_t>()
.loop(loop)
.timeout(timeout)
.loop_ownership(true)
.finish();
auto actor = sup->create_actor<bad_actor_t>().timeout(timeout).finish();
sup->start();
ev_run(loop);
REQUIRE(actor->ec == r::error_code_t::request_timeout);
REQUIRE(static_cast<r::actor_base_t *>(sup.get())->access<rt::to::state>() == r::state_t::SHUT_DOWN);
}
|
/**
* <b>SOFTWARE RIGHTS</b>
* <p>
* ANTLR 2.6.0 MageLang Insitute, 1998
* <p>
* We reserve no legal rights to the ANTLR--it is fully in the
* public domain. An individual or company may do whatever
* they wish with source code distributed with ANTLR or the
* code generated by ANTLR, including the incorporation of
* ANTLR, or its output, into commerical software.
* <p>
* We encourage users to develop software with ANTLR. However,
* we do ask that credit is given to us for developing
* ANTLR. By "credit", we mean that if you use ANTLR or
* incorporate any source code into one of your programs
* (commercial product, research project, or otherwise) that
* you acknowledge this fact somewhere in the documentation,
* research report, etc... If you like ANTLR and have
* developed a nice tool with the output, please mention that
* you developed it using ANTLR. In addition, we ask that the
* headers remain intact in our source code. As long as these
* guidelines are kept, we expect to continue enhancing this
* system and expect to make other tools available as they are
* completed.
* <p>
* The ANTLR gang:
* @version ANTLR 2.6.0 MageLang Insitute, 1998
* @author Terence Parr, <a href=http://www.MageLang.com>MageLang Institute</a>
* @author <br>John Lilley, <a href=http://www.Empathy.com>Empathy Software</a>
* @author <br><a href="mailto:pete@yamuna.demon.co.uk">Pete Wells</a>
*/
#include "antlr/CommonToken.hpp"
#include "antlr/String.hpp"
ANTLR_BEGIN_NAMESPACE(antlr)
CommonToken::CommonToken() : Token(), line(1), col(1), text("")
{}
CommonToken::CommonToken(int t, const ANTLR_USE_NAMESPACE(std)string& txt)
: Token(t), line(1), col(1), text(txt)
{}
CommonToken::CommonToken(const ANTLR_USE_NAMESPACE(std)string& s)
: Token(), line(1), col(1), text(s)
{}
int CommonToken::getLine() const
{ return line; }
ANTLR_USE_NAMESPACE(std)string CommonToken::getText() const
{ return text; }
void CommonToken::setLine(int l)
{ line=l; }
void CommonToken::setText(const ANTLR_USE_NAMESPACE(std)string& s)
{ text=s; }
ANTLR_USE_NAMESPACE(std)string CommonToken::toString() const
{
return "[\""+getText()+"\",<"+type+">,line="+line+"]";
}
int CommonToken::getColumn() const
{ return col; }
void CommonToken::setColumn(int c)
{ col=c; }
bool CommonToken::isInvalid() const
{ return type==INVALID_TYPE; }
RefToken CommonToken::factory()
{
return RefToken(new CommonToken);
}
ANTLR_END_NAMESPACE
|
// ball_thresholdaggregate.t.cpp -*-C++-*-
// ----------------------------------------------------------------------------
// NOTICE
//
// This component is not up to date with current BDE coding standards, and
// should not be used as an example for new development.
// ----------------------------------------------------------------------------
#include <ball_thresholdaggregate.h>
#include <bslim_testutil.h>
#include <bsl_climits.h>
#include <bsl_cstdlib.h>
#include <bsl_iostream.h>
#include <bsl_sstream.h>
using namespace BloombergLP;
using namespace bsl; // automatically added by script
//=============================================================================
// TEST PLAN
//-----------------------------------------------------------------------------
// Overview
// --------
// The component under test is a typical and simple value-semantic component,
// so we simply follow the standard 10-case test suite, but with those
// apparatus-based test cases empty.
//-----------------------------------------------------------------------------
// [12] static int hash(const ball::ThresholdAggregate&, int size);
// [11] static bool areValidThresholdLevels(int, int, int, int);
// [ 2] ball::ThresholdAggregate(int, int, int, int);
// [ 7] ball::ThresholdAggregate(const ball::TA&, bdema::Alct * = 0);
// [ 2] ~ball::ThresholdAggregate();
// [10] int setLevels(int, int, int, int);
// [ 9] const ball::TA& operator=(const ball::TA& other);
// [ 4] int recordLevel() const;
// [ 4] int passLevel() const;
// [ 4] int triggerLevel() const;
// [ 4] int triggerAllLevel() const;
// [ 5] bsl::ostream& print(bsl::ostream& stream, int lvl, int spl) const;
// [ 6] bool operator==(const ball::TA& lhs, const ball::TA& rhs);
// [ 6] bool operator!=(const ball::TA& lhs, const ball::TA& rhs);
// [ 5] bsl::ostream& operator<<(bsl::ostream&, const ball::TA&);
//-----------------------------------------------------------------------------
// [ 1] BREATHING TEST
// [ 3] UNUSED
// [ 8] UNUSED
// [13] USAGE EXAMPLE
// ============================================================================
// STANDARD BDE ASSERT TEST FUNCTION
// ----------------------------------------------------------------------------
namespace {
int testStatus = 0;
void aSsErT(bool condition, const char *message, int line)
{
if (condition) {
cout << "Error " __FILE__ "(" << line << "): " << message
<< " (failed)" << endl;
if (0 <= testStatus && testStatus <= 100) {
++testStatus;
}
}
}
} // close unnamed namespace
// ============================================================================
// STANDARD BDE TEST DRIVER MACRO ABBREVIATIONS
// ----------------------------------------------------------------------------
#define ASSERT BSLIM_TESTUTIL_ASSERT
#define ASSERTV BSLIM_TESTUTIL_ASSERTV
#define LOOP_ASSERT BSLIM_TESTUTIL_LOOP_ASSERT
#define LOOP0_ASSERT BSLIM_TESTUTIL_LOOP0_ASSERT
#define LOOP1_ASSERT BSLIM_TESTUTIL_LOOP1_ASSERT
#define LOOP2_ASSERT BSLIM_TESTUTIL_LOOP2_ASSERT
#define LOOP3_ASSERT BSLIM_TESTUTIL_LOOP3_ASSERT
#define LOOP4_ASSERT BSLIM_TESTUTIL_LOOP4_ASSERT
#define LOOP5_ASSERT BSLIM_TESTUTIL_LOOP5_ASSERT
#define LOOP6_ASSERT BSLIM_TESTUTIL_LOOP6_ASSERT
#define Q BSLIM_TESTUTIL_Q // Quote identifier literally.
#define P BSLIM_TESTUTIL_P // Print identifier and value.
#define P_ BSLIM_TESTUTIL_P_ // P(X) without '\n'.
#define T_ BSLIM_TESTUTIL_T_ // Print a tab (w/o newline).
#define L_ BSLIM_TESTUTIL_L_ // current Line number
// ============================================================================
// NEGATIVE-TEST MACRO ABBREVIATIONS
// ----------------------------------------------------------------------------
#define ASSERT_SAFE_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_SAFE_PASS(EXPR)
#define ASSERT_SAFE_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_SAFE_FAIL(EXPR)
#define ASSERT_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_PASS(EXPR)
#define ASSERT_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_FAIL(EXPR)
#define ASSERT_OPT_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_OPT_PASS(EXPR)
#define ASSERT_OPT_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_OPT_FAIL(EXPR)
//=============================================================================
// GLOBAL TYPEDEFS/CONSTANTS FOR TESTING
//-----------------------------------------------------------------------------
typedef ball::ThresholdAggregate Obj;
#define VA 192, 160, 128, 96
#define VB 160, 128, 96, 64
#define VC 128, 96, 64, 32
#define VD 96, 64, 32, 0
#define VE 255, 255, 255, 255
#define VA1 192
#define VA2 160
#define VA3 128
#define VA4 96
#define VB1 160
#define VB2 128
#define VB3 96
#define VB4 64
#define VC1 128
#define VC2 96
#define VC3 64
#define VC4 32
#define VD1 96
#define VD2 64
#define VD3 32
#define VD4 0
static const struct {
int d_line; // line number
int d_recordLevel; // record level
int d_passLevel; // pass level
int d_triggerLevel; // trigger level
int d_triggerAllLevel; // trigger all level
int d_isValidFlag; // if the above levels are valid
} DATA[] = {
///line record pass trigger triggerAll is
///no. level level level level valid
///---- ------ ------ ------ ----- --------
{ L_, 0, 0, 0, 0, 1 },
{ L_, 1, 0, 0, 0, 1 },
{ L_, 0, 1, 0, 0, 1 },
{ L_, 0, 0, 1, 0, 1 },
{ L_, 0, 0, 0, 1, 1 },
{ L_, 16, 32, 48, 64, 1 },
{ L_, 64, 48, 32, 16, 1 },
{ L_, 16, 32, 64, 48, 1 },
{ L_, 16, 48, 32, 64, 1 },
{ L_, 32, 16, 48, 64, 1 },
{ L_, 255, 0, 0, 0, 1 },
{ L_, 0, 255, 0, 0, 1 },
{ L_, 0, 0, 255, 0, 1 },
{ L_, 0, 0, 0, 255, 1 },
{ L_, 255, 255, 255, 255, 1 },
{ L_, 256, 0, 0, 0, 0 },
{ L_, 0, 256, 0, 0, 0 },
{ L_, 0, 0, 256, 0, 0 },
{ L_, 0, 0, 0, 256, 0 },
{ L_, 256, 256, 256, 256, 0 },
{ L_, INT_MAX, 0, 0, 0, 0 },
{ L_, 0, INT_MAX, 0, 0, 0 },
{ L_, 0, 0, INT_MAX, 0, 0 },
{ L_, 0, 0, 0, INT_MAX, 0 },
{ L_, INT_MAX, INT_MAX, INT_MAX, INT_MAX, 0 },
{ L_, -1, 0, 0, 0, 0 },
{ L_, 0, -1, 0, 0, 0 },
{ L_, 0, 0, -1, 0, 0 },
{ L_, 0, 0, 0, -1, 0 },
{ L_, -1, -1, -1, -1, 0 },
{ L_, INT_MIN, 0, 0, 0, 0 },
{ L_, 0, INT_MIN, 0, 0, 0 },
{ L_, 0, 0, INT_MIN, 0, 0 },
{ L_, 0, 0, 0, INT_MIN, 0 },
{ L_, INT_MIN, INT_MIN, INT_MIN, INT_MIN, 0 }
};
const int NUM_DATA = sizeof DATA / sizeof *DATA;
//=============================================================================
// MAIN PROGRAM
//-----------------------------------------------------------------------------
int main(int argc, char *argv[])
{
int test = argc > 1 ? atoi(argv[1]) : 0;
int verbose = argc > 2;
int veryVerbose = argc > 3;
cout << "TEST " << __FILE__ << " CASE " << test << endl;;
switch (test) { case 0: // Zero is always the leading case.
case 13: {
// --------------------------------------------------------------------
// TESTING USAGE EXAMPLE
// The usage example provided in the component header file must
// compile, link, and run on all platforms as shown.
//
// Plan:
// Incorporate usage example from header into driver, remove leading
// comment characters, and replace 'assert' with 'ASSERT'. Suppress
// all 'cout' statements in non-verbose mode, and add streaming to
// a buffer to test programmatically the printing examples.
//
// Testing:
// USAGE EXAMPLE
// --------------------------------------------------------------------
if (verbose) cout << "\nTesting Usage Examples"
<< "\n======================" << endl;
ball::ThresholdAggregate levels(192, 160, 128, 96);
ASSERT(192 == levels.recordLevel());
ASSERT(160 == levels.passLevel());
ASSERT(128 == levels.triggerLevel());
ASSERT(96 == levels.triggerAllLevel());
levels.setLevels(160, 128, 96, 64);
ASSERT(160 == levels.recordLevel());
ASSERT(128 == levels.passLevel());
ASSERT(96 == levels.triggerLevel());
ASSERT(64 == levels.triggerAllLevel());
} break;
case 12: {
// --------------------------------------------------------------------
// TESTING HASH FUNCTION (VALUE):
//
// Concerns:
// (1) All fields must be incorporated in the hash value.
// (2) The hash value must be the same across all platforms for a
// given input.
//
// Plan:
// Specifying a set of test vectors consisting of distinct valid
// test values having subtle difference and hash sizes including
// powers of two and primes. For each value and hash size, verify
// that the 'hash' function returns expected value.
//
// 7 is the smallest hash table size and 1610612741 is largest size
// (that can fit into an int) used by stlport hashtable.
//
// Testing:
// static int hash(const ball::ThresholdAggregate&, int size);
// --------------------------------------------------------------------
if (verbose) cout << "\nTesting hash function"
<< "\n====================="
<< endl;
static const struct {
int d_line; // line number
int d_recordLevel; // record level
int d_passLevel; // pass level
int d_triggerLevel; // trigger level
int d_triggerAllLevel; // trigger all level
int d_size; // hash size
int d_hash; // hash value
} HDATA[] = {
///line record pass trigger trAll hash hash
///no. level level level level size value
///---- ------ ----- ------ ----- ---- -----
{ L_, 0, 0, 0, 0, 256, 233 },
{ L_, 1, 0, 0, 0, 256, 168 },
{ L_, 0, 1, 0, 0, 256, 19 },
{ L_, 0, 0, 1, 0, 256, 217 },
{ L_, 0, 0, 0, 1, 256, 214 },
{ L_, 16, 32, 48, 64, 256, 225 },
{ L_, 64, 48, 32, 16, 256, 176 },
{ L_, 16, 32, 64, 48, 256, 234 },
{ L_, 16, 48, 32, 64, 256, 31 },
{ L_, 32, 16, 48, 64, 256, 27 },
{ L_, 255, 0, 0, 0, 256, 116 },
{ L_, 0, 255, 0, 0, 256, 8 },
{ L_, 0, 0, 255, 0, 256, 191 },
{ L_, 0, 0, 0, 255, 256, 143 },
{ L_, 255, 255, 255, 255, 256, 89 },
{ L_, 0, 0, 0, 0, 65536, 48105 },
{ L_, 1, 0, 0, 0, 65536, 53928 },
{ L_, 0, 1, 0, 0, 65536, 19731 },
{ L_, 0, 0, 1, 0, 65536, 40409 },
{ L_, 0, 0, 0, 1, 65536, 36566 },
{ L_, 16, 32, 48, 64, 65536, 59617 },
{ L_, 64, 48, 32, 16, 65536, 24752 },
{ L_, 16, 32, 64, 48, 65536, 6378 },
{ L_, 16, 48, 32, 64, 65536, 29727 },
{ L_, 32, 16, 48, 64, 65536, 32283 },
{ L_, 255, 0, 0, 0, 65536, 1908 },
{ L_, 0, 255, 0, 0, 65536, 54536 },
{ L_, 0, 0, 255, 0, 65536, 60863 },
{ L_, 0, 0, 0, 255, 65536, 63375 },
{ L_, 255, 255, 255, 255, 65536, 39513 },
{ L_, 0, 0, 0, 0, 7, 4 },
{ L_, 1, 0, 0, 0, 7, 3 },
{ L_, 0, 1, 0, 0, 7, 4 },
{ L_, 0, 0, 1, 0, 7, 3 },
{ L_, 0, 0, 0, 1, 7, 0 },
{ L_, 16, 32, 48, 64, 7, 3 },
{ L_, 64, 48, 32, 16, 7, 2 },
{ L_, 16, 32, 64, 48, 7, 4 },
{ L_, 16, 48, 32, 64, 7, 2 },
{ L_, 32, 16, 48, 64, 7, 2 },
{ L_, 255, 0, 0, 0, 7, 5 },
{ L_, 0, 255, 0, 0, 7, 2 },
{ L_, 0, 0, 255, 0, 7, 2 },
{ L_, 0, 0, 0, 255, 7, 4 },
{ L_, 255, 255, 255, 255, 7, 1 },
{ L_, 0, 0, 0, 0, 1610612741, 694533092 },
{ L_, 1, 0, 0, 0, 1610612741, 982241950 },
{ L_, 0, 1, 0, 0, 1610612741, 373312777 },
{ L_, 0, 0, 1, 0, 1610612741, 484416985 },
{ L_, 0, 0, 0, 1, 1610612741, 1335135953 },
{ L_, 16, 32, 48, 64, 1610612741, 579004636 },
{ L_, 64, 48, 32, 16, 1610612741, 426860710 },
{ L_, 16, 32, 64, 48, 1610612741, 925767904 },
{ L_, 16, 48, 32, 64, 1610612741, 690648090 },
{ L_, 32, 16, 48, 64, 1610612741, 688029211 },
{ L_, 255, 0, 0, 0, 1610612741, 1006438250 },
{ L_, 0, 255, 0, 0, 1610612741, 413390078 },
{ L_, 0, 0, 255, 0, 1610612741, 455273919 },
{ L_, 0, 0, 0, 255, 1610612741, 1538324362 },
{ L_, 255, 255, 255, 255, 1610612741, 1025677913 },
};
const int NUM_HDATA = sizeof HDATA / sizeof *HDATA;
for (int i = 0; i < NUM_HDATA; ++i) {
int LINE = HDATA[i].d_line;
Obj mX(HDATA[i].d_recordLevel,
HDATA[i].d_passLevel,
HDATA[i].d_triggerLevel,
HDATA[i].d_triggerAllLevel);
const Obj& X = mX;
int hash = Obj::hash(X, HDATA[i].d_size);
if (veryVerbose) {
cout << HDATA[i].d_recordLevel << ", "
<< HDATA[i].d_passLevel << ", "
<< HDATA[i].d_triggerLevel << ", "
<< HDATA[i].d_triggerAllLevel << ", "
<< HDATA[i].d_size
<< " ---> " << hash << endl;
}
LOOP_ASSERT(LINE, 0 <= hash);
LOOP_ASSERT(LINE, hash < HDATA[i].d_size);
LOOP_ASSERT(LINE, HDATA[i].d_hash == hash);
}
} break;
case 11: {
// --------------------------------------------------------------------
// TESTING STATIC 'areValidThresholdLevels' FUNCTION:
// The static 'areValidThresholdLevels' function should return
// correct value for both valid and invalid input.
//
// Plan:
// For a sequence of independent test values, verify that the
// function returns the expected value.
//
// Testing:
// static bool areValidThresholdLevels(int, int, int, int);
// --------------------------------------------------------------------
if (verbose) cout << "\nTesting 'areValidThresholdLevels' function"
<< "\n=========================================="
<< endl;
for (int i = 0; i < NUM_DATA; ++i) {
const int LINE = DATA[i].d_line;
if (veryVerbose) {
P_(LINE);
P_(DATA[i].d_recordLevel);
P_(DATA[i].d_passLevel);
P_(DATA[i].d_triggerLevel);
P(DATA[i].d_triggerAllLevel);
}
bool isValidFlag =
Obj::areValidThresholdLevels(DATA[i].d_recordLevel,
DATA[i].d_passLevel,
DATA[i].d_triggerLevel,
DATA[i].d_triggerAllLevel);
LOOP_ASSERT(LINE, isValidFlag == DATA[i].d_isValidFlag);
}
} break;
case 10: {
// --------------------------------------------------------------------
// TESTING 'setLevels' FUNCTION:
// The 'setLevels' function should correctly pass the specified
// value to the object.
//
// Plan:
// For a sequence of independent valid test values, use the
// constructor to create an object and then use the 'setLevels'
// function to set its value. For the set of destination values
// that are valid, verify that the value has been correctly passed
// to the object. Otherwise, verify that the original value of the
// object is retained.
//
// Testing:
// void setLevels(int, int, int, int);
// --------------------------------------------------------------------
if (verbose) cout << "\nTesting 'setLevels' function"
<< "\n============================" << endl;
for (int i = 0; i < NUM_DATA && DATA[i].d_isValidFlag; ++i) {
const int LINE1 = DATA[i].d_line;
for (int j = 0; j < NUM_DATA; ++j) {
const int LINE2 = DATA[j].d_line;
Obj mX(DATA[i].d_recordLevel,
DATA[i].d_passLevel,
DATA[i].d_triggerLevel,
DATA[i].d_triggerAllLevel);
const Obj& X = mX;
if (veryVerbose) {
P_(LINE1);
P_(X);
P_(LINE2);
P_(DATA[j].d_recordLevel);
P_(DATA[j].d_passLevel);
P_(DATA[j].d_triggerLevel);
P(DATA[j].d_triggerAllLevel);
}
mX.setLevels(DATA[j].d_recordLevel,
DATA[j].d_passLevel,
DATA[j].d_triggerLevel,
DATA[j].d_triggerAllLevel);
int k = DATA[j].d_isValidFlag ? j : i;
LOOP2_ASSERT(LINE1,
LINE2,
X.recordLevel() == DATA[k].d_recordLevel);
LOOP2_ASSERT(LINE1,
LINE2,
X.passLevel() == DATA[k].d_passLevel);
LOOP2_ASSERT(LINE1,
LINE2,
X.triggerLevel() == DATA[k].d_triggerLevel);
LOOP2_ASSERT(LINE1,
LINE2,
X.triggerAllLevel() == DATA[k].d_triggerAllLevel);
}
}
} break;
case 9: {
// --------------------------------------------------------------------
// TESTING ASSIGNMENT OPERATOR:
// Any value must be assignable to an object having any initial value
// without affecting the rhs operand value. Also, any object must be
// assignable to itself.
//
// Plan:
// Specify a set S of (unique) objects with substantial and varied
// differences in value. Construct and initialize all combinations
// (u, v) in the cross product S x S, copy construct a control w from
// v, assign v to u, and assert that w == u and w == v. Then test
// aliasing by copy constructing a control w from each u in S,
// assigning u to itself, and verifying that w == u.
//
// Testing:
// const ball::TA& operator=(const ball::TA& other)
// --------------------------------------------------------------------
if (verbose) cout << "\nTesting Assigment Operator"
<< "\n==========================" << endl;
if (verbose) cout << "\nTesting non-alias case." << endl;
for (int i = 0; i < NUM_DATA && DATA[i].d_isValidFlag; ++i) {
const int LINE1 = DATA[i].d_line;
for (int j = 0; j < NUM_DATA && DATA[j].d_isValidFlag; ++j) {
const int LINE2 = DATA[j].d_line;
if (veryVerbose) {
P_(LINE1);
P_(DATA[i].d_recordLevel);
P_(DATA[i].d_passLevel);
P_(DATA[i].d_triggerLevel);
P(DATA[i].d_triggerAllLevel);
P_(LINE2);
P_(DATA[j].d_recordLevel);
P_(DATA[j].d_passLevel);
P_(DATA[j].d_triggerLevel);
P(DATA[j].d_triggerAllLevel);
}
Obj mX(DATA[i].d_recordLevel,
DATA[i].d_passLevel,
DATA[i].d_triggerLevel,
DATA[i].d_triggerAllLevel);
const Obj& X = mX;
Obj mY(DATA[j].d_recordLevel,
DATA[j].d_passLevel,
DATA[j].d_triggerLevel,
DATA[j].d_triggerAllLevel);
const Obj& Y = mY;
Obj mW(Y); const Obj& W = mW;
mX = Y;
ASSERT(W == X);
ASSERT(W == Y);
}
}
if (verbose) cout << "\nTesting alias case." << endl;
for (int i = 0; i < NUM_DATA && DATA[i].d_isValidFlag; ++i) {
const int LINE = DATA[i].d_line;
if (veryVerbose) {
P_(LINE);
P_(DATA[i].d_recordLevel);
P_(DATA[i].d_passLevel);
P_(DATA[i].d_triggerLevel);
P(DATA[i].d_triggerAllLevel);
}
Obj mX(DATA[i].d_recordLevel,
DATA[i].d_passLevel,
DATA[i].d_triggerLevel,
DATA[i].d_triggerAllLevel);
const Obj& X = mX;
Obj mW(X); const Obj& W = mW;
mX = X;
ASSERT(W == X);
}
} break;
case 8: {
// --------------------------------------------------------------------
// TESTING SECONDARY TEST APPARATUS:
// Void for 'ball::ThresholdAggregate'.
// --------------------------------------------------------------------
} break;
case 7: {
// --------------------------------------------------------------------
// TESTING COPY CONSTRUCTOR:
// Any value must be able to be copy constructed without affecting
// its argument.
//
// Plan:
// Specify a set S whose elements have substantial and varied
// differences in value. For each element in S, construct and
// initialize identically valued objects w and x using tested
// methods. Then copy construct an object y from x, and use the
// equality operator to assert that both x and y have the same value
// as w.
//
// Testing:
// ball::ThresholdAggregate(const ball::TA&, bdema::Alct * = 0)
// --------------------------------------------------------------------
if (verbose) cout << "\nTesting Copy Constructor"
<< "\n========================" << endl;
for (int i = 0; i < NUM_DATA && DATA[i].d_isValidFlag; ++i) {
const int LINE = DATA[i].d_line;
if (veryVerbose) {
P_(LINE);
P_(DATA[i].d_recordLevel);
P_(DATA[i].d_passLevel);
P_(DATA[i].d_triggerLevel);
P(DATA[i].d_triggerAllLevel);
}
Obj w(DATA[i].d_recordLevel,
DATA[i].d_passLevel,
DATA[i].d_triggerLevel,
DATA[i].d_triggerAllLevel);
const Obj& W = w; // control
Obj x(DATA[i].d_recordLevel,
DATA[i].d_passLevel,
DATA[i].d_triggerLevel,
DATA[i].d_triggerAllLevel);
const Obj& X = x;
Obj y(X); const Obj &Y = y;
LOOP_ASSERT(LINE, X == W);
LOOP_ASSERT(LINE, Y == W);
}
} break;
case 6: {
// --------------------------------------------------------------------
// TESTING EQUALITY OPERATORS:
// Any subtle variation in value must be detected by the equality
// operators.
//
// Plan:
// Specify a set S of unique object values that may have various
// minor or subtle differences. Verify the correctness of
// 'operator==' and 'operator!=' using all elements (u, v) of the
// cross product S X S.
//
// Testing:
// bool operator==(const ball::TA& lhs, const ball::TA& rhs)
// bool operator!=(const ball::TA& lhs, const ball::TA& rhs)
// --------------------------------------------------------------------
if (verbose) cout << "\nTesting Equality Operators"
<< "\n==========================" << endl;
for (int i = 0; i < NUM_DATA && DATA[i].d_isValidFlag; ++i) {
const int LINE1 = DATA[i].d_line;
for (int j = 0; j < NUM_DATA && DATA[j].d_isValidFlag; ++j) {
const int LINE2 = DATA[j].d_line;
if (veryVerbose) {
P_(LINE1);
P_(DATA[i].d_recordLevel);
P_(DATA[i].d_passLevel);
P_(DATA[i].d_triggerLevel);
P(DATA[i].d_triggerAllLevel);
P_(LINE2);
P_(DATA[j].d_recordLevel);
P_(DATA[j].d_passLevel);
P_(DATA[j].d_triggerLevel);
P(DATA[j].d_triggerAllLevel);
}
Obj mX(DATA[i].d_recordLevel,
DATA[i].d_passLevel,
DATA[i].d_triggerLevel,
DATA[i].d_triggerAllLevel);
const Obj& X = mX;
Obj mY(DATA[j].d_recordLevel,
DATA[j].d_passLevel,
DATA[j].d_triggerLevel,
DATA[j].d_triggerAllLevel);
const Obj& Y = mY;
ASSERT((i==j) == (X == Y));
ASSERT((i!=j) == (X != Y));
}
}
} break;
case 5: {
// --------------------------------------------------------------------
// TESTING 'operator<<' AND 'print':
// The output operator and 'print' method should print out the value
// of objects in the expected format.
//
// Plan:
// For each of a small representative set of object values, use
// 'ostrstream' to write that object's value to a character buffer
// and then compare the contents of that buffer with the expected
// output format.
//
// Testing:
// bsl::ostream& operator<<(bsl::ostream&, const ball::TA&)
// --------------------------------------------------------------------
if (verbose) cout << endl
<< "Testing 'operator<<' and 'print'" << endl
<< "================================" << endl;
if (verbose) cout << "\nTesting 'operator<<' (ostream)." << endl;
static const struct {
int d_line; // line number
int d_recordLevel; // record level
int d_passLevel; // pass level
int d_triggerLevel; // trigger level
int d_triggerAllLevel; // trigger all level
const char *d_output; // expected output format
} DATA[] = {
///line rec pass trig trAll expected
///no. level level level level output
///---- ----- ----- ---- ----- --------
{ L_, 0, 0, 0, 0, "[ 0 0 0 0 ] " },
{ L_, 1, 0, 0, 0, "[ 1 0 0 0 ] " },
{ L_, 64, 48, 32, 16, "[ 64 48 32 16 ] " },
{ L_, 255, 0, 0, 0, "[ 255 0 0 0 ] " },
{ L_, 255, 255, 255, 255, "[ 255 255 255 255 ] " },
};
const int NUM_DATA = sizeof DATA / sizeof *DATA;
for (int i = 0; i < NUM_DATA; ++i) {
const int LINE = DATA[i].d_line;
if (veryVerbose) {
P_(LINE);
P_(DATA[i].d_recordLevel);
P_(DATA[i].d_passLevel);
P_(DATA[i].d_triggerLevel);
P_(DATA[i].d_triggerAllLevel);
P(DATA[i].d_output);
}
Obj mX(DATA[i].d_recordLevel,
DATA[i].d_passLevel,
DATA[i].d_triggerLevel,
DATA[i].d_triggerAllLevel);
const Obj& X = mX;
ostringstream os;
os << X;
LOOP_ASSERT(LINE, os.str() == DATA[i].d_output);
}
if (verbose) cout << "\nTesting 'print'." << endl;
static const struct {
int d_line; // line number
int d_level; // tab level
int d_spacesPerLevel; // spaces per level
const char *d_output; // expected output format
} PDATA[] = {
// line level space expected
// ---- ---- ----- -----------------------
{ L_, 0, -1, "[ 192 160 128 96 ] " },
{ L_, 1, 2, " [\n"
" 192\n"
" 160\n"
" 128\n"
" 96\n"
" ]\n" },
{ L_, -1, -2, "[ 192 160 128 96 ] " },
};
const int NUM_PDATA = sizeof PDATA / sizeof *PDATA;
for (int i = 0; i < NUM_PDATA; ++i) {
int LINE = PDATA[i].d_line;
const Obj X(VA);
ostringstream os;
X.print(os, PDATA[i].d_level, PDATA[i].d_spacesPerLevel);
if (veryVerbose) {
P_(LINE);
P_(X);
P(PDATA[i].d_output);
P_(os.str()); cout << endl;
}
LOOP_ASSERT(LINE, os.str() == PDATA[i].d_output);
}
} break;
case 4: {
// --------------------------------------------------------------------
// TESTING BASIC ACCESSORS:
// Basic accessors must correctly return each individual field.
//
// Plan:
// For a sequence of independent valid test values, use the
// constructor to create an object having the specified value and
// then use the basic accessors to verify that they return the
// correct value.
//
// Testing:
// int recordLevel() const;
// int passLevel() const;
// int triggerLevel() const;
// int triggerAllLevel() const;
// --------------------------------------------------------------------
if (verbose) cout << "\nTesting Basic Accessors"
<< "\n=======================" << endl;
for (int i = 0; i < NUM_DATA && DATA[i].d_isValidFlag; ++i) {
const int LINE = DATA[i].d_line;
const int ISVALIDFLAG = DATA[i].d_isValidFlag;
if (veryVerbose) {
P_(LINE);
P_(DATA[i].d_recordLevel);
P_(DATA[i].d_passLevel);
P_(DATA[i].d_triggerLevel);
P_(DATA[i].d_triggerAllLevel);
P(ISVALIDFLAG);
}
const Obj X(DATA[i].d_recordLevel,
DATA[i].d_passLevel,
DATA[i].d_triggerLevel,
DATA[i].d_triggerAllLevel);
LOOP_ASSERT(LINE, X.recordLevel() == DATA[i].d_recordLevel);
LOOP_ASSERT(LINE, X.passLevel() == DATA[i].d_passLevel);
LOOP_ASSERT(LINE, X.triggerLevel() == DATA[i].d_triggerLevel);
LOOP_ASSERT(LINE, X.triggerAllLevel()
== DATA[i].d_triggerAllLevel);
}
} break;
case 3: {
// --------------------------------------------------------------------
// TESTING PRIMITIVE TEST APPARATUS:
// Void for 'ball::ThresholdAggregate'.
// --------------------------------------------------------------------
} break;
case 2: {
// --------------------------------------------------------------------
// TESTING PRIMARY MANIPULATORS (BOOTSTRAP):
// Primary manipulator should correctly pass the specified value to
// the object.
//
// Plan:
// For a sequence of independent valid test values, use the
// constructor to create an object having the specified
// value. Verify, using the basic accessors, that the object has the
// expected value.
//
// Testing:
// ball::ThresholdAggregate(int, int, int, int);
// ~ball::ThresholdAggregate();
// --------------------------------------------------------------------
if (verbose) cout << "\nTesting Primary Manipulator"
<< "\n===========================" << endl;
for (int i = 0; i < NUM_DATA && DATA[i].d_isValidFlag; ++i) {
const int LINE = DATA[i].d_line;
const int ISVALIDFLAG = DATA[i].d_isValidFlag;
if (veryVerbose) {
P_(LINE);
P_(DATA[i].d_recordLevel);
P_(DATA[i].d_passLevel);
P_(DATA[i].d_triggerLevel);
P_(DATA[i].d_triggerAllLevel);
P(ISVALIDFLAG);
}
const Obj X(DATA[i].d_recordLevel,
DATA[i].d_passLevel,
DATA[i].d_triggerLevel,
DATA[i].d_triggerAllLevel);
LOOP_ASSERT(LINE, X.recordLevel() == DATA[i].d_recordLevel);
LOOP_ASSERT(LINE, X.passLevel() == DATA[i].d_passLevel);
LOOP_ASSERT(LINE, X.triggerLevel() == DATA[i].d_triggerLevel);
LOOP_ASSERT(LINE, X.triggerAllLevel()
== DATA[i].d_triggerAllLevel);
}
} break;
case 1: {
// --------------------------------------------------------------------
// BREATHING TEST:
// Exercise a broad cross-section of value-semantic functionality
// before beginning testing in earnest. Probe that functionality
// systematically and incrementally to discover basic errors in
// isolation.
//
// Plan:
// Create four test objects by using the initializing and copy
// constructors. Exercise the basic value-semantic methods and the
// equality operators using these test objects. Invoke the primary
// manipulator [3, 6], copy constructor [2, 8], and assignment
// operator without [9, 10] and with [11] aliasing. Use the direct
// accessors to verify the expected results. Display object values
// frequently in verbose mode. Note that 'VA', 'VB', and 'VC'
// denote unique, but otherwise arbitrary, object values, while '0'
// denotes the default object value.
//
// 1. Create an object x1 using VA. { x1:VA }
// 2. Create an object x2 (copy from x1). { x1:VA x2:VA }
// 3. Set x1 to VB. { x1:VB x2:VA }
// 4. Set x2 to VB. { x1:VB x2:VB }
// 5. Set x2 to VC. { x1:VB x2:VC }
// 6. Set x1 to VA. { x1:VA x2:VC }
// 7. Create an object x3 (with value VD). { x1:VA x2:VC x3:VD }
// 8. Create an object x4 (copy from x1). { x1:VA x2:VC x3:VD x4:VA }
// 9. Assign x2 = x1. { x1:VA x2:VA x3:VD x4:VA }
// 10. Assign x2 = x3. { x1:VA x2:VD x3:VD x4:VA }
// 11. Assign x1 = x1 (aliasing). { x1:VA x2:VD x3:VD x4:VA }
//
// Testing:
// This Test Case exercises basic value-semantic functionality.
// --------------------------------------------------------------------
if (verbose) cout << "\nBREATHING TEST"
<< "\n==============" << endl;
if (verbose) cout << "\n 1. Create an object x1 using VA." << endl;
Obj mX1(VA); const Obj& X1 = mX1;
ASSERT(VA1 == X1.recordLevel());
ASSERT(VA2 == X1.passLevel());
ASSERT(VA3 == X1.triggerLevel());
ASSERT(VA4 == X1.triggerAllLevel());
if (verbose) cout << "\n 2. Create an object x2 (copy from x1)."
<< endl;
Obj mX2(X1); const Obj& X2 = mX2;
ASSERT(VA1 == X2.recordLevel());
ASSERT(VA2 == X2.passLevel());
ASSERT(VA3 == X2.triggerLevel());
ASSERT(VA4 == X2.triggerAllLevel());
ASSERT(1 == (X2 == X1)); ASSERT(0 == (X2 != X1));
ASSERT(1 == (X2 == X2)); ASSERT(0 == (X2 != X2));
if (verbose) cout << "\n 3. Set x1 to VB." << endl;
mX1.setLevels(VB);
ASSERT(VB1 == X1.recordLevel());
ASSERT(VB2 == X1.passLevel());
ASSERT(VB3 == X1.triggerLevel());
ASSERT(VB4 == X1.triggerAllLevel());
ASSERT(1 == (X1 == X1)); ASSERT(0 == (X1 != X1));
ASSERT(0 == (X1 == X2)); ASSERT(1 == (X1 != X2));
if (verbose) cout << "\n 4. Set x2 to VB." << endl;
mX2.setLevels(VB);
ASSERT(VB1 == X2.recordLevel());
ASSERT(VB2 == X2.passLevel());
ASSERT(VB3 == X2.triggerLevel());
ASSERT(VB4 == X2.triggerAllLevel());
ASSERT(1 == (X2 == X2)); ASSERT(0 == (X2 != X2));
ASSERT(1 == (X1 == X2)); ASSERT(0 == (X1 != X2));
if (verbose) cout << "\n 5. Set x2 to VC." << endl;
mX2.setLevels(VC);
ASSERT(VC1 == X2.recordLevel());
ASSERT(VC2 == X2.passLevel());
ASSERT(VC3 == X2.triggerLevel());
ASSERT(VC4 == X2.triggerAllLevel());
ASSERT(1 == (X2 == X2)); ASSERT(0 == (X2 != X2));
ASSERT(0 == (X1 == X2)); ASSERT(1 == (X1 != X2));
if (verbose) cout << "\n 6. Set x1 to VA." << endl;
mX1.setLevels(VA);
ASSERT(VA1 == X1.recordLevel());
ASSERT(VA2 == X1.passLevel());
ASSERT(VA3 == X1.triggerLevel());
ASSERT(VA4 == X1.triggerAllLevel());
ASSERT(1 == (X1 == X1)); ASSERT(0 == (X1 != X1));
ASSERT(0 == (X1 == X2)); ASSERT(1 == (X1 != X2));
if (verbose) cout << "\n 7. Create an object x3 (with value VD)."
<< endl;
Obj mX3(VD); const Obj& X3 = mX3;
ASSERT(VD1 == X3.recordLevel());
ASSERT(VD2 == X3.passLevel());
ASSERT(VD3 == X3.triggerLevel());
ASSERT(VD4 == X3.triggerAllLevel());
ASSERT(1 == (X3 == X3)); ASSERT(0 == (X3 != X3));
ASSERT(0 == (X3 == X1)); ASSERT(1 == (X3 != X1));
ASSERT(0 == (X3 == X2)); ASSERT(1 == (X3 != X2));
if (verbose) cout << "\n 8. Create an object x4 (copy from x1)."
<< endl;
Obj mX4(X1); const Obj& X4 = mX4;
ASSERT(VA1 == X4.recordLevel());
ASSERT(VA2 == X4.passLevel());
ASSERT(VA3 == X4.triggerLevel());
ASSERT(VA4 == X4.triggerAllLevel());
ASSERT(1 == (X4 == X1)); ASSERT(0 == (X4 != X1));
ASSERT(0 == (X4 == X2)); ASSERT(1 == (X4 != X2));
ASSERT(0 == (X4 == X3)); ASSERT(1 == (X4 != X3));
ASSERT(1 == (X4 == X4)); ASSERT(0 == (X4 != X4));
if (verbose) cout << "\n 9. Assign x2 = x1." << endl;
mX2 = X1;
ASSERT(VA1 == X2.recordLevel());
ASSERT(VA2 == X2.passLevel());
ASSERT(VA3 == X2.triggerLevel());
ASSERT(VA4 == X2.triggerAllLevel());
ASSERT(1 == (X2 == X1)); ASSERT(0 == (X2 != X1));
ASSERT(1 == (X2 == X2)); ASSERT(0 == (X2 != X2));
ASSERT(0 == (X2 == X3)); ASSERT(1 == (X2 != X3));
ASSERT(1 == (X2 == X4)); ASSERT(0 == (X2 != X4));
if (verbose) cout << "\n 10. Assign x2 = x3." << endl;
mX2 = X3;
ASSERT(VD1 == X2.recordLevel());
ASSERT(VD2 == X2.passLevel());
ASSERT(VD3 == X2.triggerLevel());
ASSERT(VD4 == X2.triggerAllLevel());
ASSERT(0 == (X2 == X1)); ASSERT(1 == (X2 != X1));
ASSERT(1 == (X2 == X2)); ASSERT(0 == (X2 != X2));
ASSERT(1 == (X2 == X3)); ASSERT(0 == (X2 != X3));
ASSERT(0 == (X2 == X4)); ASSERT(1 == (X2 != X4));
if (verbose) cout << "\n 11. Assign x1 = x1 (aliasing)." << endl;
mX1 = X1;
ASSERT(VA1 == X1.recordLevel());
ASSERT(VA2 == X1.passLevel());
ASSERT(VA3 == X1.triggerLevel());
ASSERT(VA4 == X1.triggerAllLevel());
ASSERT(1 == (X1 == X1)); ASSERT(0 == (X1 != X1));
ASSERT(0 == (X1 == X2)); ASSERT(1 == (X1 != X2));
ASSERT(0 == (X1 == X3)); ASSERT(1 == (X1 != X3));
ASSERT(1 == (X1 == X4)); ASSERT(0 == (X1 != X4));
} break;
default: {
cerr << "WARNING: CASE `" << test << "' NOT FOUND." << endl;
testStatus = -1;
} break;
}
if (testStatus > 0) {
cerr << "Error, non-zero test status = " << testStatus << "." << endl;
}
return testStatus;
}
// ----------------------------------------------------------------------------
// Copyright 2015 Bloomberg Finance L.P.
//
// 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.
// ----------------------------- END-OF-FILE ----------------------------------
|
/*
* TLogServer.actor.cpp
*
* This source file is part of the FoundationDB open source project
*
* Copyright 2013-2018 Apple Inc. and the FoundationDB project 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 "flow/Hash3.h"
#include "flow/Stats.h"
#include "flow/UnitTest.h"
#include "fdbclient/NativeAPI.actor.h"
#include "fdbclient/Notified.h"
#include "fdbclient/KeyRangeMap.h"
#include "fdbclient/RunTransaction.actor.h"
#include "fdbclient/SystemData.h"
#include "fdbserver/WorkerInterface.actor.h"
#include "fdbserver/TLogInterface.h"
#include "fdbserver/Knobs.h"
#include "fdbserver/IKeyValueStore.h"
#include "flow/ActorCollection.h"
#include "fdbrpc/FailureMonitor.h"
#include "fdbserver/IDiskQueue.h"
#include "fdbrpc/sim_validation.h"
#include "fdbrpc/simulator.h"
#include "fdbserver/ServerDBInfo.h"
#include "fdbserver/LogSystem.h"
#include "fdbserver/WaitFailure.h"
#include "fdbserver/RecoveryState.h"
#include "fdbserver/FDBExecHelper.actor.h"
#include "flow/actorcompiler.h" // This must be the last #include.
using std::pair;
using std::make_pair;
using std::min;
using std::max;
namespace oldTLog_6_0 {
struct TLogQueueEntryRef {
UID id;
Version version;
Version knownCommittedVersion;
StringRef messages;
TLogQueueEntryRef() : version(0), knownCommittedVersion(0) {}
TLogQueueEntryRef(Arena &a, TLogQueueEntryRef const &from)
: version(from.version), knownCommittedVersion(from.knownCommittedVersion), id(from.id), messages(a, from.messages) {
}
template <class Ar>
void serialize(Ar& ar) {
serializer(ar, version, messages, knownCommittedVersion, id);
}
size_t expectedSize() const {
return messages.expectedSize();
}
};
struct AlternativeTLogQueueEntryRef {
UID id;
Version version;
Version knownCommittedVersion;
std::vector<TagsAndMessage>* alternativeMessages;
AlternativeTLogQueueEntryRef() : version(0), knownCommittedVersion(0), alternativeMessages(NULL) {}
template <class Ar>
void serialize(Ar& ar) {
ASSERT(!ar.isDeserializing && alternativeMessages);
uint32_t msgSize = expectedSize();
serializer(ar, version, msgSize);
for(auto& msg : *alternativeMessages) {
ar.serializeBytes( msg.message );
}
serializer(ar, knownCommittedVersion, id);
}
uint32_t expectedSize() const {
uint32_t msgSize = 0;
for(auto& msg : *alternativeMessages) {
msgSize += msg.message.size();
}
return msgSize;
}
};
typedef Standalone<TLogQueueEntryRef> TLogQueueEntry;
struct LogData;
struct TLogData;
struct TLogQueue : public IClosable {
public:
TLogQueue( IDiskQueue* queue, UID dbgid ) : queue(queue), dbgid(dbgid) {}
// Each packet in the queue is
// uint32_t payloadSize
// uint8_t payload[payloadSize] (begins with uint64_t protocolVersion via IncludeVersion)
// uint8_t validFlag
// TLogQueue is a durable queue of TLogQueueEntry objects with an interface similar to IDiskQueue
// TLogQueue pushes (but not commits) are atomic - after commit fails to return, a prefix of entire calls to push are durable. This is
// implemented on top of the weaker guarantee of IDiskQueue::commit (that a prefix of bytes is durable) using validFlag and by
// padding any incomplete packet with zeros after recovery.
// Before calling push, pop, or commit, the user must call readNext() until it throws
// end_of_stream(). It may not be called again thereafter.
Future<TLogQueueEntry> readNext( TLogData* tLog ) {
return readNext( this, tLog );
}
template <class T>
void push( T const& qe, Reference<LogData> logData );
void pop( Version upTo, Reference<LogData> logData );
Future<Void> commit() { return queue->commit(); }
// Implements IClosable
virtual Future<Void> getError() { return queue->getError(); }
virtual Future<Void> onClosed() { return queue->onClosed(); }
virtual void dispose() { queue->dispose(); delete this; }
virtual void close() { queue->close(); delete this; }
private:
IDiskQueue* queue;
UID dbgid;
void updateVersionSizes( const TLogQueueEntry& result, TLogData* tLog );
ACTOR static Future<TLogQueueEntry> readNext( TLogQueue* self, TLogData* tLog ) {
state TLogQueueEntry result;
state int zeroFillSize = 0;
loop {
Standalone<StringRef> h = wait( self->queue->readNext( sizeof(uint32_t) ) );
if (h.size() != sizeof(uint32_t)) {
if (h.size()) {
TEST( true ); // Zero fill within size field
int payloadSize = 0;
memcpy(&payloadSize, h.begin(), h.size());
zeroFillSize = sizeof(uint32_t)-h.size(); // zero fill the size itself
zeroFillSize += payloadSize+1; // and then the contents and valid flag
}
break;
}
state uint32_t payloadSize = *(uint32_t*)h.begin();
ASSERT( payloadSize < (100<<20) );
Standalone<StringRef> e = wait( self->queue->readNext( payloadSize+1 ) );
if (e.size() != payloadSize+1) {
TEST( true ); // Zero fill within payload
zeroFillSize = payloadSize+1 - e.size();
break;
}
if (e[payloadSize]) {
Arena a = e.arena();
ArenaReader ar( a, e.substr(0, payloadSize), IncludeVersion() );
ar >> result;
self->updateVersionSizes(result, tLog);
return result;
}
}
if (zeroFillSize) {
TEST( true ); // Fixing a partial commit at the end of the tlog queue
for(int i=0; i<zeroFillSize; i++)
self->queue->push( StringRef((const uint8_t*)"",1) );
}
throw end_of_stream();
}
};
////// Persistence format (for self->persistentData)
// Immutable keys
static const KeyValueRef persistFormat( LiteralStringRef( "Format" ), LiteralStringRef("FoundationDB/LogServer/2/4") );
static const KeyRangeRef persistFormatReadableRange( LiteralStringRef("FoundationDB/LogServer/2/3"), LiteralStringRef("FoundationDB/LogServer/2/5") );
static const KeyRangeRef persistRecoveryCountKeys = KeyRangeRef( LiteralStringRef( "DbRecoveryCount/" ), LiteralStringRef( "DbRecoveryCount0" ) );
// Updated on updatePersistentData()
static const KeyRangeRef persistCurrentVersionKeys = KeyRangeRef( LiteralStringRef( "version/" ), LiteralStringRef( "version0" ) );
static const KeyRangeRef persistKnownCommittedVersionKeys = KeyRangeRef( LiteralStringRef( "knownCommitted/" ), LiteralStringRef( "knownCommitted0" ) );
static const KeyRangeRef persistLocalityKeys = KeyRangeRef( LiteralStringRef( "Locality/" ), LiteralStringRef( "Locality0" ) );
static const KeyRangeRef persistLogRouterTagsKeys = KeyRangeRef( LiteralStringRef( "LogRouterTags/" ), LiteralStringRef( "LogRouterTags0" ) );
static const KeyRangeRef persistTxsTagsKeys = KeyRangeRef( LiteralStringRef( "TxsTags/" ), LiteralStringRef( "TxsTags0" ) );
static const KeyRange persistTagMessagesKeys = prefixRange(LiteralStringRef("TagMsg/"));
static const KeyRange persistTagPoppedKeys = prefixRange(LiteralStringRef("TagPop/"));
static Key persistTagMessagesKey( UID id, Tag tag, Version version ) {
BinaryWriter wr( Unversioned() );
wr.serializeBytes(persistTagMessagesKeys.begin);
wr << id;
wr << tag;
wr << bigEndian64( version );
return wr.toValue();
}
static Key persistTagPoppedKey( UID id, Tag tag ) {
BinaryWriter wr(Unversioned());
wr.serializeBytes( persistTagPoppedKeys.begin );
wr << id;
wr << tag;
return wr.toValue();
}
static Value persistTagPoppedValue( Version popped ) {
return BinaryWriter::toValue( popped, Unversioned() );
}
static Tag decodeTagPoppedKey( KeyRef id, KeyRef key ) {
Tag s;
BinaryReader rd( key.removePrefix(persistTagPoppedKeys.begin).removePrefix(id), Unversioned() );
rd >> s;
return s;
}
static Version decodeTagPoppedValue( ValueRef value ) {
return BinaryReader::fromStringRef<Version>( value, Unversioned() );
}
static StringRef stripTagMessagesKey( StringRef key ) {
return key.substr( sizeof(UID) + sizeof(Tag) + persistTagMessagesKeys.begin.size() );
}
static Version decodeTagMessagesKey( StringRef key ) {
return bigEndian64( BinaryReader::fromStringRef<Version>( stripTagMessagesKey(key), Unversioned() ) );
}
struct TLogData : NonCopyable {
AsyncTrigger newLogData;
Deque<UID> queueOrder;
std::map<UID, Reference<struct LogData>> id_data;
UID dbgid;
UID workerID;
IKeyValueStore* persistentData;
IDiskQueue* rawPersistentQueue;
TLogQueue *persistentQueue;
int64_t diskQueueCommitBytes;
AsyncVar<bool> largeDiskQueueCommitBytes; //becomes true when diskQueueCommitBytes is greater than MAX_QUEUE_COMMIT_BYTES
Reference<AsyncVar<ServerDBInfo>> dbInfo;
Database cx;
NotifiedVersion queueCommitEnd;
Version queueCommitBegin;
int64_t instanceID;
int64_t bytesInput;
int64_t bytesDurable;
int64_t targetVolatileBytes; // The number of bytes of mutations this TLog should hold in memory before spilling.
int64_t overheadBytesInput;
int64_t overheadBytesDurable;
WorkerCache<TLogInterface> tlogCache;
PromiseStream<Future<Void>> sharedActors;
Promise<Void> terminated;
FlowLock concurrentLogRouterReads;
FlowLock persistentDataCommitLock;
bool ignorePopRequest; // ignore pop request from storage servers
double ignorePopDeadline; // time until which the ignorePopRequest will be
// honored
std::string ignorePopUid; // callers that set ignorePopRequest will set this
// extra state, used to validate the ownership of
// the set and for callers that unset will
// be able to match it up
std::string dataFolder; // folder where data is stored
std::map<Tag, Version> toBePopped; // map of Tag->Version for all the pops
// that came when ignorePopRequest was set
Reference<AsyncVar<bool>> degraded;
std::vector<TagsAndMessage> tempTagMessages;
TLogData(UID dbgid, UID workerID, IKeyValueStore* persistentData, IDiskQueue * persistentQueue, Reference<AsyncVar<ServerDBInfo>> dbInfo, Reference<AsyncVar<bool>> degraded, std::string folder)
: dbgid(dbgid), workerID(workerID), instanceID(deterministicRandom()->randomUniqueID().first()),
persistentData(persistentData), rawPersistentQueue(persistentQueue), persistentQueue(new TLogQueue(persistentQueue, dbgid)),
dbInfo(dbInfo), degraded(degraded), queueCommitBegin(0), queueCommitEnd(0),
diskQueueCommitBytes(0), largeDiskQueueCommitBytes(false), bytesInput(0), bytesDurable(0), targetVolatileBytes(SERVER_KNOBS->TLOG_SPILL_THRESHOLD), overheadBytesInput(0), overheadBytesDurable(0),
concurrentLogRouterReads(SERVER_KNOBS->CONCURRENT_LOG_ROUTER_READS),
ignorePopRequest(false), ignorePopDeadline(), ignorePopUid(), dataFolder(folder), toBePopped()
{
cx = openDBOnServer(dbInfo, TaskPriority::DefaultEndpoint, true, true);
}
};
struct LogData : NonCopyable, public ReferenceCounted<LogData> {
struct TagData : NonCopyable, public ReferenceCounted<TagData> {
std::deque<std::pair<Version, LengthPrefixedStringRef>> versionMessages;
bool nothingPersistent; // true means tag is *known* to have no messages in persistentData. false means nothing.
bool poppedRecently; // `popped` has changed since last updatePersistentData
Version popped; // see popped version tracking contract below
bool unpoppedRecovered;
Tag tag;
TagData( Tag tag, Version popped, bool nothingPersistent, bool poppedRecently, bool unpoppedRecovered ) : tag(tag), nothingPersistent(nothingPersistent), popped(popped), poppedRecently(poppedRecently), unpoppedRecovered(unpoppedRecovered) {}
TagData(TagData&& r) noexcept
: versionMessages(std::move(r.versionMessages)), nothingPersistent(r.nothingPersistent),
poppedRecently(r.poppedRecently), popped(r.popped), tag(r.tag), unpoppedRecovered(r.unpoppedRecovered) {}
void operator=(TagData&& r) noexcept {
versionMessages = std::move(r.versionMessages);
nothingPersistent = r.nothingPersistent;
poppedRecently = r.poppedRecently;
popped = r.popped;
tag = r.tag;
unpoppedRecovered = r.unpoppedRecovered;
}
// Erase messages not needed to update *from* versions >= before (thus, messages with toversion <= before)
ACTOR Future<Void> eraseMessagesBefore( TagData *self, Version before, TLogData *tlogData, Reference<LogData> logData, TaskPriority taskID ) {
while(!self->versionMessages.empty() && self->versionMessages.front().first < before) {
Version version = self->versionMessages.front().first;
std::pair<int,int> &sizes = logData->version_sizes[version];
int64_t messagesErased = 0;
while(!self->versionMessages.empty() && self->versionMessages.front().first == version) {
auto const& m = self->versionMessages.front();
++messagesErased;
if(self->tag.locality != tagLocalityTxs && self->tag != txsTag) {
sizes.first -= m.second.expectedSize();
} else {
sizes.second -= m.second.expectedSize();
}
self->versionMessages.pop_front();
}
int64_t bytesErased = messagesErased * SERVER_KNOBS->VERSION_MESSAGES_ENTRY_BYTES_WITH_OVERHEAD;
logData->bytesDurable += bytesErased;
tlogData->bytesDurable += bytesErased;
tlogData->overheadBytesDurable += bytesErased;
wait(yield(taskID));
}
return Void();
}
Future<Void> eraseMessagesBefore(Version before, TLogData *tlogData, Reference<LogData> logData, TaskPriority taskID) {
return eraseMessagesBefore(this, before, tlogData, logData, taskID);
}
};
Map<Version, IDiskQueue::location> versionLocation; // For the version of each entry that was push()ed, the end location of the serialized bytes
/*
Popped version tracking contract needed by log system to implement ILogCursor::popped():
- Log server tracks for each (possible) tag a popped_version
Impl: TagData::popped (in memory) and persistTagPoppedKeys (in persistentData)
- popped_version(tag) is <= the maximum version for which log server (or a predecessor) is ever asked to pop the tag
Impl: Only increased by tLogPop() in response to either a pop request or recovery from a predecessor
- popped_version(tag) is > the maximum version for which log server is unable to peek messages due to previous pops (on this server or a predecessor)
Impl: Increased by tLogPop() atomically with erasing messages from memory; persisted by updatePersistentData() atomically with erasing messages from store; messages are not erased from queue where popped_version is not persisted
- LockTLogReply returns all tags which either have messages, or which have nonzero popped_versions
Impl: tag_data is present for all such tags
- peek(tag, v) returns the popped_version for tag if that is greater than v
Impl: Check tag_data->popped (after all waits)
*/
AsyncTrigger stopCommit;
bool stopped, initialized;
DBRecoveryCount recoveryCount;
VersionMetricHandle persistentDataVersion, persistentDataDurableVersion; // The last version number in the portion of the log (written|durable) to persistentData
NotifiedVersion version, queueCommittedVersion;
Version queueCommittingVersion;
Version knownCommittedVersion, durableKnownCommittedVersion, minKnownCommittedVersion;
// Track lastUpdate time for parallel peek and detect stall on tLogs
struct PeekTrackerData {
std::map<int, Promise<std::pair<Version, bool>>> sequence_version;
double lastUpdate;
Tag tag;
double lastLogged;
int64_t totalPeeks;
int64_t replyBytes;
int64_t duplicatePeeks;
double queueTime;
double queueMax;
double blockTime;
double blockMax;
double workTime;
double workMax;
int64_t unblockedPeeks;
double idleTime;
double idleMax;
PeekTrackerData() : lastUpdate(0) {
resetMetrics();
}
void resetMetrics() {
lastLogged = now();
totalPeeks = 0;
replyBytes = 0;
duplicatePeeks = 0;
queueTime = 0;
queueMax = 0;
blockTime = 0;
blockMax = 0;
workTime = 0;
workMax = 0;
unblockedPeeks = 0;
idleTime = 0;
idleMax = 0;
}
};
std::map<UID, PeekTrackerData> peekTracker;
Deque<std::pair<Version, Standalone<VectorRef<uint8_t>>>> messageBlocks;
std::vector<std::vector<Reference<TagData>>> tag_data; //tag.locality | tag.id
int unpoppedRecoveredTags;
Reference<TagData> getTagData(Tag tag) {
int idx = tag.toTagDataIndex();
if(idx >= tag_data.size()) {
tag_data.resize(idx+1);
}
if(tag.id >= tag_data[idx].size()) {
tag_data[idx].resize(tag.id+1);
}
return tag_data[idx][tag.id];
}
//only callable after getTagData returns a null reference
Reference<TagData> createTagData(Tag tag, Version popped, bool nothingPersistent, bool poppedRecently, bool unpoppedRecovered) {
if(tag.locality != tagLocalityLogRouter && tag.locality != tagLocalityTxs && tag != txsTag && allTags.size() && !allTags.count(tag) && popped <= recoveredAt) {
popped = recoveredAt + 1;
}
Reference<TagData> newTagData = Reference<TagData>( new TagData(tag, popped, nothingPersistent, poppedRecently, unpoppedRecovered) );
tag_data[tag.toTagDataIndex()][tag.id] = newTagData;
return newTagData;
}
Map<Version, std::pair<int,int>> version_sizes;
CounterCollection cc;
Counter bytesInput;
Counter bytesDurable;
UID logId;
Version newPersistentDataVersion;
Future<Void> removed;
PromiseStream<Future<Void>> addActor;
TLogData* tLogData;
Promise<Void> recoveryComplete, committingQueue;
Version unrecoveredBefore, recoveredAt;
Reference<AsyncVar<Reference<ILogSystem>>> logSystem;
Tag remoteTag;
bool isPrimary;
int logRouterTags;
Version logRouterPoppedVersion, logRouterPopToVersion;
int8_t locality;
UID recruitmentID;
std::set<Tag> allTags;
Future<Void> terminated;
FlowLock execOpLock;
bool execOpCommitInProgress;
int txsTags;
explicit LogData(TLogData* tLogData, TLogInterface interf, Tag remoteTag, bool isPrimary, int logRouterTags, int txsTags, UID recruitmentID, std::vector<Tag> tags, std::string context)
: tLogData(tLogData), knownCommittedVersion(0), logId(interf.id()),
cc("TLog", interf.id().toString()), bytesInput("BytesInput", cc), bytesDurable("BytesDurable", cc), remoteTag(remoteTag), isPrimary(isPrimary), logRouterTags(logRouterTags), txsTags(txsTags), recruitmentID(recruitmentID),
logSystem(new AsyncVar<Reference<ILogSystem>>()), logRouterPoppedVersion(0), durableKnownCommittedVersion(0), minKnownCommittedVersion(0), allTags(tags.begin(), tags.end()), terminated(tLogData->terminated.getFuture()),
// These are initialized differently on init() or recovery
recoveryCount(), stopped(false), initialized(false), queueCommittingVersion(0), newPersistentDataVersion(invalidVersion), unrecoveredBefore(1), recoveredAt(1), unpoppedRecoveredTags(0),
logRouterPopToVersion(0), locality(tagLocalityInvalid), execOpCommitInProgress(false)
{
startRole(Role::TRANSACTION_LOG, interf.id(), tLogData->workerID, {{"SharedTLog", tLogData->dbgid.shortString()}}, context);
addActor.send(traceRole(Role::TRANSACTION_LOG, interf.id()));
persistentDataVersion.init(LiteralStringRef("TLog.PersistentDataVersion"), cc.id);
persistentDataDurableVersion.init(LiteralStringRef("TLog.PersistentDataDurableVersion"), cc.id);
version.initMetric(LiteralStringRef("TLog.Version"), cc.id);
queueCommittedVersion.initMetric(LiteralStringRef("TLog.QueueCommittedVersion"), cc.id);
specialCounter(cc, "Version", [this](){ return this->version.get(); });
specialCounter(cc, "QueueCommittedVersion", [this](){ return this->queueCommittedVersion.get(); });
specialCounter(cc, "PersistentDataVersion", [this](){ return this->persistentDataVersion; });
specialCounter(cc, "PersistentDataDurableVersion", [this](){ return this->persistentDataDurableVersion; });
specialCounter(cc, "KnownCommittedVersion", [this](){ return this->knownCommittedVersion; });
specialCounter(cc, "QueuePoppedVersion", [this](){ return this->persistentDataDurableVersion; });
specialCounter(cc, "SharedBytesInput", [tLogData](){ return tLogData->bytesInput; });
specialCounter(cc, "SharedBytesDurable", [tLogData](){ return tLogData->bytesDurable; });
specialCounter(cc, "SharedOverheadBytesInput", [tLogData](){ return tLogData->overheadBytesInput; });
specialCounter(cc, "SharedOverheadBytesDurable", [tLogData](){ return tLogData->overheadBytesDurable; });
specialCounter(cc, "KvstoreBytesUsed", [tLogData](){ return tLogData->persistentData->getStorageBytes().used; });
specialCounter(cc, "KvstoreBytesFree", [tLogData](){ return tLogData->persistentData->getStorageBytes().free; });
specialCounter(cc, "KvstoreBytesAvailable", [tLogData](){ return tLogData->persistentData->getStorageBytes().available; });
specialCounter(cc, "KvstoreBytesTotal", [tLogData](){ return tLogData->persistentData->getStorageBytes().total; });
specialCounter(cc, "QueueDiskBytesUsed", [tLogData](){ return tLogData->rawPersistentQueue->getStorageBytes().used; });
specialCounter(cc, "QueueDiskBytesFree", [tLogData](){ return tLogData->rawPersistentQueue->getStorageBytes().free; });
specialCounter(cc, "QueueDiskBytesAvailable", [tLogData](){ return tLogData->rawPersistentQueue->getStorageBytes().available; });
specialCounter(cc, "QueueDiskBytesTotal", [tLogData](){ return tLogData->rawPersistentQueue->getStorageBytes().total; });
}
~LogData() {
endRole(Role::TRANSACTION_LOG, logId, "Error", true);
if(!terminated.isReady()) {
tLogData->bytesDurable += bytesInput.getValue() - bytesDurable.getValue();
TraceEvent("TLogBytesWhenRemoved", logId).detail("SharedBytesInput", tLogData->bytesInput).detail("SharedBytesDurable", tLogData->bytesDurable).detail("LocalBytesInput", bytesInput.getValue()).detail("LocalBytesDurable", bytesDurable.getValue());
ASSERT_ABORT(tLogData->bytesDurable <= tLogData->bytesInput);
Key logIdKey = BinaryWriter::toValue(logId,Unversioned());
tLogData->persistentData->clear( singleKeyRange(logIdKey.withPrefix(persistCurrentVersionKeys.begin)) );
tLogData->persistentData->clear( singleKeyRange(logIdKey.withPrefix(persistKnownCommittedVersionKeys.begin)) );
tLogData->persistentData->clear( singleKeyRange(logIdKey.withPrefix(persistLocalityKeys.begin)) );
tLogData->persistentData->clear( singleKeyRange(logIdKey.withPrefix(persistLogRouterTagsKeys.begin)) );
tLogData->persistentData->clear( singleKeyRange(logIdKey.withPrefix(persistTxsTagsKeys.begin)) );
tLogData->persistentData->clear( singleKeyRange(logIdKey.withPrefix(persistRecoveryCountKeys.begin)) );
Key msgKey = logIdKey.withPrefix(persistTagMessagesKeys.begin);
tLogData->persistentData->clear( KeyRangeRef( msgKey, strinc(msgKey) ) );
Key poppedKey = logIdKey.withPrefix(persistTagPoppedKeys.begin);
tLogData->persistentData->clear( KeyRangeRef( poppedKey, strinc(poppedKey) ) );
}
for ( auto it = peekTracker.begin(); it != peekTracker.end(); ++it ) {
for(auto seq : it->second.sequence_version) {
if(!seq.second.isSet()) {
seq.second.sendError(operation_obsolete());
}
}
}
}
LogEpoch epoch() const { return recoveryCount; }
};
template <class T>
void TLogQueue::push( T const& qe, Reference<LogData> logData ) {
BinaryWriter wr( Unversioned() ); // outer framing is not versioned
wr << uint32_t(0);
IncludeVersion(ProtocolVersion::withTLogQueueEntryRef()).write(wr); // payload is versioned
wr << qe;
wr << uint8_t(1);
*(uint32_t*)wr.getData() = wr.getLength() - sizeof(uint32_t) - sizeof(uint8_t);
auto loc = queue->push( wr.toValue() );
//TraceEvent("TLogQueueVersionWritten", dbgid).detail("Size", wr.getLength() - sizeof(uint32_t) - sizeof(uint8_t)).detail("Loc", loc);
logData->versionLocation[qe.version] = loc;
}
void TLogQueue::pop( Version upTo, Reference<LogData> logData ) {
// Keep only the given and all subsequent version numbers
// Find the first version >= upTo
auto v = logData->versionLocation.lower_bound(upTo);
if (v == logData->versionLocation.begin()) return;
if(v == logData->versionLocation.end()) {
v = logData->versionLocation.lastItem();
}
else {
v.decrementNonEnd();
}
queue->pop( v->value );
logData->versionLocation.erase( logData->versionLocation.begin(), v ); // ... and then we erase that previous version and all prior versions
}
void TLogQueue::updateVersionSizes( const TLogQueueEntry& result, TLogData* tLog ) {
auto it = tLog->id_data.find(result.id);
if(it != tLog->id_data.end()) {
it->second->versionLocation[result.version] = queue->getNextReadLocation();
}
}
ACTOR Future<Void> tLogLock( TLogData* self, ReplyPromise< TLogLockResult > reply, Reference<LogData> logData ) {
state Version stopVersion = logData->version.get();
TEST(true); // TLog stopped by recovering master
TEST( logData->stopped );
TEST( !logData->stopped );
TraceEvent("TLogStop", logData->logId).detail("Ver", stopVersion).detail("IsStopped", logData->stopped).detail("QueueCommitted", logData->queueCommittedVersion.get());
logData->stopped = true;
if(!logData->recoveryComplete.isSet()) {
logData->recoveryComplete.sendError(end_of_stream());
}
// Lock once the current version has been committed
wait( logData->queueCommittedVersion.whenAtLeast( stopVersion ) );
ASSERT(stopVersion == logData->version.get());
TLogLockResult result;
result.end = stopVersion;
result.knownCommittedVersion = logData->knownCommittedVersion;
TraceEvent("TLogStop2", self->dbgid).detail("LogId", logData->logId).detail("Ver", stopVersion).detail("IsStopped", logData->stopped).detail("QueueCommitted", logData->queueCommittedVersion.get()).detail("KnownCommitted", result.knownCommittedVersion);
reply.send( result );
return Void();
}
void updatePersistentPopped( TLogData* self, Reference<LogData> logData, Reference<LogData::TagData> data ) {
if (!data->poppedRecently) return;
self->persistentData->set(KeyValueRef( persistTagPoppedKey(logData->logId, data->tag), persistTagPoppedValue(data->popped) ));
data->poppedRecently = false;
if (data->nothingPersistent) return;
self->persistentData->clear( KeyRangeRef(
persistTagMessagesKey( logData->logId, data->tag, Version(0) ),
persistTagMessagesKey( logData->logId, data->tag, data->popped ) ) );
if (data->popped > logData->persistentDataVersion)
data->nothingPersistent = true;
}
ACTOR Future<Void> updatePersistentData( TLogData* self, Reference<LogData> logData, Version newPersistentDataVersion ) {
// PERSIST: Changes self->persistentDataVersion and writes and commits the relevant changes
ASSERT( newPersistentDataVersion <= logData->version.get() );
ASSERT( newPersistentDataVersion <= logData->queueCommittedVersion.get() );
ASSERT( newPersistentDataVersion > logData->persistentDataVersion );
ASSERT( logData->persistentDataVersion == logData->persistentDataDurableVersion );
//TraceEvent("UpdatePersistentData", self->dbgid).detail("Seq", newPersistentDataSeq);
state bool anyData = false;
// For all existing tags
state int tagLocality = 0;
state int tagId = 0;
for(tagLocality = 0; tagLocality < logData->tag_data.size(); tagLocality++) {
for(tagId = 0; tagId < logData->tag_data[tagLocality].size(); tagId++) {
state Reference<LogData::TagData> tagData = logData->tag_data[tagLocality][tagId];
if(tagData) {
state Version currentVersion = 0;
// Clear recently popped versions from persistentData if necessary
updatePersistentPopped( self, logData, tagData );
// Transfer unpopped messages with version numbers less than newPersistentDataVersion to persistentData
state std::deque<std::pair<Version, LengthPrefixedStringRef>>::iterator msg = tagData->versionMessages.begin();
while(msg != tagData->versionMessages.end() && msg->first <= newPersistentDataVersion) {
currentVersion = msg->first;
anyData = true;
tagData->nothingPersistent = false;
BinaryWriter wr( Unversioned() );
for(; msg != tagData->versionMessages.end() && msg->first == currentVersion; ++msg)
wr << msg->second.toStringRef();
self->persistentData->set( KeyValueRef( persistTagMessagesKey( logData->logId, tagData->tag, currentVersion ), wr.toValue() ) );
Future<Void> f = yield(TaskPriority::UpdateStorage);
if(!f.isReady()) {
wait(f);
msg = std::upper_bound(tagData->versionMessages.begin(), tagData->versionMessages.end(), std::make_pair(currentVersion, LengthPrefixedStringRef()), CompareFirst<std::pair<Version, LengthPrefixedStringRef>>());
}
}
wait(yield(TaskPriority::UpdateStorage));
}
}
}
self->persistentData->set( KeyValueRef( BinaryWriter::toValue(logData->logId,Unversioned()).withPrefix(persistCurrentVersionKeys.begin), BinaryWriter::toValue(newPersistentDataVersion, Unversioned()) ) );
self->persistentData->set( KeyValueRef( BinaryWriter::toValue(logData->logId,Unversioned()).withPrefix(persistKnownCommittedVersionKeys.begin), BinaryWriter::toValue(logData->knownCommittedVersion, Unversioned()) ) );
logData->persistentDataVersion = newPersistentDataVersion;
wait( self->persistentData->commit() ); // SOMEDAY: This seems to be running pretty often, should we slow it down???
wait( delay(0, TaskPriority::UpdateStorage) );
// Now that the changes we made to persistentData are durable, erase the data we moved from memory and the queue, increase bytesDurable accordingly, and update persistentDataDurableVersion.
TEST(anyData); // TLog moved data to persistentData
logData->persistentDataDurableVersion = newPersistentDataVersion;
for(tagLocality = 0; tagLocality < logData->tag_data.size(); tagLocality++) {
for(tagId = 0; tagId < logData->tag_data[tagLocality].size(); tagId++) {
if(logData->tag_data[tagLocality][tagId]) {
wait(logData->tag_data[tagLocality][tagId]->eraseMessagesBefore( newPersistentDataVersion+1, self, logData, TaskPriority::UpdateStorage ));
wait(yield(TaskPriority::UpdateStorage));
}
}
}
logData->version_sizes.erase(logData->version_sizes.begin(), logData->version_sizes.lower_bound(logData->persistentDataDurableVersion));
wait(yield(TaskPriority::UpdateStorage));
while(!logData->messageBlocks.empty() && logData->messageBlocks.front().first <= newPersistentDataVersion) {
int64_t bytesErased = int64_t(logData->messageBlocks.front().second.size()) * SERVER_KNOBS->TLOG_MESSAGE_BLOCK_OVERHEAD_FACTOR;
logData->bytesDurable += bytesErased;
self->bytesDurable += bytesErased;
logData->messageBlocks.pop_front();
wait(yield(TaskPriority::UpdateStorage));
}
if(logData->bytesDurable.getValue() > logData->bytesInput.getValue() || self->bytesDurable > self->bytesInput) {
TraceEvent(SevError, "BytesDurableTooLarge", logData->logId).detail("SharedBytesInput", self->bytesInput).detail("SharedBytesDurable", self->bytesDurable).detail("LocalBytesInput", logData->bytesInput.getValue()).detail("LocalBytesDurable", logData->bytesDurable.getValue());
}
ASSERT(logData->bytesDurable.getValue() <= logData->bytesInput.getValue());
ASSERT(self->bytesDurable <= self->bytesInput);
if( self->queueCommitEnd.get() > 0 )
self->persistentQueue->pop( newPersistentDataVersion+1, logData ); // SOMEDAY: this can cause a slow task (~0.5ms), presumably from erasing too many versions. Should we limit the number of versions cleared at a time?
return Void();
}
ACTOR Future<Void> tLogPopCore( TLogData* self, Tag inputTag, Version to, Reference<LogData> logData ) {
if (self->ignorePopRequest) {
TraceEvent(SevDebug, "IgnoringPopRequest").detail("IgnorePopDeadline", self->ignorePopDeadline);
if (self->toBePopped.find(inputTag) == self->toBePopped.end()
|| to > self->toBePopped[inputTag]) {
self->toBePopped[inputTag] = to;
}
// add the pop to the toBePopped map
TraceEvent(SevDebug, "IgnoringPopRequest")
.detail("IgnorePopDeadline", self->ignorePopDeadline)
.detail("Tag", inputTag.toString())
.detail("Version", to);
return Void();
}
state Version upTo = to;
int8_t tagLocality = inputTag.locality;
if (isPseudoLocality(tagLocality)) {
if (logData->logSystem->get().isValid()) {
upTo = logData->logSystem->get()->popPseudoLocalityTag(inputTag, to);
tagLocality = tagLocalityLogRouter;
} else {
TraceEvent(SevWarn, "TLogPopNoLogSystem", self->dbgid).detail("Locality", tagLocality).detail("Version", upTo);
return Void();
}
}
state Tag tag(tagLocality, inputTag.id);
auto tagData = logData->getTagData(tag);
if (!tagData) {
tagData = logData->createTagData(tag, upTo, true, true, false);
} else if (upTo > tagData->popped) {
tagData->popped = upTo;
tagData->poppedRecently = true;
if(tagData->unpoppedRecovered && upTo > logData->recoveredAt) {
tagData->unpoppedRecovered = false;
logData->unpoppedRecoveredTags--;
TraceEvent("TLogPoppedTag", logData->logId).detail("Tags", logData->unpoppedRecoveredTags).detail("Tag", tag.toString()).detail("DurableKCVer", logData->durableKnownCommittedVersion).detail("RecoveredAt", logData->recoveredAt);
if(logData->unpoppedRecoveredTags == 0 && logData->durableKnownCommittedVersion >= logData->recoveredAt && logData->recoveryComplete.canBeSet()) {
logData->recoveryComplete.send(Void());
}
}
if (upTo > logData->persistentDataDurableVersion)
wait(tagData->eraseMessagesBefore(upTo, self, logData, TaskPriority::TLogPop));
//TraceEvent("TLogPop", self->dbgid).detail("Tag", tag.toString()).detail("To", upTo);
}
return Void();
}
ACTOR Future<Void> tLogPop( TLogData* self, TLogPopRequest req, Reference<LogData> logData ) {
// timeout check for ignorePopRequest
if (self->ignorePopRequest && (g_network->now() > self->ignorePopDeadline)) {
TraceEvent("EnableTLogPlayAllIgnoredPops");
// use toBePopped and issue all the pops
state std::map<Tag, Version>::iterator it;
state vector<Future<Void>> ignoredPops;
self->ignorePopRequest = false;
self->ignorePopUid = "";
self->ignorePopDeadline = 0.0;
for (it = self->toBePopped.begin(); it != self->toBePopped.end(); it++) {
TraceEvent("PlayIgnoredPop")
.detail("Tag", it->first.toString())
.detail("Version", it->second);
ignoredPops.push_back(tLogPopCore(self, it->first, it->second, logData));
}
self->toBePopped.clear();
wait(waitForAll(ignoredPops));
TraceEvent("ResetIgnorePopRequest")
.detail("Now", g_network->now())
.detail("IgnorePopRequest", self->ignorePopRequest)
.detail("IgnorePopDeadline", self->ignorePopDeadline);
}
wait(tLogPopCore(self, req.tag, req.to, logData));
req.reply.send(Void());
return Void();
}
// This function (and updatePersistentData, which is called by this function) run at a low priority and can soak up all CPU resources.
// For this reason, they employ aggressive use of yields to avoid causing slow tasks that could introduce latencies for more important
// work (e.g. commits).
ACTOR Future<Void> updateStorage( TLogData* self ) {
while(self->queueOrder.size() && !self->id_data.count(self->queueOrder.front())) {
self->queueOrder.pop_front();
}
if(!self->queueOrder.size()) {
wait( delay(BUGGIFY ? SERVER_KNOBS->BUGGIFY_TLOG_STORAGE_MIN_UPDATE_INTERVAL : SERVER_KNOBS->TLOG_STORAGE_MIN_UPDATE_INTERVAL, TaskPriority::UpdateStorage) );
return Void();
}
state Reference<LogData> logData = self->id_data[self->queueOrder.front()];
state Version nextVersion = 0;
state int totalSize = 0;
state FlowLock::Releaser commitLockReleaser;
//FIXME: This policy for calculating the cache pop version could end up popping recent data in the remote DC after two consecutive recoveries.
// It also does not protect against spilling the cache tag directly, so it is theoretically possible to spill this tag; which is not intended to ever happen.
Optional<Version> cachePopVersion;
for(auto& it : self->id_data) {
if(!it.second->stopped) {
if(it.second->version.get() - it.second->unrecoveredBefore > SERVER_KNOBS->MAX_VERSIONS_IN_FLIGHT + SERVER_KNOBS->MAX_CACHE_VERSIONS) {
cachePopVersion = it.second->version.get() - SERVER_KNOBS->MAX_CACHE_VERSIONS;
}
break;
}
}
if(cachePopVersion.present()) {
state std::vector<Future<Void>> cachePopFutures;
for(auto& it : self->id_data) {
cachePopFutures.push_back(tLogPop(self, TLogPopRequest(cachePopVersion.get(),0,cacheTag), it.second));
}
wait( waitForAll(cachePopFutures) );
}
if(logData->stopped) {
if (self->bytesInput - self->bytesDurable >= self->targetVolatileBytes) {
while(logData->persistentDataDurableVersion != logData->version.get()) {
totalSize = 0;
Map<Version, std::pair<int,int>>::iterator sizeItr = logData->version_sizes.begin();
nextVersion = logData->version.get();
while( totalSize < SERVER_KNOBS->UPDATE_STORAGE_BYTE_LIMIT && sizeItr != logData->version_sizes.end() )
{
totalSize += sizeItr->value.first + sizeItr->value.second;
++sizeItr;
nextVersion = sizeItr == logData->version_sizes.end() ? logData->version.get() : sizeItr->key;
}
wait( logData->queueCommittedVersion.whenAtLeast( nextVersion ) );
wait( delay(0, TaskPriority::UpdateStorage) );
//TraceEvent("TlogUpdatePersist", self->dbgid).detail("LogId", logData->logId).detail("NextVersion", nextVersion).detail("Version", logData->version.get()).detail("PersistentDataDurableVer", logData->persistentDataDurableVersion).detail("QueueCommitVer", logData->queueCommittedVersion.get()).detail("PersistDataVer", logData->persistentDataVersion);
if (nextVersion > logData->persistentDataVersion) {
wait( self->persistentDataCommitLock.take() );
commitLockReleaser = FlowLock::Releaser(self->persistentDataCommitLock);
wait( updatePersistentData(self, logData, nextVersion) );
commitLockReleaser.release();
} else {
wait( delay(BUGGIFY ? SERVER_KNOBS->BUGGIFY_TLOG_STORAGE_MIN_UPDATE_INTERVAL : SERVER_KNOBS->TLOG_STORAGE_MIN_UPDATE_INTERVAL, TaskPriority::UpdateStorage) );
}
if( logData->removed.isReady() ) {
break;
}
}
if(logData->persistentDataDurableVersion == logData->version.get()) {
self->queueOrder.pop_front();
}
wait( delay(0.0, TaskPriority::UpdateStorage) );
} else {
wait( delay(BUGGIFY ? SERVER_KNOBS->BUGGIFY_TLOG_STORAGE_MIN_UPDATE_INTERVAL : SERVER_KNOBS->TLOG_STORAGE_MIN_UPDATE_INTERVAL, TaskPriority::UpdateStorage) );
}
}
else if(logData->initialized) {
ASSERT(self->queueOrder.size() == 1);
if(logData->version_sizes.empty()) {
nextVersion = logData->version.get();
} else {
Map<Version, std::pair<int,int>>::iterator sizeItr = logData->version_sizes.begin();
while( totalSize < SERVER_KNOBS->UPDATE_STORAGE_BYTE_LIMIT && sizeItr != logData->version_sizes.end()
&& (logData->bytesInput.getValue() - logData->bytesDurable.getValue() - totalSize >= self->targetVolatileBytes || sizeItr->value.first == 0) )
{
totalSize += sizeItr->value.first + sizeItr->value.second;
++sizeItr;
nextVersion = sizeItr == logData->version_sizes.end() ? logData->version.get() : sizeItr->key;
}
}
//TraceEvent("UpdateStorageVer", logData->logId).detail("NextVersion", nextVersion).detail("PersistentDataVersion", logData->persistentDataVersion).detail("TotalSize", totalSize);
wait( logData->queueCommittedVersion.whenAtLeast( nextVersion ) );
wait( delay(0, TaskPriority::UpdateStorage) );
if (nextVersion > logData->persistentDataVersion) {
wait( self->persistentDataCommitLock.take() );
commitLockReleaser = FlowLock::Releaser(self->persistentDataCommitLock);
wait( updatePersistentData(self, logData, nextVersion) );
commitLockReleaser.release();
}
if( totalSize < SERVER_KNOBS->UPDATE_STORAGE_BYTE_LIMIT ) {
wait( delay(BUGGIFY ? SERVER_KNOBS->BUGGIFY_TLOG_STORAGE_MIN_UPDATE_INTERVAL : SERVER_KNOBS->TLOG_STORAGE_MIN_UPDATE_INTERVAL, TaskPriority::UpdateStorage) );
}
else {
//recovery wants to commit to persistant data when updatePersistentData is not active, this delay ensures that immediately after
//updatePersist returns another one has not been started yet.
wait( delay(0.0, TaskPriority::UpdateStorage) );
}
} else {
wait( delay(BUGGIFY ? SERVER_KNOBS->BUGGIFY_TLOG_STORAGE_MIN_UPDATE_INTERVAL : SERVER_KNOBS->TLOG_STORAGE_MIN_UPDATE_INTERVAL, TaskPriority::UpdateStorage) );
}
return Void();
}
ACTOR Future<Void> updateStorageLoop( TLogData* self ) {
wait(delay(0, TaskPriority::UpdateStorage));
loop {
wait( updateStorage(self) );
}
}
void commitMessages( TLogData* self, Reference<LogData> logData, Version version, const std::vector<TagsAndMessage>& taggedMessages ) {
// SOMEDAY: This method of copying messages is reasonably memory efficient, but it's still a lot of bytes copied. Find a
// way to do the memory allocation right as we receive the messages in the network layer.
int64_t addedBytes = 0;
int64_t overheadBytes = 0;
int expectedBytes = 0;
int txsBytes = 0;
if(!taggedMessages.size()) {
return;
}
int msgSize = 0;
for(auto& i : taggedMessages) {
msgSize += i.message.size();
}
// Grab the last block in the blocks list so we can share its arena
// We pop all of the elements of it to create a "fresh" vector that starts at the end of the previous vector
Standalone<VectorRef<uint8_t>> block;
if(logData->messageBlocks.empty()) {
block = Standalone<VectorRef<uint8_t>>();
block.reserve(block.arena(), std::max<int64_t>(SERVER_KNOBS->TLOG_MESSAGE_BLOCK_BYTES, msgSize));
}
else {
block = logData->messageBlocks.back().second;
}
block.pop_front(block.size());
for(auto& msg : taggedMessages) {
if(msg.message.size() > block.capacity() - block.size()) {
logData->messageBlocks.emplace_back(version, block);
addedBytes += int64_t(block.size()) * SERVER_KNOBS->TLOG_MESSAGE_BLOCK_OVERHEAD_FACTOR;
block = Standalone<VectorRef<uint8_t>>();
block.reserve(block.arena(), std::max<int64_t>(SERVER_KNOBS->TLOG_MESSAGE_BLOCK_BYTES, msgSize));
}
block.append(block.arena(), msg.message.begin(), msg.message.size());
for(auto tag : msg.tags) {
if(logData->locality == tagLocalitySatellite) {
if(!(tag.locality == tagLocalityTxs || tag.locality == tagLocalityLogRouter || tag == txsTag)) {
continue;
}
} else if(!(logData->locality == tagLocalitySpecial || logData->locality == tag.locality || tag.locality < 0)) {
continue;
}
if(tag.locality == tagLocalityLogRouter) {
if(!logData->logRouterTags) {
continue;
}
tag.id = tag.id % logData->logRouterTags;
}
if(tag.locality == tagLocalityTxs) {
if (logData->txsTags > 0) {
tag.id = tag.id % logData->txsTags;
} else {
tag = txsTag;
}
}
Reference<LogData::TagData> tagData = logData->getTagData(tag);
if(!tagData) {
tagData = logData->createTagData(tag, 0, true, true, false);
}
if (version >= tagData->popped) {
tagData->versionMessages.emplace_back(version, LengthPrefixedStringRef((uint32_t*)(block.end() - msg.message.size())));
if(tagData->versionMessages.back().second.expectedSize() > SERVER_KNOBS->MAX_MESSAGE_SIZE) {
TraceEvent(SevWarnAlways, "LargeMessage").detail("Size", tagData->versionMessages.back().second.expectedSize());
}
if (tag.locality != tagLocalityTxs && tag != txsTag) {
expectedBytes += tagData->versionMessages.back().second.expectedSize();
} else {
txsBytes += tagData->versionMessages.back().second.expectedSize();
}
// The factor of VERSION_MESSAGES_OVERHEAD is intended to be an overestimate of the actual memory used to store this data in a std::deque.
// In practice, this number is probably something like 528/512 ~= 1.03, but this could vary based on the implementation.
// There will also be a fixed overhead per std::deque, but its size should be trivial relative to the size of the TLog
// queue and can be thought of as increasing the capacity of the queue slightly.
overheadBytes += SERVER_KNOBS->VERSION_MESSAGES_ENTRY_BYTES_WITH_OVERHEAD;
}
}
msgSize -= msg.message.size();
}
logData->messageBlocks.emplace_back(version, block);
addedBytes += int64_t(block.size()) * SERVER_KNOBS->TLOG_MESSAGE_BLOCK_OVERHEAD_FACTOR;
addedBytes += overheadBytes;
logData->version_sizes[version] = std::make_pair(expectedBytes, txsBytes);
logData->bytesInput += addedBytes;
self->bytesInput += addedBytes;
self->overheadBytesInput += overheadBytes;
//TraceEvent("TLogPushed", self->dbgid).detail("Bytes", addedBytes).detail("MessageBytes", messages.size()).detail("Tags", tags.size()).detail("ExpectedBytes", expectedBytes).detail("MCount", mCount).detail("TCount", tCount);
}
void commitMessages( TLogData *self, Reference<LogData> logData, Version version, Arena arena, StringRef messages ) {
ArenaReader rd( arena, messages, Unversioned() );
self->tempTagMessages.clear();
while(!rd.empty()) {
TagsAndMessage tagsAndMsg;
tagsAndMsg.loadFromArena(&rd, nullptr);
self->tempTagMessages.push_back(std::move(tagsAndMsg));
}
commitMessages(self, logData, version, self->tempTagMessages);
}
Version poppedVersion( Reference<LogData> self, Tag tag) {
auto tagData = self->getTagData(tag);
if (!tagData) {
if (tag == txsTag || tag.locality == tagLocalityTxs) {
return 0;
}
return self->recoveredAt;
}
return tagData->popped;
}
std::deque<std::pair<Version, LengthPrefixedStringRef>> & getVersionMessages( Reference<LogData> self, Tag tag ) {
auto tagData = self->getTagData(tag);
if (!tagData) {
static std::deque<std::pair<Version, LengthPrefixedStringRef>> empty;
return empty;
}
return tagData->versionMessages;
};
void peekMessagesFromMemory( Reference<LogData> self, TLogPeekRequest const& req, BinaryWriter& messages, Version& endVersion ) {
ASSERT( !messages.getLength() );
auto& deque = getVersionMessages(self, req.tag);
//TraceEvent("TLogPeekMem", self->dbgid).detail("Tag", req.tag1).detail("PDS", self->persistentDataSequence).detail("PDDS", self->persistentDataDurableSequence).detail("Oldest", map1.empty() ? 0 : map1.begin()->key ).detail("OldestMsgCount", map1.empty() ? 0 : map1.begin()->value.size());
Version begin = std::max( req.begin, self->persistentDataDurableVersion+1 );
auto it = std::lower_bound(deque.begin(), deque.end(), std::make_pair(begin, LengthPrefixedStringRef()), CompareFirst<std::pair<Version, LengthPrefixedStringRef>>());
Version currentVersion = -1;
for(; it != deque.end(); ++it) {
if(it->first != currentVersion) {
if (messages.getLength() >= SERVER_KNOBS->DESIRED_TOTAL_BYTES) {
endVersion = currentVersion + 1;
//TraceEvent("TLogPeekMessagesReached2", self->dbgid);
break;
}
currentVersion = it->first;
messages << VERSION_HEADER << currentVersion;
}
messages << it->second.toStringRef();
}
}
ACTOR Future<Void> tLogPeekMessages( TLogData* self, TLogPeekRequest req, Reference<LogData> logData ) {
state BinaryWriter messages(Unversioned());
state BinaryWriter messages2(Unversioned());
state int sequence = -1;
state UID peekId;
state double queueStart = now();
if(req.tag.locality == tagLocalityTxs && req.tag.id >= logData->txsTags && logData->txsTags > 0) {
req.tag.id = req.tag.id % logData->txsTags;
}
if(req.sequence.present()) {
try {
peekId = req.sequence.get().first;
sequence = req.sequence.get().second;
if (sequence >= SERVER_KNOBS->PARALLEL_GET_MORE_REQUESTS && logData->peekTracker.find(peekId) == logData->peekTracker.end()) {
throw operation_obsolete();
}
auto& trackerData = logData->peekTracker[peekId];
if (sequence == 0 && trackerData.sequence_version.find(0) == trackerData.sequence_version.end()) {
trackerData.tag = req.tag;
trackerData.sequence_version[0].send(std::make_pair(req.begin, req.onlySpilled));
}
auto seqBegin = trackerData.sequence_version.begin();
while(trackerData.sequence_version.size() && seqBegin->first <= sequence - SERVER_KNOBS->PARALLEL_GET_MORE_REQUESTS) {
if(seqBegin->second.canBeSet()) {
seqBegin->second.sendError(operation_obsolete());
}
trackerData.sequence_version.erase(seqBegin);
seqBegin = trackerData.sequence_version.begin();
}
if(trackerData.sequence_version.size() && sequence < seqBegin->first) {
throw operation_obsolete();
}
Future<std::pair<Version, bool>> fPrevPeekData = trackerData.sequence_version[sequence].getFuture();
if(fPrevPeekData.isReady()) {
trackerData.unblockedPeeks++;
double t = now() - trackerData.lastUpdate;
if(t > trackerData.idleMax) trackerData.idleMax = t;
trackerData.idleTime += t;
}
trackerData.lastUpdate = now();
std::pair<Version, bool> prevPeekData = wait(fPrevPeekData);
req.begin = std::max(prevPeekData.first, req.begin);
req.onlySpilled = prevPeekData.second;
wait(yield());
} catch( Error &e ) {
if(e.code() == error_code_timed_out || e.code() == error_code_operation_obsolete) {
req.reply.sendError(e);
return Void();
} else {
throw;
}
}
}
state double blockStart = now();
if( req.returnIfBlocked && logData->version.get() < req.begin ) {
req.reply.sendError(end_of_stream());
if(req.sequence.present()) {
auto& trackerData = logData->peekTracker[peekId];
auto& sequenceData = trackerData.sequence_version[sequence+1];
if (!sequenceData.isSet()) {
sequenceData.send(std::make_pair(req.begin, req.onlySpilled));
}
}
return Void();
}
//TraceEvent("TLogPeekMessages0", self->dbgid).detail("ReqBeginEpoch", req.begin.epoch).detail("ReqBeginSeq", req.begin.sequence).detail("Epoch", self->epoch()).detail("PersistentDataSeq", self->persistentDataSequence).detail("Tag1", req.tag1).detail("Tag2", req.tag2);
// Wait until we have something to return that the caller doesn't already have
if( logData->version.get() < req.begin ) {
wait( logData->version.whenAtLeast( req.begin ) );
wait( delay(SERVER_KNOBS->TLOG_PEEK_DELAY, g_network->getCurrentTask()) );
}
if( logData->locality != tagLocalitySatellite && req.tag.locality == tagLocalityLogRouter ) {
wait( self->concurrentLogRouterReads.take() );
state FlowLock::Releaser globalReleaser(self->concurrentLogRouterReads);
wait( delay(0.0, TaskPriority::Low) );
}
if( req.begin <= logData->persistentDataDurableVersion && req.tag.locality != tagLocalityTxs && req.tag != txsTag) {
// Reading spilled data will almost always imply that the storage server is >5s behind the rest
// of the cluster. We shouldn't prioritize spending CPU on helping this server catch up
// slightly faster over keeping the rest of the cluster operating normally.
// txsTag is only ever peeked on recovery, and we would still wish to prioritize requests
// that impact recovery duration.
wait(delay(0, TaskPriority::TLogSpilledPeekReply));
}
state double workStart = now();
Version poppedVer = poppedVersion(logData, req.tag);
if(poppedVer > req.begin) {
TLogPeekReply rep;
rep.maxKnownVersion = logData->version.get();
rep.minKnownCommittedVersion = logData->minKnownCommittedVersion;
rep.popped = poppedVer;
rep.end = poppedVer;
rep.onlySpilled = false;
if(req.sequence.present()) {
auto& trackerData = logData->peekTracker[peekId];
auto& sequenceData = trackerData.sequence_version[sequence+1];
trackerData.lastUpdate = now();
if(trackerData.sequence_version.size() && sequence+1 < trackerData.sequence_version.begin()->first) {
req.reply.sendError(operation_obsolete());
if (!sequenceData.isSet())
sequenceData.sendError(operation_obsolete());
return Void();
}
if(sequenceData.isSet()) {
if(sequenceData.getFuture().get().first != rep.end) {
TEST(true); //tlog peek second attempt ended at a different version
req.reply.sendError(operation_obsolete());
return Void();
}
} else {
sequenceData.send(std::make_pair(rep.end, rep.onlySpilled));
}
rep.begin = req.begin;
}
req.reply.send( rep );
return Void();
}
state Version endVersion = logData->version.get() + 1;
state bool onlySpilled = false;
//grab messages from disk
//TraceEvent("TLogPeekMessages", self->dbgid).detail("ReqBeginEpoch", req.begin.epoch).detail("ReqBeginSeq", req.begin.sequence).detail("Epoch", self->epoch()).detail("PersistentDataSeq", self->persistentDataSequence).detail("Tag1", req.tag1).detail("Tag2", req.tag2);
if( req.begin <= logData->persistentDataDurableVersion ) {
// Just in case the durable version changes while we are waiting for the read, we grab this data from memory. We may or may not actually send it depending on
// whether we get enough data from disk.
// SOMEDAY: Only do this if an initial attempt to read from disk results in insufficient data and the required data is no longer in memory
// SOMEDAY: Should we only send part of the messages we collected, to actually limit the size of the result?
if (req.onlySpilled) {
endVersion = logData->persistentDataDurableVersion + 1;
} else {
peekMessagesFromMemory( logData, req, messages2, endVersion );
}
Standalone<RangeResultRef> kvs = wait(
self->persistentData->readRange(KeyRangeRef(
persistTagMessagesKey(logData->logId, req.tag, req.begin),
persistTagMessagesKey(logData->logId, req.tag, logData->persistentDataDurableVersion + 1)), SERVER_KNOBS->DESIRED_TOTAL_BYTES, SERVER_KNOBS->DESIRED_TOTAL_BYTES));
//TraceEvent("TLogPeekResults", self->dbgid).detail("ForAddress", req.reply.getEndpoint().address).detail("Tag1Results", s1).detail("Tag2Results", s2).detail("Tag1ResultsLim", kv1.size()).detail("Tag2ResultsLim", kv2.size()).detail("Tag1ResultsLast", kv1.size() ? kv1[0].key : "").detail("Tag2ResultsLast", kv2.size() ? kv2[0].key : "").detail("Limited", limited).detail("NextEpoch", next_pos.epoch).detail("NextSeq", next_pos.sequence).detail("NowEpoch", self->epoch()).detail("NowSeq", self->sequence.getNextSequence());
for (auto &kv : kvs) {
auto ver = decodeTagMessagesKey(kv.key);
messages << VERSION_HEADER << ver;
messages.serializeBytes(kv.value);
}
if (kvs.expectedSize() >= SERVER_KNOBS->DESIRED_TOTAL_BYTES) {
endVersion = decodeTagMessagesKey(kvs.end()[-1].key) + 1;
onlySpilled = true;
} else {
messages.serializeBytes( messages2.toValue() );
}
} else {
peekMessagesFromMemory( logData, req, messages, endVersion );
//TraceEvent("TLogPeekResults", self->dbgid).detail("ForAddress", req.reply.getEndpoint().address).detail("MessageBytes", messages.getLength()).detail("NextEpoch", next_pos.epoch).detail("NextSeq", next_pos.sequence).detail("NowSeq", self->sequence.getNextSequence());
}
TLogPeekReply reply;
reply.maxKnownVersion = logData->version.get();
reply.minKnownCommittedVersion = logData->minKnownCommittedVersion;
reply.messages = messages.toValue();
reply.end = endVersion;
reply.onlySpilled = onlySpilled;
//TraceEvent("TlogPeek", self->dbgid).detail("LogId", logData->logId).detail("EndVer", reply.end).detail("MsgBytes", reply.messages.expectedSize()).detail("ForAddress", req.reply.getEndpoint().address);
if(req.sequence.present()) {
auto& trackerData = logData->peekTracker[peekId];
trackerData.lastUpdate = now();
double queueT = blockStart-queueStart;
double blockT = workStart-blockStart;
double workT = now()-workStart;
trackerData.totalPeeks++;
trackerData.replyBytes += reply.messages.size();
if(queueT > trackerData.queueMax) trackerData.queueMax = queueT;
if(blockT > trackerData.blockMax) trackerData.blockMax = blockT;
if(workT > trackerData.workMax) trackerData.workMax = workT;
trackerData.queueTime += queueT;
trackerData.blockTime += blockT;
trackerData.workTime += workT;
auto& sequenceData = trackerData.sequence_version[sequence+1];
if(trackerData.sequence_version.size() && sequence+1 < trackerData.sequence_version.begin()->first) {
req.reply.sendError(operation_obsolete());
if(!sequenceData.isSet())
sequenceData.sendError(operation_obsolete());
return Void();
}
if(sequenceData.isSet()) {
trackerData.duplicatePeeks++;
if(sequenceData.getFuture().get().first != reply.end) {
TEST(true); //tlog peek second attempt ended at a different version
req.reply.sendError(operation_obsolete());
return Void();
}
} else {
sequenceData.send(std::make_pair(reply.end, reply.onlySpilled));
}
reply.begin = req.begin;
}
req.reply.send( reply );
return Void();
}
ACTOR Future<Void> watchDegraded(TLogData* self) {
if(g_network->isSimulated() && g_simulator.speedUpSimulation) {
return Void();
}
wait(lowPriorityDelay(SERVER_KNOBS->TLOG_DEGRADED_DURATION));
TraceEvent(SevWarnAlways, "TLogDegraded", self->dbgid);
TEST(true); //6.0 TLog degraded
self->degraded->set(true);
return Void();
}
ACTOR Future<Void> doQueueCommit( TLogData* self, Reference<LogData> logData, std::vector<Reference<LogData>> missingFinalCommit ) {
state Version ver = logData->version.get();
state Version commitNumber = self->queueCommitBegin+1;
state Version knownCommittedVersion = logData->knownCommittedVersion;
self->queueCommitBegin = commitNumber;
logData->queueCommittingVersion = ver;
g_network->setCurrentTask(TaskPriority::TLogCommitReply);
Future<Void> c = self->persistentQueue->commit();
self->diskQueueCommitBytes = 0;
self->largeDiskQueueCommitBytes.set(false);
state Future<Void> degraded = watchDegraded(self);
wait(c);
if(g_network->isSimulated() && !g_simulator.speedUpSimulation && BUGGIFY_WITH_PROB(0.0001)) {
wait(delay(6.0));
}
degraded.cancel();
wait(self->queueCommitEnd.whenAtLeast(commitNumber-1));
//Calling check_yield instead of yield to avoid a destruction ordering problem in simulation
if(g_network->check_yield(g_network->getCurrentTask())) {
wait(delay(0, g_network->getCurrentTask()));
}
ASSERT( ver > logData->queueCommittedVersion.get() );
logData->durableKnownCommittedVersion = knownCommittedVersion;
if(logData->unpoppedRecoveredTags == 0 && knownCommittedVersion >= logData->recoveredAt && logData->recoveryComplete.canBeSet()) {
TraceEvent("TLogRecoveryComplete", logData->logId).detail("Tags", logData->unpoppedRecoveredTags).detail("DurableKCVer", logData->durableKnownCommittedVersion).detail("RecoveredAt", logData->recoveredAt);
logData->recoveryComplete.send(Void());
}
//TraceEvent("TLogCommitDurable", self->dbgid).detail("Version", ver);
if(logData->logSystem->get() && (!logData->isPrimary || logData->logRouterPoppedVersion < logData->logRouterPopToVersion)) {
logData->logRouterPoppedVersion = ver;
logData->logSystem->get()->pop(ver, logData->remoteTag, knownCommittedVersion, logData->locality);
}
logData->queueCommittedVersion.set(ver);
self->queueCommitEnd.set(commitNumber);
for(auto& it : missingFinalCommit) {
TraceEvent("TLogCommitMissingFinalCommit", self->dbgid).detail("LogId", logData->logId).detail("Version", it->version.get()).detail("QueueVer", it->queueCommittedVersion.get());
TEST(true); //A TLog was replaced before having a chance to commit its queue
it->queueCommittedVersion.set(it->version.get());
}
return Void();
}
ACTOR Future<Void> commitQueue( TLogData* self ) {
state Reference<LogData> logData;
loop {
int foundCount = 0;
state std::vector<Reference<LogData>> missingFinalCommit;
for(auto it : self->id_data) {
if(!it.second->stopped) {
logData = it.second;
foundCount++;
} else if(it.second->version.get() > std::max(it.second->queueCommittingVersion, it.second->queueCommittedVersion.get())) {
missingFinalCommit.push_back(it.second);
}
}
ASSERT(foundCount < 2);
if(!foundCount) {
wait( self->newLogData.onTrigger() );
continue;
}
TraceEvent("CommitQueueNewLog", self->dbgid).detail("LogId", logData->logId).detail("Version", logData->version.get()).detail("Committing", logData->queueCommittingVersion).detail("Commmitted", logData->queueCommittedVersion.get());
if(logData->committingQueue.canBeSet()) {
logData->committingQueue.send(Void());
}
loop {
if(logData->stopped && logData->version.get() == std::max(logData->queueCommittingVersion, logData->queueCommittedVersion.get())) {
wait( logData->queueCommittedVersion.whenAtLeast(logData->version.get() ) );
break;
}
choose {
when(wait( logData->version.whenAtLeast( std::max(logData->queueCommittingVersion, logData->queueCommittedVersion.get()) + 1 ) ) ) {
while( self->queueCommitBegin != self->queueCommitEnd.get() && !self->largeDiskQueueCommitBytes.get() ) {
wait( self->queueCommitEnd.whenAtLeast(self->queueCommitBegin) || self->largeDiskQueueCommitBytes.onChange() );
}
self->sharedActors.send(doQueueCommit(self, logData, missingFinalCommit));
missingFinalCommit.clear();
}
when(wait(self->newLogData.onTrigger())) {}
}
}
}
}
ACTOR Future<Void> tLogCommit(
TLogData* self,
TLogCommitRequest req,
Reference<LogData> logData,
PromiseStream<Void> warningCollectorInput ) {
state Optional<UID> tlogDebugID;
if(req.debugID.present())
{
tlogDebugID = nondeterministicRandom()->randomUniqueID();
g_traceBatch.addAttach("CommitAttachID", req.debugID.get().first(), tlogDebugID.get().first());
g_traceBatch.addEvent("CommitDebug", tlogDebugID.get().first(), "TLog.tLogCommit.BeforeWaitForVersion");
}
logData->minKnownCommittedVersion = std::max(logData->minKnownCommittedVersion, req.minKnownCommittedVersion);
wait( logData->version.whenAtLeast( req.prevVersion ) );
//Calling check_yield instead of yield to avoid a destruction ordering problem in simulation
if(g_network->check_yield(g_network->getCurrentTask())) {
wait(delay(0, g_network->getCurrentTask()));
}
state double waitStartT = 0;
while( self->bytesInput - self->bytesDurable >= SERVER_KNOBS->TLOG_HARD_LIMIT_BYTES && !logData->stopped ) {
if (now() - waitStartT >= 1) {
TraceEvent(SevWarn, "TLogUpdateLag", logData->logId)
.detail("Version", logData->version.get())
.detail("PersistentDataVersion", logData->persistentDataVersion)
.detail("PersistentDataDurableVersion", logData->persistentDataDurableVersion);
waitStartT = now();
}
wait( delayJittered(.005, TaskPriority::TLogCommit) );
}
if(logData->stopped) {
req.reply.sendError( tlog_stopped() );
return Void();
}
if (logData->version.get() == req.prevVersion) { // Not a duplicate (check relies on critical section between here self->version.set() below!)
if(req.debugID.present())
g_traceBatch.addEvent("CommitDebug", tlogDebugID.get().first(), "TLog.tLogCommit.Before");
//TraceEvent("TLogCommit", logData->logId).detail("Version", req.version);
commitMessages(self, logData, req.version, req.arena, req.messages);
logData->knownCommittedVersion = std::max(logData->knownCommittedVersion, req.knownCommittedVersion);
TLogQueueEntryRef qe;
// Log the changes to the persistent queue, to be committed by commitQueue()
qe.version = req.version;
qe.knownCommittedVersion = logData->knownCommittedVersion;
qe.messages = req.messages;
qe.id = logData->logId;
self->persistentQueue->push( qe, logData );
self->diskQueueCommitBytes += qe.expectedSize();
if( self->diskQueueCommitBytes > SERVER_KNOBS->MAX_QUEUE_COMMIT_BYTES ) {
self->largeDiskQueueCommitBytes.set(true);
}
// Notifies the commitQueue actor to commit persistentQueue, and also unblocks tLogPeekMessages actors
logData->version.set( req.version );
if(req.debugID.present())
g_traceBatch.addEvent("CommitDebug", tlogDebugID.get().first(), "TLog.tLogCommit.AfterTLogCommit");
}
// Send replies only once all prior messages have been received and committed.
state Future<Void> stopped = logData->stopCommit.onTrigger();
wait( timeoutWarning( logData->queueCommittedVersion.whenAtLeast( req.version ) || stopped, 0.1, warningCollectorInput ) );
if(stopped.isReady()) {
ASSERT(logData->stopped);
req.reply.sendError( tlog_stopped() );
return Void();
}
if(req.debugID.present())
g_traceBatch.addEvent("CommitDebug", tlogDebugID.get().first(), "TLog.tLogCommit.After");
req.reply.send( logData->durableKnownCommittedVersion );
return Void();
}
ACTOR Future<Void> initPersistentState( TLogData* self, Reference<LogData> logData ) {
wait( self->persistentDataCommitLock.take() );
state FlowLock::Releaser commitLockReleaser(self->persistentDataCommitLock);
// PERSIST: Initial setup of persistentData for a brand new tLog for a new database
state IKeyValueStore *storage = self->persistentData;
wait( ioTimeoutError( storage->init(), SERVER_KNOBS->TLOG_MAX_CREATE_DURATION ) );
storage->set( persistFormat );
storage->set( KeyValueRef( BinaryWriter::toValue(logData->logId,Unversioned()).withPrefix(persistCurrentVersionKeys.begin), BinaryWriter::toValue(logData->version.get(), Unversioned()) ) );
storage->set( KeyValueRef( BinaryWriter::toValue(logData->logId,Unversioned()).withPrefix(persistKnownCommittedVersionKeys.begin), BinaryWriter::toValue(logData->knownCommittedVersion, Unversioned()) ) );
storage->set( KeyValueRef( BinaryWriter::toValue(logData->logId,Unversioned()).withPrefix(persistLocalityKeys.begin), BinaryWriter::toValue(logData->locality, Unversioned()) ) );
storage->set( KeyValueRef( BinaryWriter::toValue(logData->logId,Unversioned()).withPrefix(persistLogRouterTagsKeys.begin), BinaryWriter::toValue(logData->logRouterTags, Unversioned()) ) );
storage->set( KeyValueRef( BinaryWriter::toValue(logData->logId,Unversioned()).withPrefix(persistTxsTagsKeys.begin), BinaryWriter::toValue(logData->txsTags, Unversioned()) ) );
storage->set( KeyValueRef( BinaryWriter::toValue(logData->logId,Unversioned()).withPrefix(persistRecoveryCountKeys.begin), BinaryWriter::toValue(logData->recoveryCount, Unversioned()) ) );
for(auto tag : logData->allTags) {
ASSERT(!logData->getTagData(tag));
logData->createTagData(tag, 0, true, true, true);
updatePersistentPopped( self, logData, logData->getTagData(tag) );
}
TraceEvent("TLogInitCommit", logData->logId);
wait( ioTimeoutError( self->persistentData->commit(), SERVER_KNOBS->TLOG_MAX_CREATE_DURATION ) );
return Void();
}
ACTOR Future<Void> rejoinMasters( TLogData* self, TLogInterface tli, DBRecoveryCount recoveryCount, Future<Void> registerWithMaster, bool isPrimary ) {
state UID lastMasterID(0,0);
loop {
auto const& inf = self->dbInfo->get();
bool isDisplaced = !std::count( inf.priorCommittedLogServers.begin(), inf.priorCommittedLogServers.end(), tli.id() );
if(isPrimary) {
isDisplaced = isDisplaced && inf.recoveryCount >= recoveryCount && inf.recoveryState != RecoveryState::UNINITIALIZED;
} else {
isDisplaced = isDisplaced && ( ( inf.recoveryCount > recoveryCount && inf.recoveryState != RecoveryState::UNINITIALIZED ) || ( inf.recoveryCount == recoveryCount && inf.recoveryState == RecoveryState::FULLY_RECOVERED ) );
}
isDisplaced = isDisplaced && !inf.logSystemConfig.hasTLog(tli.id());
if (isDisplaced) {
TraceEvent("TLogDisplaced", tli.id())
.detail("Reason", "DBInfoDoesNotContain")
.detail("RecoveryCount", recoveryCount)
.detail("InfRecoveryCount", inf.recoveryCount)
.detail("RecoveryState", (int)inf.recoveryState)
.detail("LogSysConf", describe(inf.logSystemConfig.tLogs))
.detail("PriorLogs", describe(inf.priorCommittedLogServers))
.detail("OldLogGens", inf.logSystemConfig.oldTLogs.size());
if (BUGGIFY) wait( delay( SERVER_KNOBS->BUGGIFY_WORKER_REMOVED_MAX_LAG * deterministicRandom()->random01() ) );
throw worker_removed();
}
if( registerWithMaster.isReady() ) {
if ( self->dbInfo->get().master.id() != lastMasterID) {
// The TLogRejoinRequest is needed to establish communications with a new master, which doesn't have our TLogInterface
TLogRejoinRequest req(tli);
TraceEvent("TLogRejoining", tli.id()).detail("Master", self->dbInfo->get().master.id());
choose {
when(TLogRejoinReply rep =
wait(brokenPromiseToNever(self->dbInfo->get().master.tlogRejoin.getReply(req)))) {
if (rep.masterIsRecovered) lastMasterID = self->dbInfo->get().master.id();
}
when ( wait( self->dbInfo->onChange() ) ) { }
}
} else {
wait( self->dbInfo->onChange() );
}
} else {
wait( registerWithMaster || self->dbInfo->onChange() );
}
}
}
ACTOR Future<Void> respondToRecovered( TLogInterface tli, Promise<Void> recoveryComplete ) {
state bool finishedRecovery = true;
try {
wait( recoveryComplete.getFuture() );
} catch( Error &e ) {
if(e.code() != error_code_end_of_stream) {
throw;
}
finishedRecovery = false;
}
TraceEvent("TLogRespondToRecovered", tli.id()).detail("Finished", finishedRecovery);
loop {
TLogRecoveryFinishedRequest req = waitNext( tli.recoveryFinished.getFuture() );
if(finishedRecovery) {
req.reply.send(Void());
} else {
req.reply.send(Never());
}
}
}
ACTOR Future<Void> cleanupPeekTrackers( LogData* logData ) {
loop {
double minTimeUntilExpiration = SERVER_KNOBS->PEEK_TRACKER_EXPIRATION_TIME;
auto it = logData->peekTracker.begin();
while(it != logData->peekTracker.end()) {
double timeUntilExpiration = it->second.lastUpdate + SERVER_KNOBS->PEEK_TRACKER_EXPIRATION_TIME - now();
if(timeUntilExpiration < 1.0e-6) {
for(auto seq : it->second.sequence_version) {
if(!seq.second.isSet()) {
seq.second.sendError(timed_out());
}
}
it = logData->peekTracker.erase(it);
} else {
minTimeUntilExpiration = std::min(minTimeUntilExpiration, timeUntilExpiration);
++it;
}
}
wait( delay(minTimeUntilExpiration) );
}
}
ACTOR Future<Void> logPeekTrackers( LogData* logData ) {
loop {
int64_t logThreshold = 1;
if(logData->peekTracker.size() > SERVER_KNOBS->PEEK_LOGGING_AMOUNT) {
std::vector<int64_t> peekCounts;
peekCounts.reserve(logData->peekTracker.size());
for( auto& it : logData->peekTracker ) {
peekCounts.push_back(it.second.totalPeeks);
}
size_t pivot = peekCounts.size()-SERVER_KNOBS->PEEK_LOGGING_AMOUNT;
std::nth_element(peekCounts.begin(), peekCounts.begin()+pivot, peekCounts.end());
logThreshold = std::max<int64_t>(1,peekCounts[pivot]);
}
int logCount = 0;
for( auto& it : logData->peekTracker ) {
if(it.second.totalPeeks >= logThreshold) {
logCount++;
TraceEvent("PeekMetrics", logData->logId)
.detail("Tag", it.second.tag.toString())
.detail("Elapsed", now() - it.second.lastLogged)
.detail("MeanReplyBytes", it.second.replyBytes/it.second.totalPeeks)
.detail("TotalPeeks", it.second.totalPeeks)
.detail("UnblockedPeeks", it.second.unblockedPeeks)
.detail("DuplicatePeeks", it.second.duplicatePeeks)
.detail("Sequence", it.second.sequence_version.size() ? it.second.sequence_version.begin()->first : -1)
.detail("IdleSeconds", it.second.idleTime)
.detail("IdleMax", it.second.idleMax)
.detail("QueueSeconds", it.second.queueTime)
.detail("QueueMax", it.second.queueMax)
.detail("BlockSeconds", it.second.blockTime)
.detail("BlockMax", it.second.blockMax)
.detail("WorkSeconds", it.second.workTime)
.detail("WorkMax", it.second.workMax);
it.second.resetMetrics();
}
}
wait( delay(SERVER_KNOBS->PEEK_LOGGING_DELAY * std::max(1,logCount)) );
}
}
void getQueuingMetrics( TLogData* self, Reference<LogData> logData, TLogQueuingMetricsRequest const& req ) {
TLogQueuingMetricsReply reply;
reply.localTime = now();
reply.instanceID = self->instanceID;
reply.bytesInput = self->bytesInput;
reply.bytesDurable = self->bytesDurable;
reply.storageBytes = self->persistentData->getStorageBytes();
//FIXME: Add the knownCommittedVersion to this message and change ratekeeper to use that version.
reply.v = logData->durableKnownCommittedVersion;
req.reply.send( reply );
}
ACTOR Future<Void>
tLogSnapCreate(TLogSnapRequest snapReq, TLogData* self, Reference<LogData> logData) {
if (self->ignorePopUid != snapReq.snapUID.toString()) {
snapReq.reply.sendError(operation_failed());
return Void();
}
ExecCmdValueString snapArg(snapReq.snapPayload);
try {
int err = wait(execHelper(&snapArg, snapReq.snapUID, self->dataFolder, snapReq.role.toString()));
std::string uidStr = snapReq.snapUID.toString();
TraceEvent("ExecTraceTLog")
.detail("Uid", uidStr)
.detail("Status", err)
.detail("Role", snapReq.role)
.detail("Value", self->dataFolder)
.detail("ExecPayload", snapReq.snapPayload)
.detail("PersistentDataVersion", logData->persistentDataVersion)
.detail("PersistentDatadurableVersion", logData->persistentDataDurableVersion)
.detail("QueueCommittedVersion", logData->queueCommittedVersion.get())
.detail("Version", logData->version.get());
if (err != 0) {
throw operation_failed();
}
snapReq.reply.send(Void());
} catch (Error& e) {
TraceEvent("TLogSnapCreateError").error(e, true /*includeCancelled */);
if (e.code() != error_code_operation_cancelled) {
snapReq.reply.sendError(e);
} else {
throw e;
}
}
return Void();
}
ACTOR Future<Void>
tLogEnablePopReq(TLogEnablePopRequest enablePopReq, TLogData* self, Reference<LogData> logData) {
if (self->ignorePopUid != enablePopReq.snapUID.toString()) {
TraceEvent(SevWarn, "TLogPopDisableEnableUidMismatch")
.detail("IgnorePopUid", self->ignorePopUid)
.detail("UidStr", enablePopReq.snapUID.toString());
enablePopReq.reply.sendError(operation_failed());
return Void();
}
TraceEvent("EnableTLogPlayAllIgnoredPops2");
// use toBePopped and issue all the pops
std::map<Tag, Version>::iterator it;
vector<Future<Void>> ignoredPops;
self->ignorePopRequest = false;
self->ignorePopDeadline = 0.0;
self->ignorePopUid = "";
for (it = self->toBePopped.begin(); it != self->toBePopped.end(); it++) {
TraceEvent("PlayIgnoredPop")
.detail("Tag", it->first.toString())
.detail("Version", it->second);
ignoredPops.push_back(tLogPopCore(self, it->first, it->second, logData));
}
TraceEvent("TLogExecCmdPopEnable")
.detail("UidStr", enablePopReq.snapUID.toString())
.detail("IgnorePopUid", self->ignorePopUid)
.detail("IgnporePopRequest", self->ignorePopRequest)
.detail("IgnporePopDeadline", self->ignorePopDeadline)
.detail("PersistentDataVersion", logData->persistentDataVersion)
.detail("PersistentDatadurableVersion", logData->persistentDataDurableVersion)
.detail("QueueCommittedVersion", logData->queueCommittedVersion.get())
.detail("Version", logData->version.get());
wait(waitForAll(ignoredPops));
self->toBePopped.clear();
enablePopReq.reply.send(Void());
return Void();
}
ACTOR Future<Void> serveTLogInterface( TLogData* self, TLogInterface tli, Reference<LogData> logData, PromiseStream<Void> warningCollectorInput ) {
state Future<Void> dbInfoChange = Void();
loop choose {
when( wait( dbInfoChange ) ) {
dbInfoChange = self->dbInfo->onChange();
bool found = false;
if(self->dbInfo->get().recoveryState >= RecoveryState::ACCEPTING_COMMITS) {
for(auto& logs : self->dbInfo->get().logSystemConfig.tLogs) {
if( std::count( logs.tLogs.begin(), logs.tLogs.end(), logData->logId ) ) {
found = true;
break;
}
}
}
if(found && self->dbInfo->get().logSystemConfig.recruitmentID == logData->recruitmentID) {
logData->logSystem->set(ILogSystem::fromServerDBInfo( self->dbgid, self->dbInfo->get() ));
if(!logData->isPrimary) {
logData->logSystem->get()->pop(logData->logRouterPoppedVersion, logData->remoteTag, logData->durableKnownCommittedVersion, logData->locality);
}
if(!logData->isPrimary && logData->stopped) {
TraceEvent("TLogAlreadyStopped", self->dbgid);
logData->removed = logData->removed && logData->logSystem->get()->endEpoch();
}
} else {
logData->logSystem->set(Reference<ILogSystem>());
}
}
when( TLogPeekRequest req = waitNext( tli.peekMessages.getFuture() ) ) {
logData->addActor.send( tLogPeekMessages( self, req, logData ) );
}
when( TLogPopRequest req = waitNext( tli.popMessages.getFuture() ) ) {
logData->addActor.send(tLogPop(self, req, logData));
}
when( TLogCommitRequest req = waitNext( tli.commit.getFuture() ) ) {
//TraceEvent("TLogCommitReq", logData->logId).detail("Ver", req.version).detail("PrevVer", req.prevVersion).detail("LogVer", logData->version.get());
ASSERT(logData->isPrimary);
TEST(logData->stopped); // TLogCommitRequest while stopped
if (!logData->stopped)
logData->addActor.send( tLogCommit( self, req, logData, warningCollectorInput ) );
else
req.reply.sendError( tlog_stopped() );
}
when( ReplyPromise< TLogLockResult > reply = waitNext( tli.lock.getFuture() ) ) {
logData->addActor.send( tLogLock(self, reply, logData) );
}
when (TLogQueuingMetricsRequest req = waitNext(tli.getQueuingMetrics.getFuture())) {
getQueuingMetrics(self, logData, req);
}
when (TLogConfirmRunningRequest req = waitNext(tli.confirmRunning.getFuture())){
if (req.debugID.present() ) {
UID tlogDebugID = nondeterministicRandom()->randomUniqueID();
g_traceBatch.addAttach("TransactionAttachID", req.debugID.get().first(), tlogDebugID.first());
g_traceBatch.addEvent("TransactionDebug", tlogDebugID.first(), "TLogServer.TLogConfirmRunningRequest");
}
if (!logData->stopped)
req.reply.send(Void());
else
req.reply.sendError( tlog_stopped() );
}
when( TLogDisablePopRequest req = waitNext( tli.disablePopRequest.getFuture() ) ) {
if (self->ignorePopUid != "") {
TraceEvent(SevWarn, "TLogPopDisableonDisable")
.detail("IgnorePopUid", self->ignorePopUid)
.detail("UidStr", req.snapUID.toString())
.detail("PersistentDataVersion", logData->persistentDataVersion)
.detail("PersistentDatadurableVersion", logData->persistentDataDurableVersion)
.detail("QueueCommittedVersion", logData->queueCommittedVersion.get())
.detail("Version", logData->version.get());
req.reply.sendError(operation_failed());
} else {
//FIXME: As part of reverting snapshot V1, make ignorePopUid a UID instead of string
self->ignorePopRequest = true;
self->ignorePopUid = req.snapUID.toString();
self->ignorePopDeadline = g_network->now() + SERVER_KNOBS->TLOG_IGNORE_POP_AUTO_ENABLE_DELAY;
req.reply.send(Void());
}
}
when( TLogEnablePopRequest enablePopReq = waitNext( tli.enablePopRequest.getFuture() ) ) {
logData->addActor.send( tLogEnablePopReq( enablePopReq, self, logData) );
}
when( TLogSnapRequest snapReq = waitNext( tli.snapRequest.getFuture() ) ) {
logData->addActor.send( tLogSnapCreate( snapReq, self, logData) );
}
}
}
void removeLog( TLogData* self, Reference<LogData> logData ) {
TraceEvent("TLogRemoved", logData->logId).detail("Input", logData->bytesInput.getValue()).detail("Durable", logData->bytesDurable.getValue());
logData->stopped = true;
if(!logData->recoveryComplete.isSet()) {
logData->recoveryComplete.sendError(end_of_stream());
}
logData->addActor = PromiseStream<Future<Void>>(); //there could be items still in the promise stream if one of the actors threw an error immediately
self->id_data.erase(logData->logId);
if(self->id_data.size()) {
return;
} else {
throw worker_removed();
}
}
ACTOR Future<Void> pullAsyncData( TLogData* self, Reference<LogData> logData, std::vector<Tag> tags, Version beginVersion, Optional<Version> endVersion, bool poppedIsKnownCommitted ) {
state Future<Void> dbInfoChange = Void();
state Reference<ILogSystem::IPeekCursor> r;
state Version tagAt = beginVersion;
state Version lastVer = 0;
while (!endVersion.present() || logData->version.get() < endVersion.get()) {
loop {
choose {
when(wait( r ? r->getMore(TaskPriority::TLogCommit) : Never() ) ) {
break;
}
when( wait( dbInfoChange ) ) {
if( logData->logSystem->get() ) {
r = logData->logSystem->get()->peek( logData->logId, tagAt, endVersion, tags, true );
} else {
r = Reference<ILogSystem::IPeekCursor>();
}
dbInfoChange = logData->logSystem->onChange();
}
}
}
state double waitStartT = 0;
while( self->bytesInput - self->bytesDurable >= SERVER_KNOBS->TLOG_HARD_LIMIT_BYTES && !logData->stopped ) {
if (now() - waitStartT >= 1) {
TraceEvent(SevWarn, "TLogUpdateLag", logData->logId)
.detail("Version", logData->version.get())
.detail("PersistentDataVersion", logData->persistentDataVersion)
.detail("PersistentDataDurableVersion", logData->persistentDataDurableVersion);
waitStartT = now();
}
wait( delayJittered(.005, TaskPriority::TLogCommit) );
}
state Version ver = 0;
state std::vector<TagsAndMessage> messages;
loop {
state bool foundMessage = r->hasMessage();
if (!foundMessage || r->version().version != ver) {
ASSERT(r->version().version > lastVer);
if (ver) {
if(logData->stopped || (endVersion.present() && ver > endVersion.get())) {
return Void();
}
if(poppedIsKnownCommitted) {
logData->knownCommittedVersion = std::max(logData->knownCommittedVersion, r->popped());
logData->minKnownCommittedVersion = std::max(logData->minKnownCommittedVersion, r->getMinKnownCommittedVersion());
}
commitMessages(self, logData, ver, messages);
if(self->terminated.isSet()) {
return Void();
}
// Log the changes to the persistent queue, to be committed by commitQueue()
AlternativeTLogQueueEntryRef qe;
qe.version = ver;
qe.knownCommittedVersion = logData->knownCommittedVersion;
qe.alternativeMessages = &messages;
qe.id = logData->logId;
self->persistentQueue->push( qe, logData );
self->diskQueueCommitBytes += qe.expectedSize();
if( self->diskQueueCommitBytes > SERVER_KNOBS->MAX_QUEUE_COMMIT_BYTES ) {
self->largeDiskQueueCommitBytes.set(true);
}
// Notifies the commitQueue actor to commit persistentQueue, and also unblocks tLogPeekMessages actors
logData->version.set( ver );
wait( yield(TaskPriority::TLogCommit) );
}
lastVer = ver;
ver = r->version().version;
messages.clear();
if (!foundMessage) {
ver--;
if(ver > logData->version.get()) {
if(logData->stopped || (endVersion.present() && ver > endVersion.get())) {
return Void();
}
if(poppedIsKnownCommitted) {
logData->knownCommittedVersion = std::max(logData->knownCommittedVersion, r->popped());
logData->minKnownCommittedVersion = std::max(logData->minKnownCommittedVersion, r->getMinKnownCommittedVersion());
}
if(self->terminated.isSet()) {
return Void();
}
// Log the changes to the persistent queue, to be committed by commitQueue()
TLogQueueEntryRef qe;
qe.version = ver;
qe.knownCommittedVersion = logData->knownCommittedVersion;
qe.messages = StringRef();
qe.id = logData->logId;
self->persistentQueue->push( qe, logData );
self->diskQueueCommitBytes += qe.expectedSize();
if( self->diskQueueCommitBytes > SERVER_KNOBS->MAX_QUEUE_COMMIT_BYTES ) {
self->largeDiskQueueCommitBytes.set(true);
}
// Notifies the commitQueue actor to commit persistentQueue, and also unblocks tLogPeekMessages actors
logData->version.set( ver );
wait( yield(TaskPriority::TLogCommit) );
}
break;
}
}
messages.emplace_back(r->getMessageWithTags(), r->getTags());
r->nextMessage();
}
tagAt = std::max( r->version().version, logData->version.get() + 1 );
}
return Void();
}
ACTOR Future<Void> tLogCore( TLogData* self, Reference<LogData> logData, TLogInterface tli, bool pulledRecoveryVersions ) {
if(logData->removed.isReady()) {
wait(delay(0)); //to avoid iterator invalidation in restorePersistentState when removed is already ready
ASSERT(logData->removed.isError());
if(logData->removed.getError().code() != error_code_worker_removed) {
throw logData->removed.getError();
}
removeLog(self, logData);
return Void();
}
state PromiseStream<Void> warningCollectorInput;
state Future<Void> warningCollector = timeoutWarningCollector( warningCollectorInput.getFuture(), 1.0, "TLogQueueCommitSlow", self->dbgid );
state Future<Void> error = actorCollection( logData->addActor.getFuture() );
logData->addActor.send( waitFailureServer( tli.waitFailure.getFuture()) );
logData->addActor.send( logData->removed );
//FIXME: update tlogMetrics to include new information, or possibly only have one copy for the shared instance
logData->addActor.send( traceCounters("TLogMetrics", logData->logId, SERVER_KNOBS->STORAGE_LOGGING_DELAY, &logData->cc, logData->logId.toString() + "/TLogMetrics"));
logData->addActor.send( serveTLogInterface(self, tli, logData, warningCollectorInput) );
logData->addActor.send( cleanupPeekTrackers(logData.getPtr()) );
logData->addActor.send( logPeekTrackers(logData.getPtr()) );
if(!logData->isPrimary) {
std::vector<Tag> tags;
tags.push_back(logData->remoteTag);
logData->addActor.send( pullAsyncData(self, logData, tags, pulledRecoveryVersions ? logData->recoveredAt + 1 : logData->unrecoveredBefore, Optional<Version>(), true) );
}
try {
wait( error );
throw internal_error();
} catch( Error &e ) {
if( e.code() != error_code_worker_removed )
throw;
removeLog(self, logData);
return Void();
}
}
ACTOR Future<Void> checkEmptyQueue(TLogData* self) {
TraceEvent("TLogCheckEmptyQueueBegin", self->dbgid);
try {
TLogQueueEntry r = wait( self->persistentQueue->readNext(self) );
throw internal_error();
} catch (Error& e) {
if (e.code() != error_code_end_of_stream) throw;
TraceEvent("TLogCheckEmptyQueueEnd", self->dbgid);
return Void();
}
}
ACTOR Future<Void> checkRecovered(TLogData* self) {
TraceEvent("TLogCheckRecoveredBegin", self->dbgid);
Optional<Value> v = wait( self->persistentData->readValue(StringRef()) );
TraceEvent("TLogCheckRecoveredEnd", self->dbgid);
return Void();
}
ACTOR Future<Void> restorePersistentState( TLogData* self, LocalityData locality, Promise<Void> oldLog, Promise<Void> recovered, PromiseStream<InitializeTLogRequest> tlogRequests ) {
state double startt = now();
state Reference<LogData> logData;
state KeyRange tagKeys;
// PERSIST: Read basic state from persistentData; replay persistentQueue but don't erase it
TraceEvent("TLogRestorePersistentState", self->dbgid);
state IKeyValueStore *storage = self->persistentData;
wait(storage->init());
state Future<Optional<Value>> fFormat = storage->readValue(persistFormat.key);
state Future<Standalone<RangeResultRef>> fVers = storage->readRange(persistCurrentVersionKeys);
state Future<Standalone<RangeResultRef>> fKnownCommitted = storage->readRange(persistKnownCommittedVersionKeys);
state Future<Standalone<RangeResultRef>> fLocality = storage->readRange(persistLocalityKeys);
state Future<Standalone<RangeResultRef>> fLogRouterTags = storage->readRange(persistLogRouterTagsKeys);
state Future<Standalone<RangeResultRef>> fTxsTags = storage->readRange(persistTxsTagsKeys);
state Future<Standalone<RangeResultRef>> fRecoverCounts = storage->readRange(persistRecoveryCountKeys);
// FIXME: metadata in queue?
wait( waitForAll( std::vector{fFormat} ) );
wait( waitForAll( std::vector{fVers, fKnownCommitted, fLocality, fLogRouterTags, fTxsTags, fRecoverCounts} ) );
if (fFormat.get().present() && !persistFormatReadableRange.contains( fFormat.get().get() )) {
//FIXME: remove when we no longer need to test upgrades from 4.X releases
if(g_network->isSimulated()) {
TraceEvent("ElapsedTime").detail("SimTime", now()).detail("RealTime", 0).detail("RandomUnseed", 0);
flushAndExit(0);
}
TraceEvent(SevError, "UnsupportedDBFormat", self->dbgid).detail("Format", fFormat.get().get()).detail("Expected", persistFormat.value.toString());
throw worker_recovery_failed();
}
if (!fFormat.get().present()) {
Standalone<RangeResultRef> v = wait( self->persistentData->readRange( KeyRangeRef(StringRef(), LiteralStringRef("\xff")), 1 ) );
if (!v.size()) {
TEST(true); // The DB is completely empty, so it was never initialized. Delete it.
throw worker_removed();
} else {
// This should never happen
TraceEvent(SevError, "NoDBFormatKey", self->dbgid).detail("FirstKey", v[0].key);
ASSERT( false );
throw worker_recovery_failed();
}
}
state std::vector<Future<ErrorOr<Void>>> removed;
if(fFormat.get().get() == LiteralStringRef("FoundationDB/LogServer/2/3")) {
//FIXME: need for upgrades from 5.X to 6.0, remove once this upgrade path is no longer needed
if(recovered.canBeSet()) recovered.send(Void());
oldLog.send(Void());
while(!tlogRequests.isEmpty()) {
tlogRequests.getFuture().pop().reply.sendError(recruitment_failed());
}
wait( oldTLog_4_6::tLog(self->persistentData, self->rawPersistentQueue, self->dbInfo, locality, self->dbgid, self->workerID) );
throw internal_error();
}
ASSERT(fVers.get().size() == fRecoverCounts.get().size());
state std::map<UID, int8_t> id_locality;
for(auto it : fLocality.get()) {
id_locality[ BinaryReader::fromStringRef<UID>(it.key.removePrefix(persistLocalityKeys.begin), Unversioned())] = BinaryReader::fromStringRef<int8_t>( it.value, Unversioned() );
}
state std::map<UID, int> id_logRouterTags;
for(auto it : fLogRouterTags.get()) {
id_logRouterTags[ BinaryReader::fromStringRef<UID>(it.key.removePrefix(persistLogRouterTagsKeys.begin), Unversioned())] = BinaryReader::fromStringRef<int>( it.value, Unversioned() );
}
state std::map<UID, int> id_txsTags;
for(auto it : fTxsTags.get()) {
id_txsTags[ BinaryReader::fromStringRef<UID>(it.key.removePrefix(persistTxsTagsKeys.begin), Unversioned())] = BinaryReader::fromStringRef<int>( it.value, Unversioned() );
}
state std::map<UID, Version> id_knownCommitted;
for(auto it : fKnownCommitted.get()) {
id_knownCommitted[ BinaryReader::fromStringRef<UID>(it.key.removePrefix(persistKnownCommittedVersionKeys.begin), Unversioned())] = BinaryReader::fromStringRef<Version>( it.value, Unversioned() );
}
state int idx = 0;
state Promise<Void> registerWithMaster;
state std::map<UID, TLogInterface> id_interf;
for(idx = 0; idx < fVers.get().size(); idx++) {
state KeyRef rawId = fVers.get()[idx].key.removePrefix(persistCurrentVersionKeys.begin);
UID id1 = BinaryReader::fromStringRef<UID>( rawId, Unversioned() );
UID id2 = BinaryReader::fromStringRef<UID>( fRecoverCounts.get()[idx].key.removePrefix(persistRecoveryCountKeys.begin), Unversioned() );
ASSERT(id1 == id2);
TLogInterface recruited(id1, self->dbgid, locality);
recruited.initEndpoints();
DUMPTOKEN( recruited.peekMessages );
DUMPTOKEN( recruited.popMessages );
DUMPTOKEN( recruited.commit );
DUMPTOKEN( recruited.lock );
DUMPTOKEN( recruited.getQueuingMetrics );
DUMPTOKEN( recruited.confirmRunning );
//We do not need the remoteTag, because we will not be loading any additional data
logData = Reference<LogData>( new LogData(self, recruited, Tag(), true, id_logRouterTags[id1], id_txsTags[id1], UID(), std::vector<Tag>(), "Restored") );
logData->locality = id_locality[id1];
logData->stopped = true;
self->id_data[id1] = logData;
id_interf[id1] = recruited;
logData->knownCommittedVersion = id_knownCommitted[id1];
Version ver = BinaryReader::fromStringRef<Version>( fVers.get()[idx].value, Unversioned() );
logData->persistentDataVersion = ver;
logData->persistentDataDurableVersion = ver;
logData->version.set(ver);
logData->recoveryCount = BinaryReader::fromStringRef<DBRecoveryCount>( fRecoverCounts.get()[idx].value, Unversioned() );
logData->removed = rejoinMasters(self, recruited, logData->recoveryCount, registerWithMaster.getFuture(), false);
removed.push_back(errorOr(logData->removed));
TraceEvent("TLogRestorePersistentStateVer", id1).detail("Ver", ver);
// Restore popped keys. Pop operations that took place after the last (committed) updatePersistentDataVersion might be lost, but
// that is fine because we will get the corresponding data back, too.
tagKeys = prefixRange( rawId.withPrefix(persistTagPoppedKeys.begin) );
loop {
if(logData->removed.isReady()) break;
Standalone<RangeResultRef> data = wait( self->persistentData->readRange( tagKeys, BUGGIFY ? 3 : 1<<30, 1<<20 ) );
if (!data.size()) break;
((KeyRangeRef&)tagKeys) = KeyRangeRef( keyAfter(data.back().key, tagKeys.arena()), tagKeys.end );
for(auto &kv : data) {
Tag tag = decodeTagPoppedKey(rawId, kv.key);
Version popped = decodeTagPoppedValue(kv.value);
TraceEvent("TLogRestorePopped", logData->logId).detail("Tag", tag.toString()).detail("To", popped);
auto tagData = logData->getTagData(tag);
ASSERT( !tagData );
logData->createTagData(tag, popped, false, false, false);
}
}
}
state Future<Void> allRemoved = waitForAll(removed);
state UID lastId = UID(1,1); //initialized so it will not compare equal to a default UID
state double recoverMemoryLimit = SERVER_KNOBS->TLOG_RECOVER_MEMORY_LIMIT;
if (BUGGIFY) recoverMemoryLimit = std::max<double>(SERVER_KNOBS->BUGGIFY_RECOVER_MEMORY_LIMIT, SERVER_KNOBS->TLOG_SPILL_THRESHOLD);
try {
loop {
if(allRemoved.isReady()) {
TEST(true); //all tlogs removed during queue recovery
throw worker_removed();
}
choose {
when( TLogQueueEntry qe = wait( self->persistentQueue->readNext(self) ) ) {
if(!self->queueOrder.size() || self->queueOrder.back() != qe.id) self->queueOrder.push_back(qe.id);
if(qe.id != lastId) {
lastId = qe.id;
auto it = self->id_data.find(qe.id);
if(it != self->id_data.end()) {
logData = it->second;
} else {
logData = Reference<LogData>();
}
}
//TraceEvent("TLogRecoveredQE", self->dbgid).detail("LogId", qe.id).detail("Ver", qe.version).detail("MessageBytes", qe.messages.size()).detail("Tags", qe.tags.size())
// .detail("Tag0", qe.tags.size() ? qe.tags[0].tag : invalidTag).detail("Version", logData->version.get());
if(logData) {
logData->knownCommittedVersion = std::max(logData->knownCommittedVersion, qe.knownCommittedVersion);
if( qe.version > logData->version.get() ) {
commitMessages(self, logData, qe.version, qe.arena(), qe.messages);
logData->version.set( qe.version );
logData->queueCommittedVersion.set( qe.version );
while (self->bytesInput - self->bytesDurable >= recoverMemoryLimit) {
TEST(true); // Flush excess data during TLog queue recovery
TraceEvent("FlushLargeQueueDuringRecovery", self->dbgid).detail("BytesInput", self->bytesInput).detail("BytesDurable", self->bytesDurable).detail("Version", logData->version.get()).detail("PVer", logData->persistentDataVersion);
choose {
when( wait( updateStorage(self) ) ) {}
when( wait( allRemoved ) ) { throw worker_removed(); }
}
}
}
}
}
when( wait( allRemoved ) ) { throw worker_removed(); }
}
}
} catch (Error& e) {
if (e.code() != error_code_end_of_stream) throw;
}
TraceEvent("TLogRestorePersistentStateDone", self->dbgid).detail("Took", now()-startt);
TEST( now()-startt >= 1.0 ); // TLog recovery took more than 1 second
for(auto it : self->id_data) {
if(it.second->queueCommittedVersion.get() == 0) {
TraceEvent("TLogZeroVersion", self->dbgid).detail("LogId", it.first);
it.second->queueCommittedVersion.set(it.second->version.get());
}
it.second->recoveryComplete.sendError(end_of_stream());
self->sharedActors.send( tLogCore( self, it.second, id_interf[it.first], false ) );
}
if(registerWithMaster.canBeSet()) registerWithMaster.send(Void());
return Void();
}
bool tlogTerminated( TLogData* self, IKeyValueStore* persistentData, TLogQueue* persistentQueue, Error const& e ) {
// Dispose the IKVS (destroying its data permanently) only if this shutdown is definitely permanent. Otherwise just close it.
if (e.code() == error_code_worker_removed || e.code() == error_code_recruitment_failed) {
persistentData->dispose();
persistentQueue->dispose();
} else {
persistentData->close();
persistentQueue->close();
}
if ( e.code() == error_code_worker_removed ||
e.code() == error_code_recruitment_failed ||
e.code() == error_code_file_not_found )
{
TraceEvent("TLogTerminated", self->dbgid).error(e, true);
return true;
} else
return false;
}
ACTOR Future<Void> updateLogSystem(TLogData* self, Reference<LogData> logData, LogSystemConfig recoverFrom, Reference<AsyncVar<Reference<ILogSystem>>> logSystem) {
loop {
bool found = false;
if(self->dbInfo->get().logSystemConfig.recruitmentID == logData->recruitmentID) {
if( self->dbInfo->get().logSystemConfig.isNextGenerationOf(recoverFrom) ) {
logSystem->set(ILogSystem::fromOldLogSystemConfig( logData->logId, self->dbInfo->get().myLocality, self->dbInfo->get().logSystemConfig ));
found = true;
} else if( self->dbInfo->get().logSystemConfig.isEqualIds(recoverFrom) ) {
logSystem->set(ILogSystem::fromLogSystemConfig( logData->logId, self->dbInfo->get().myLocality, self->dbInfo->get().logSystemConfig, false, true ));
found = true;
}
else if( self->dbInfo->get().recoveryState >= RecoveryState::ACCEPTING_COMMITS ) {
logSystem->set(ILogSystem::fromLogSystemConfig( logData->logId, self->dbInfo->get().myLocality, self->dbInfo->get().logSystemConfig, true ));
found = true;
}
}
if( !found ) {
logSystem->set(Reference<ILogSystem>());
} else {
logData->logSystem->get()->pop(logData->logRouterPoppedVersion, logData->remoteTag, logData->durableKnownCommittedVersion, logData->locality);
}
TraceEvent("TLogUpdate", self->dbgid).detail("LogId", logData->logId).detail("RecruitmentID", logData->recruitmentID).detail("DbRecruitmentID", self->dbInfo->get().logSystemConfig.recruitmentID).detail("RecoverFrom", recoverFrom.toString()).detail("DbInfo", self->dbInfo->get().logSystemConfig.toString()).detail("Found", found).detail("LogSystem", (bool) logSystem->get() ).detail("RecoveryState", (int)self->dbInfo->get().recoveryState);
for(auto it : self->dbInfo->get().logSystemConfig.oldTLogs) {
TraceEvent("TLogUpdateOld", self->dbgid).detail("LogId", logData->logId).detail("DbInfo", it.toString());
}
wait( self->dbInfo->onChange() );
}
}
ACTOR Future<Void> tLogStart( TLogData* self, InitializeTLogRequest req, LocalityData locality ) {
state TLogInterface recruited(self->dbgid, locality);
recruited.initEndpoints();
DUMPTOKEN( recruited.peekMessages );
DUMPTOKEN( recruited.popMessages );
DUMPTOKEN( recruited.commit );
DUMPTOKEN( recruited.lock );
DUMPTOKEN( recruited.getQueuingMetrics );
DUMPTOKEN( recruited.confirmRunning );
for(auto it : self->id_data) {
if( !it.second->stopped ) {
TraceEvent("TLogStoppedByNewRecruitment", self->dbgid).detail("StoppedId", it.first.toString()).detail("RecruitedId", recruited.id()).detail("EndEpoch", it.second->logSystem->get().getPtr() != 0);
if(!it.second->isPrimary && it.second->logSystem->get()) {
it.second->removed = it.second->removed && it.second->logSystem->get()->endEpoch();
}
if(it.second->committingQueue.canBeSet()) {
it.second->committingQueue.sendError(worker_removed());
}
}
it.second->stopped = true;
if(!it.second->recoveryComplete.isSet()) {
it.second->recoveryComplete.sendError(end_of_stream());
}
it.second->stopCommit.trigger();
}
bool recovering = (req.recoverFrom.logSystemType == LogSystemType::tagPartitioned);
state Reference<LogData> logData = Reference<LogData>( new LogData(self, recruited, req.remoteTag, req.isPrimary, req.logRouterTags, req.txsTags, req.recruitmentID, req.allTags, recovering ? "Recovered" : "Recruited") );
self->id_data[recruited.id()] = logData;
logData->locality = req.locality;
logData->recoveryCount = req.epoch;
logData->removed = rejoinMasters(self, recruited, req.epoch, Future<Void>(Void()), req.isPrimary);
self->queueOrder.push_back(recruited.id());
TraceEvent("TLogStart", logData->logId);
state Future<Void> updater;
state bool pulledRecoveryVersions = false;
try {
if( logData->removed.isReady() ) {
throw logData->removed.getError();
}
if (recovering) {
logData->unrecoveredBefore = req.startVersion;
logData->recoveredAt = req.recoverAt;
logData->knownCommittedVersion = req.startVersion - 1;
logData->persistentDataVersion = logData->unrecoveredBefore - 1;
logData->persistentDataDurableVersion = logData->unrecoveredBefore - 1;
logData->queueCommittedVersion.set( logData->unrecoveredBefore - 1 );
logData->version.set( logData->unrecoveredBefore - 1 );
logData->unpoppedRecoveredTags = req.allTags.size();
wait( initPersistentState( self, logData ) || logData->removed );
TraceEvent("TLogRecover", self->dbgid).detail("LogId", logData->logId).detail("At", req.recoverAt).detail("Known", req.knownCommittedVersion).detail("Unrecovered", logData->unrecoveredBefore).detail("Tags", describe(req.recoverTags)).detail("Locality", req.locality).detail("LogRouterTags", logData->logRouterTags);
if(logData->recoveryComplete.isSet()) {
throw worker_removed();
}
updater = updateLogSystem(self, logData, req.recoverFrom, logData->logSystem);
logData->initialized = true;
self->newLogData.trigger();
if((req.isPrimary || req.recoverFrom.logRouterTags == 0) && !logData->stopped && logData->unrecoveredBefore <= req.recoverAt) {
if(req.recoverFrom.logRouterTags > 0 && req.locality != tagLocalitySatellite) {
logData->logRouterPopToVersion = req.recoverAt;
std::vector<Tag> tags;
tags.push_back(logData->remoteTag);
wait(pullAsyncData(self, logData, tags, logData->unrecoveredBefore, req.recoverAt, true) || logData->removed);
} else if(!req.recoverTags.empty()) {
ASSERT(logData->unrecoveredBefore > req.knownCommittedVersion);
wait(pullAsyncData(self, logData, req.recoverTags, req.knownCommittedVersion + 1, req.recoverAt, false) || logData->removed);
}
pulledRecoveryVersions = true;
logData->knownCommittedVersion = req.recoverAt;
}
if((req.isPrimary || req.recoverFrom.logRouterTags == 0) && logData->version.get() < req.recoverAt && !logData->stopped) {
// Log the changes to the persistent queue, to be committed by commitQueue()
TLogQueueEntryRef qe;
qe.version = req.recoverAt;
qe.knownCommittedVersion = logData->knownCommittedVersion;
qe.messages = StringRef();
qe.id = logData->logId;
self->persistentQueue->push( qe, logData );
self->diskQueueCommitBytes += qe.expectedSize();
if( self->diskQueueCommitBytes > SERVER_KNOBS->MAX_QUEUE_COMMIT_BYTES ) {
self->largeDiskQueueCommitBytes.set(true);
}
logData->version.set( req.recoverAt );
}
if(logData->recoveryComplete.isSet()) {
throw worker_removed();
}
logData->addActor.send( respondToRecovered( recruited, logData->recoveryComplete ) );
} else {
// Brand new tlog, initialization has already been done by caller
wait( initPersistentState( self, logData ) || logData->removed );
if(logData->recoveryComplete.isSet()) {
throw worker_removed();
}
logData->initialized = true;
self->newLogData.trigger();
logData->recoveryComplete.send(Void());
}
wait(logData->committingQueue.getFuture() || logData->removed );
} catch( Error &e ) {
req.reply.sendError(recruitment_failed());
if( e.code() != error_code_worker_removed ) {
throw;
}
wait( delay(0.0) ); // if multiple recruitment requests were already in the promise stream make sure they are all started before any are removed
removeLog(self, logData);
return Void();
}
req.reply.send( recruited );
TraceEvent("TLogReady", logData->logId).detail("AllTags", describe(req.allTags)).detail("Locality", logData->locality);
updater = Void();
wait( tLogCore( self, logData, recruited, pulledRecoveryVersions ) );
return Void();
}
ACTOR Future<Void> startSpillingInTenSeconds(TLogData* self, UID tlogId, Reference<AsyncVar<UID>> activeSharedTLog) {
wait(delay(10));
if (activeSharedTLog->get() != tlogId) {
// TODO: This should fully spill, but currently doing so will cause us to no longer update poppedVersion
// and QuietDatabase will hang thinking our TLog is behind.
self->targetVolatileBytes = SERVER_KNOBS->REFERENCE_SPILL_UPDATE_STORAGE_BYTE_LIMIT * 2;
}
return Void();
}
// New tLog (if !recoverFrom.size()) or restore from network
ACTOR Future<Void> tLog( IKeyValueStore* persistentData, IDiskQueue* persistentQueue, Reference<AsyncVar<ServerDBInfo>> db, LocalityData locality, PromiseStream<InitializeTLogRequest> tlogRequests, UID tlogId, UID workerID, bool restoreFromDisk, Promise<Void> oldLog, Promise<Void> recovered, std::string folder, Reference<AsyncVar<bool>> degraded, Reference<AsyncVar<UID>> activeSharedTLog) {
state TLogData self( tlogId, workerID, persistentData, persistentQueue, db, degraded, folder );
state Future<Void> error = actorCollection( self.sharedActors.getFuture() );
TraceEvent("SharedTlog", tlogId);
try {
if(restoreFromDisk) {
wait( restorePersistentState( &self, locality, oldLog, recovered, tlogRequests ) );
} else {
wait( ioTimeoutError( checkEmptyQueue(&self) && checkRecovered(&self), SERVER_KNOBS->TLOG_MAX_CREATE_DURATION ) );
}
//Disk errors need a chance to kill this actor.
wait(delay(0.000001));
if(recovered.canBeSet()) recovered.send(Void());
self.sharedActors.send( commitQueue(&self) );
self.sharedActors.send( updateStorageLoop(&self) );
state Future<Void> activeSharedChange = Void();
loop {
choose {
when ( InitializeTLogRequest req = waitNext(tlogRequests.getFuture() ) ) {
if( !self.tlogCache.exists( req.recruitmentID ) ) {
self.tlogCache.set( req.recruitmentID, req.reply.getFuture() );
self.sharedActors.send( self.tlogCache.removeOnReady( req.recruitmentID, tLogStart( &self, req, locality ) ) );
} else {
forwardPromise( req.reply, self.tlogCache.get( req.recruitmentID ) );
}
}
when ( wait( error ) ) { throw internal_error(); }
when ( wait( activeSharedChange ) ) {
if (activeSharedTLog->get() == tlogId) {
self.targetVolatileBytes = SERVER_KNOBS->TLOG_SPILL_THRESHOLD;
} else {
self.sharedActors.send( startSpillingInTenSeconds(&self, tlogId, activeSharedTLog) );
}
activeSharedChange = activeSharedTLog->onChange();
}
}
}
} catch (Error& e) {
self.terminated.send(Void());
TraceEvent("TLogError", tlogId).error(e, true);
if(recovered.canBeSet()) recovered.send(Void());
while(!tlogRequests.isEmpty()) {
tlogRequests.getFuture().pop().reply.sendError(recruitment_failed());
}
for( auto& it : self.id_data ) {
if(!it.second->recoveryComplete.isSet()) {
it.second->recoveryComplete.sendError(end_of_stream());
}
}
if (tlogTerminated( &self, persistentData, self.persistentQueue, e )) {
return Void();
} else {
throw;
}
}
}
// UNIT TESTS
struct DequeAllocatorStats {
static int64_t allocatedBytes;
};
int64_t DequeAllocatorStats::allocatedBytes = 0;
template <class T>
struct DequeAllocator : std::allocator<T> {
template<typename U>
struct rebind {
typedef DequeAllocator<U> other;
};
DequeAllocator() {}
template<typename U>
DequeAllocator(DequeAllocator<U> const& u) : std::allocator<T>(u) {}
T* allocate(std::size_t n, std::allocator<void>::const_pointer hint = 0) {
DequeAllocatorStats::allocatedBytes += n * sizeof(T);
//fprintf(stderr, "Allocating %lld objects for %lld bytes (total allocated: %lld)\n", n, n * sizeof(T), DequeAllocatorStats::allocatedBytes);
return std::allocator<T>::allocate(n, hint);
}
void deallocate(T* p, std::size_t n) {
DequeAllocatorStats::allocatedBytes -= n * sizeof(T);
//fprintf(stderr, "Deallocating %lld objects for %lld bytes (total allocated: %lld)\n", n, n * sizeof(T), DequeAllocatorStats::allocatedBytes);
return std::allocator<T>::deallocate(p, n);
}
};
TEST_CASE("/fdbserver/tlogserver/VersionMessagesOverheadFactor" ) {
typedef std::pair<Version, LengthPrefixedStringRef> TestType; // type used by versionMessages
for(int i = 1; i < 9; ++i) {
for(int j = 0; j < 20; ++j) {
DequeAllocatorStats::allocatedBytes = 0;
DequeAllocator<TestType> allocator;
std::deque<TestType, DequeAllocator<TestType>> d(allocator);
int numElements = deterministicRandom()->randomInt(pow(10, i-1), pow(10, i));
for(int k = 0; k < numElements; ++k) {
d.push_back(TestType());
}
int removedElements = 0;//deterministicRandom()->randomInt(0, numElements); // FIXME: the overhead factor does not accurately account for removal!
for(int k = 0; k < removedElements; ++k) {
d.pop_front();
}
int64_t dequeBytes = DequeAllocatorStats::allocatedBytes + sizeof(std::deque<TestType>);
int64_t insertedBytes = (numElements-removedElements) * sizeof(TestType);
double overheadFactor = std::max<double>(insertedBytes, dequeBytes-10000) / insertedBytes; // We subtract 10K here as an estimated upper bound for the fixed cost of an std::deque
//fprintf(stderr, "%d elements (%d inserted, %d removed):\n", numElements-removedElements, numElements, removedElements);
//fprintf(stderr, "Allocated %lld bytes to store %lld bytes (%lf overhead factor)\n", dequeBytes, insertedBytes, overheadFactor);
ASSERT(overheadFactor * 1024 <= SERVER_KNOBS->VERSION_MESSAGES_OVERHEAD_FACTOR_1024THS);
}
}
return Void();
}
} // namespace oldTLog_6_0
|
#pragma once
//------------------------------------------------------------------------------
//
// Copyright 2018-2020 Fetch.AI Limited
//
// 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/byte_array/const_byte_array.hpp"
namespace fetch {
namespace byte_array {
class Token : public ConstByteArray
{
public:
Token() = default;
explicit Token(char const *str)
: ConstByteArray(str)
{}
explicit Token(std::string const &str)
: ConstByteArray(str.c_str())
{}
explicit Token(ConstByteArray const &other)
: ConstByteArray(other)
{}
explicit Token(ConstByteArray &&other)
: ConstByteArray(other)
{}
Token(ConstByteArray const &other, std::size_t start, std::size_t length)
: ConstByteArray(other, start, length)
{}
bool operator==(ConstByteArray const &other) const
{
return ConstByteArray::operator==(other);
}
bool operator!=(ConstByteArray const &other) const
{
return !(*this == other);
}
void SetType(int const &t)
{
type_ = t;
}
void SetLine(int const &l)
{
line_ = l;
}
void SetChar(std::size_t c)
{
char_ = c;
}
int type() const
{
return type_;
}
int line() const
{
return line_;
}
std::size_t character() const
{
return char_;
}
private:
int type_ = -1;
int line_ = 0;
std::size_t char_ = 0;
};
} // namespace byte_array
} // namespace fetch
|
/**
* Marlin 3D Printer Firmware
* Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
*
* Based on Sprinter and grbl.
* Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
*/
#include "tft_image.h"
#include <stddef.h>
const tImage NoLogo = { (void *)NULL, 0, 0, NOCOLORS };
const tImage MarlinLogo112x38x1 = { (void *)marlin_logo_112x38x1, 112, 38, GREYSCALE1 };
const tImage MarlinLogo228x255x2 = { (void *)marlin_logo_228x255x2, 228, 255, GREYSCALE2 };
const tImage MarlinLogo228x255x4 = { (void *)marlin_logo_228x255x4, 228, 255, GREYSCALE4 };
const tImage MarlinLogo195x59x16 = { (void *)marlin_logo_195x59x16, 195, 59, HIGHCOLOR };
const tImage MarlinLogo320x240x16 = { (void *)marlin_logo_320x240x16, 320, 240, HIGHCOLOR };
const tImage MarlinLogo480x320x16 = { (void *)marlin_logo_480x320x16, 480, 320, HIGHCOLOR };
const tImage Background320x30x16 = { (void *)background_320x30x16, 320, 30, HIGHCOLOR };
const tImage HotEnd_64x64x4 = { (void *)hotend_64x64x4, 64, 64, GREYSCALE4 };
const tImage Bed_64x64x4 = { (void *)bed_64x64x4, 64, 64, GREYSCALE4 };
const tImage Bed_Heated_64x64x4 = { (void *)bed_heated_64x64x4, 64, 64, GREYSCALE4 };
const tImage Chamber_64x64x4 = { (void *)chamber_64x64x4, 64, 64, GREYSCALE4 };
const tImage Chamber_Heated_64x64x4 = { (void *)chamber_heated_64x64x4, 64, 64, GREYSCALE4 };
const tImage Fan0_64x64x4 = { (void *)fan0_64x64x4, 64, 64, GREYSCALE4 };
const tImage Fan1_64x64x4 = { (void *)fan1_64x64x4, 64, 64, GREYSCALE4 };
const tImage Fan_Slow0_64x64x4 = { (void *)fan_slow0_64x64x4, 64, 64, GREYSCALE4 };
const tImage Fan_Slow1_64x64x4 = { (void *)fan_slow1_64x64x4, 64, 64, GREYSCALE4 };
const tImage Fan_Fast0_64x64x4 = { (void *)fan_fast0_64x64x4, 64, 64, GREYSCALE4 };
const tImage Fan_Fast1_64x64x4 = { (void *)fan_fast1_64x64x4, 64, 64, GREYSCALE4 };
const tImage SD_64x64x4 = { (void *)sd_64x64x4, 64, 64, GREYSCALE4 };
const tImage Menu_64x64x4 = { (void *)menu_64x64x4, 64, 64, GREYSCALE4 };
const tImage Settings_64x64x4 = { (void *)settings_64x64x4, 64, 64, GREYSCALE4 };
const tImage Confirm_64x64x4 = { (void *)confirm_64x64x4, 64, 64, GREYSCALE4 };
const tImage Cancel_64x64x4 = { (void *)cancel_64x64x4, 64, 64, GREYSCALE4 };
const tImage Increase_64x64x4 = { (void *)increase_64x64x4, 64, 64, GREYSCALE4 };
const tImage Decrease_64x64x4 = { (void *)decrease_64x64x4, 64, 64, GREYSCALE4 };
const tImage Pause_64x64x4 = { (void *)pause_64x64x4, 64, 64, GREYSCALE4 };
const tImage Feedrate_32x32x4 = { (void *)feedrate_32x32x4, 32, 32, GREYSCALE4 };
const tImage Flowrate_32x32x4 = { (void *)flowrate_32x32x4, 32, 32, GREYSCALE4 };
const tImage Directory_32x32x4 = { (void *)directory_32x32x4, 32, 32, GREYSCALE4 };
const tImage Back_32x32x4 = { (void *)back_32x32x4, 32, 32, GREYSCALE4 };
const tImage Up_32x32x4 = { (void *)up_32x32x4, 32, 32, GREYSCALE4 };
const tImage Down_32x32x4 = { (void *)down_32x32x4, 32, 32, GREYSCALE4 };
const tImage Left_32x32x4 = { (void *)left_32x32x4, 32, 32, GREYSCALE4 };
const tImage Right_32x32x4 = { (void *)right_32x32x4, 32, 32, GREYSCALE4 };
const tImage Refresh_32x32x4 = { (void *)refresh_32x32x4, 32, 32, GREYSCALE4 };
const tImage Leveling_32x32x4 = { (void *)leveling_32x32x4, 32, 32, GREYSCALE4 };
const tImage Slider8x16x4 = { (void *)slider_8x16x4, 8, 16, GREYSCALE4 };
extern const tImage Images[imgCount];
|
/*
pagefaulthandler.cpp
Copyright (c) 17 Yann BOUCHER (yann)
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 "paging.hpp"
#include "panic.hpp"
#include "mem/page_fault.hpp"
#include <libdisasm/libdis.h>
bool Paging::page_fault_handler(registers *regs)
{
panic_regs = *regs;
PageFault fault;
fault.mcontext = regs;
fault.address = cr2();
fault.level = (regs->err_code & (1<<2)) ? PageFault::User : PageFault::Kernel;
fault.error = (regs->err_code & (1<<0)) ? PageFault::Protection : PageFault::NonPresent;
fault.type = (regs->err_code & (1<<1)) ? PageFault::Write :
(regs->err_code & (1<<4)) ? PageFault::Execute
: PageFault::Read;
if (regs->err_code & (1<<3)) // reserved bit write, this should definitely never happen
{
panic("Reserved paging structure bit write !\n");
}
log_serial("returning to 0x%x\n", regs->eip);
// if eip seems invalid, try to manually pop the stack and return
if (!Memory::is_mapped((unsigned char*)regs->eip))
{
if (Memory::is_mapped((unsigned char*)regs->esp))
{
uintptr_t return_eip = *(uintptr_t*)(regs->esp);
regs->eip = return_eip;
regs->esp += sizeof(uintptr_t);
log_serial("more like 0x%x\n", return_eip);
}
}
else
{
// if we actually return, move eip to the next instruction
uint8_t buf[x86_max_insn_size()];
memcpy(buf, (uint8_t*)regs->eip, sizeof(buf));
x86_invariant_t ins;
x86_invariant_disasm(buf, x86_max_insn_size(), &ins);
regs->eip += ins.size;
}
page_fault_entry(fault);
return true;
}
|
// 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 "chrome/browser/ui/views/ash/screenshot_taker.h"
#include <string>
#include "ash/shell.h"
#include "ash/shell_window_ids.h"
#include "base/bind.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/i18n/time_formatting.h"
#include "base/logging.h"
#include "base/memory/ref_counted_memory.h"
#include "base/stringprintf.h"
#include "base/time.h"
#include "chrome/browser/download/download_util.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/window_snapshot/window_snapshot.h"
#include "chrome/common/pref_names.h"
#include "content/public/browser/browser_thread.h"
#include "ui/aura/window.h"
#if defined(OS_CHROMEOS)
#include "chrome/browser/chromeos/login/user_manager.h"
#endif
namespace {
bool ShouldUse24HourClock() {
#if defined(OS_CHROMEOS)
Profile* profile = ProfileManager::GetDefaultProfileOrOffTheRecord();
if (profile) {
PrefService* pref_service = profile->GetPrefs();
if (pref_service) {
return pref_service->GetBoolean(prefs::kUse24HourClock);
}
}
#endif
return base::GetHourClockType() == base::k24HourClock;
}
std::string GetScreenshotFileName(bool use_24hour_clock) {
base::Time::Exploded now;
base::Time::Now().LocalExplode(&now);
// We don't use base/i18n/time_formatting.h here because it doesn't
// support our format. Don't use ICU either to avoid i18n file names
// for non-English locales.
// TODO(mukai): integrate this logic somewhere time_formatting.h
std::string file_name = base::StringPrintf(
"Screenshot %d-%02d-%02d ", now.year, now.month, now.day_of_month);
if (use_24hour_clock) {
file_name.append(base::StringPrintf(
"%02d:%02d:%02d.png", now.hour, now.minute, now.second));
} else {
int hour = now.hour;
if (hour > 12) {
hour -= 12;
} else if (hour == 0) {
hour = 12;
}
file_name.append(base::StringPrintf(
"%d:%02d:%02d ", hour, now.minute, now.second));
file_name.append((now.hour >= 12) ? "PM" : "AM");
file_name.append(".png");
}
return file_name;
}
// |is_logged_in| is used only for ChromeOS. Otherwise it is always true.
void SaveScreenshot(bool is_logged_in,
bool use_24hour_clock,
scoped_refptr<base::RefCountedBytes> png_data) {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::FILE));
std::string screenshot_filename = GetScreenshotFileName(use_24hour_clock);
FilePath screenshot_path;
if (is_logged_in) {
screenshot_path = download_util::GetDefaultDownloadDirectory().AppendASCII(
screenshot_filename);
} else {
file_util::CreateTemporaryFile(&screenshot_path);
}
if (static_cast<size_t>(file_util::WriteFile(
screenshot_path,
reinterpret_cast<char*>(&(png_data->data()[0])),
png_data->size())) == png_data->size()) {
if (!is_logged_in) {
// We created a temporary file without .png suffix. Rename it
// here.
FilePath real_path = screenshot_path.DirName().AppendASCII(
screenshot_filename);
if (!file_util::ReplaceFile(screenshot_path, real_path)) {
LOG(ERROR) << "Failed to rename the file to " << real_path.value();
}
}
} else {
LOG(ERROR) << "Failed to save to " << screenshot_path.value();
}
}
// How opaque should the layer that we flash onscreen to provide visual
// feedback after the screenshot is taken be?
const float kVisualFeedbackLayerOpacity = 0.25f;
// How long should the visual feedback layer be displayed?
const int64 kVisualFeedbackLayerDisplayTimeMs = 100;
} // namespace
ScreenshotTaker::ScreenshotTaker() {
}
ScreenshotTaker::~ScreenshotTaker() {
}
void ScreenshotTaker::HandleTakePartialScreenshot(
aura::Window* window, const gfx::Rect& rect) {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
scoped_refptr<base::RefCountedBytes> png_data(new base::RefCountedBytes);
bool is_logged_in = true;
#if defined(OS_CHROMEOS)
is_logged_in = chromeos::UserManager::Get()->IsUserLoggedIn();
#endif
bool use_24hour_clock = ShouldUse24HourClock();
if (browser::GrabWindowSnapshot(window, &png_data->data(), rect)) {
DisplayVisualFeedback(rect);
content::BrowserThread::PostTask(
content::BrowserThread::FILE, FROM_HERE,
base::Bind(&SaveScreenshot, is_logged_in, use_24hour_clock, png_data));
} else {
LOG(ERROR) << "Failed to grab the window screenshot";
}
}
void ScreenshotTaker::HandleTakeScreenshot(aura::Window* window) {
HandleTakePartialScreenshot(window, window->bounds());
}
void ScreenshotTaker::CloseVisualFeedbackLayer() {
visual_feedback_layer_.reset();
}
void ScreenshotTaker::DisplayVisualFeedback(const gfx::Rect& rect) {
visual_feedback_layer_.reset(new ui::Layer(ui::LAYER_SOLID_COLOR));
visual_feedback_layer_->SetColor(SK_ColorWHITE);
visual_feedback_layer_->SetOpacity(kVisualFeedbackLayerOpacity);
visual_feedback_layer_->SetBounds(rect);
ui::Layer* parent = ash::Shell::GetInstance()->GetContainer(
ash::internal::kShellWindowId_OverlayContainer)->layer();
parent->Add(visual_feedback_layer_.get());
visual_feedback_layer_->SetVisible(true);
MessageLoopForUI::current()->PostDelayedTask(
FROM_HERE,
base::Bind(&ScreenshotTaker::CloseVisualFeedbackLayer,
base::Unretained(this)),
base::TimeDelta::FromMilliseconds(kVisualFeedbackLayerDisplayTimeMs));
}
|
#include <QMessageBox>
#include "LXcpCanTrans.h"
// Static class data
const QString LXcpCanTrans::s_strProtocolName = "XcpCan";
const QString LXcpCanTrans::s_strSwVersion = "1.0";
LXcpCanTrans::LXcpCanTrans()
{
m_bIsDeviceReady = false;
m_pCanDataManager = nullptr;
m_pDataProc = new LDataProcessing(m_mapAllData, m_mutex);
m_pDataProcThread = new QThread;
/// \note This will move ALL the slots of LDataProcessing processed in the sub-thread
#if 0
m_pDataProc->moveToThread(m_pDataProcThread);
#endif
m_pSettingsWidget = new LXcpCanSettingsWidget;
m_pToolWidget = new LXcpCanToolWidget;
m_pSettingsRelier = new LXcpCanSettingsRelier(m_mapAllData, m_pToolWidget->getElfVarEditorWidget());
m_pToolWidget->getElfVarEditorWidget()->setDataMap(&m_mapAllData);
connect(m_pSettingsWidget, &LXcpCanSettingsWidget::sendDeviceReady, this, &LXcpCanTrans::receiveDeviceReady);
connect(m_pSettingsWidget, &LXcpCanSettingsWidget::sendDeviceReady, m_pDataProc, &LDataProcessing::receiveDeviceReady);
connect(m_pToolWidget->getElfVarEditorWidget(), &LElfVarEditorWidget::applyAllData, m_pDataProc, &LDataProcessing::applyAllData);
connect(m_pDataProc, &LDataProcessing::sendSingleVar, this, &LXcpCanTrans::receiveSingleVar);
connect(m_pToolWidget->getElfVarEditorWidget(), &LElfVarEditorWidget::saveSettings, m_pSettingsRelier, &LXcpCanSettingsRelier::saveSettings);
#if 0
// Start data processing thread
m_pDataProcThread->start();
#endif
}
LXcpCanTrans::~LXcpCanTrans()
{
// Make sure the thread quits
m_pDataProcThread->quit();
m_pDataProcThread->wait();
// we only need delete this map, other LEvoxVarData* containers all point to memory managed by this one
qDeleteAll(m_mapAllData);
m_mapAllData.clear();
m_pDataProc->deleteLater();
if(m_pSettingsWidget != NULL) {
delete m_pSettingsWidget, m_pSettingsWidget = NULL;
}
if(m_pSettingsRelier != NULL) {
delete m_pSettingsRelier, m_pSettingsRelier = NULL;
}
if (m_pToolWidget != NULL) {
delete m_pToolWidget, m_pToolWidget = NULL;
}
}
void LXcpCanTrans::configurate(const LObixObjIter &a_rConfigIter)
{
// Parse the configuration file and add points
m_bErrorFlag = false;
parseConfigTree(a_rConfigIter);
m_pDataProc->setCanMsgId(m_iSlaveRxCanId, m_iSlaveTxCanId);
}
bool LXcpCanTrans::getDataList(LDataNameList &a_rDataNameList) const
{
if(m_bErrorFlag) {
return false;
}
else {
a_rDataNameList = m_mapAllData.keys();
return true;
}
}
void LXcpCanTrans::resetCaredDataList(const LDataNameList &a_rCaredDataNameList)
{
// clear the old list
m_mapCaredData.clear();
// build a new one
LDataNameListIter i(a_rCaredDataNameList);
QString strName;
while (i.hasNext()) {
strName = i.next();
if(m_mapAllData.contains(strName)) {
m_mapCaredData[strName] = m_mapAllData[strName];
}
}
}
void LXcpCanTrans::start()
{
m_pDataProc->startProcessing(true);
}
void LXcpCanTrans::stop()
{
m_pDataProc->startProcessing(false);
}
void LXcpCanTrans::setChannelPrefix(const QString &a_rPrefix)
{
m_strPrefix = a_rPrefix;
}
const QString &LXcpCanTrans::getProtocolName() const
{
return s_strProtocolName;
}
const QString &LXcpCanTrans::getSwVersion() const
{
return s_strSwVersion;
}
QWidget *LXcpCanTrans::getSettingsWidget()
{
return m_pSettingsWidget;
}
LSettingsRelier *LXcpCanTrans::getSettingsRelier()
{
return m_pSettingsRelier;
}
QWidget *LXcpCanTrans::getToolWidget()
{
return m_pToolWidget;
}
void LXcpCanTrans::setDataValue(QString a_strDataName, LDataValue a_dataValue)
{
// remove prefix
QString strNameWithoutPrefix = a_strDataName.right(a_strDataName.length()-1-m_strPrefix.length());
m_pDataProc->setValueCmd(strNameWithoutPrefix, a_dataValue.getValue());
}
void LXcpCanTrans::setUniqueResource(const LUniqueResource &a_rUniqueResource)
{
m_pCanDataManager = a_rUniqueResource.pUsbCan;
m_pSettingsWidget->setCanDataManager(m_pCanDataManager);
m_pDataProc->setCanDataManager(m_pCanDataManager);
}
void LXcpCanTrans::pullAttributes()
{
// Nothing
}
void LXcpCanTrans::pullDataValue(QString a_strDataName)
{
// remove prefix
QString strNameWithoutPrefix = a_strDataName.right(a_strDataName.length()-1-m_strPrefix.length());
m_pDataProc->pullValueCmd(strNameWithoutPrefix);
}
void LXcpCanTrans::receiveSingleVar(QString a_strDataName, LDataValue a_dataValue)
{
LDataValueList valueList;
valueList.append(a_dataValue);
emit notifySingleVar(m_strPrefix+"_"+a_strDataName, valueList);
}
void LXcpCanTrans::parseConfigTree(const LObixObjIter &a_rConfigIter)
{
LObixObjIter configIter = a_rConfigIter;
if ((configIter.getValue().getType() == eObj) && (configIter.getValue().getProperty("is") == "XcpCan Plugin Config")) {
configIter.moveToFirstChild();
}
else {
m_bErrorFlag = true;
return;
}
if ((configIter.getValue().getType() == eInt) && (configIter.getValue().getProperty("name") == "Slave Receive CAN ID")) {
m_iSlaveRxCanId = configIter.getValue().getProperty("val").toInt(nullptr, 16);
}
else {
m_bErrorFlag = true;
return;
}
configIter.moveToNextSibling();
if ((configIter.getValue().getType() == eInt) && (configIter.getValue().getProperty("name") == "Slave Transmit CAN ID")) {
m_iSlaveTxCanId = configIter.getValue().getProperty("val").toInt(nullptr, 16);
}
else {
m_bErrorFlag = true;
return;
}
}
void LXcpCanTrans::receiveDeviceReady(bool isConnected, unsigned long deviceIndex, unsigned long canIndex, unsigned long devType)
{
m_bIsDeviceReady = isConnected;
}
|
// Generated file (from: topk_v2_1D_quant8.mod.py). Do not edit
void CreateModel(Model *model) {
OperandType type1(Type::INT32, {});
OperandType type3(Type::TENSOR_INT32, {2});
OperandType type2(Type::TENSOR_QUANT8_ASYMM, {2}, 0.5f, 1);
OperandType type0(Type::TENSOR_QUANT8_ASYMM, {4}, 0.5f, 1);
// Phase 1, operands
auto op1 = model->addOperand(&type0);
auto k = model->addOperand(&type1);
auto op2 = model->addOperand(&type2);
auto op3 = model->addOperand(&type3);
// Phase 2, operations
static int32_t k_init[] = {2};
model->setOperandValue(k, k_init, sizeof(int32_t) * 1);
model->addOperationEx(ANEURALNETWORKS_TOPK_V2_EX, {op1, k}, {op2, op3});
// Phase 3, inputs and outputs
model->identifyInputsAndOutputs(
{op1},
{op2, op3});
assert(model->isValid());
}
bool is_ignored(int i) {
static std::set<int> ignore = {};
return ignore.find(i) != ignore.end();
}
|
#include "image_queue.h"
#include <ros/ros.h>
#include <sensor_msgs/Image.h>
// Bring in gtest
#include <gtest/gtest.h>
class ImageQueueFixture : public ::testing::Test
{
protected:
sensor_msgs::ImageConstPtr imgA;
sensor_msgs::ImageConstPtr imgB;
optic_flow::ImageQueue iq;
ImageQueueFixture():
iq{5,3}
{
imgA = sensor_msgs::ImageConstPtr{new sensor_msgs::Image{}};
imgB = sensor_msgs::ImageConstPtr{new sensor_msgs::Image{}};
}
};
TEST_F(ImageQueueFixture, ConstructorTest)
{
try
{
optic_flow::ImageQueue inv{0, 0};
FAIL();
}
catch (const std::invalid_argument& ia) {}
try
{
optic_flow::ImageQueue inv{1, 0};
FAIL();
}
catch (const std::invalid_argument& ia) {}
try
{
optic_flow::ImageQueue inv{0, 1};
FAIL();
}
catch (const std::invalid_argument& ia) {}
}
TEST_F(ImageQueueFixture, PopEmptyTest)
{
try
{
ASSERT_EQ(iq.size(),0);
iq.popFrame();
FAIL();
}
catch (const std::runtime_error& ia) {}
iq.pushFrame(imgA);
ASSERT_EQ(iq.size(), 1);
auto out = iq.popFrame();
ASSERT_EQ(out, imgA);
ASSERT_EQ(iq.size(), 0);
}
TEST_F(ImageQueueFixture, AutoPopTest)
{
ASSERT_NE(imgA, imgB);
for (int i = 0; i < 5; i++)
{
if (i % 2)
iq.pushFrame(imgA);
else
iq.pushFrame(imgB);
}
ASSERT_EQ(iq.size(), 5);
auto front = iq.popFrame();
ASSERT_EQ(front, imgB);
ASSERT_EQ(iq.size(), 4);
iq.pushFrame(imgA);
iq.pushFrame(imgB);
ASSERT_EQ(iq.size(), 6);
front = iq.popFrame();
ASSERT_EQ(front, imgB);
ASSERT_EQ(iq.size(), 4);
iq.pushFrame(imgA);
iq.pushFrame(imgB);
iq.pushFrame(imgA);
iq.pushFrame(imgB);
iq.pushFrame(imgA);
ASSERT_EQ(iq.size(), 9);
front = iq.popFrame();
ASSERT_EQ(front, imgB);
ASSERT_EQ(iq.size(), 5);
}
// Run all the tests that were declared with TEST()
int main(int argc, char **argv){
testing::InitGoogleTest(&argc, argv);
ros::init(argc, argv, "tester");
ros::NodeHandle nh;
return RUN_ALL_TESTS();
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file mkldnn_concat.cc
* \brief
* \author
*/
#if MXNET_USE_ONEDNN == 1
#include "mkldnn_concat-inl.h"
namespace mxnet {
namespace op {
static inline bool IsUsingPadding(const mkldnn::memory::desc &dst_md) {
// make sure a blocked format is used (at least one dimension is blocked)
bool is_blocked_format = dst_md.data.format_kind == mkldnn_blocked &&
dst_md.data.format_desc.blocking.inner_nblks > 0;
return is_blocked_format && !std::equal(dst_md.data.dims, dst_md.data.dims + dst_md.data.ndims,
dst_md.data.padded_dims);
}
MKLDNNConcatFwd::MKLDNNConcatFwd(int concat_dim, const std::vector<mkldnn::memory::desc> &data_md)
: fwd_pd(concat_dim, data_md, CpuEngine::Get()->get_engine()) {
// MKL-DNN introduced padded formats since 0.15 which require more memory
// compared to the actual size of the tensor. Currently, MKL-DNN operators
// still reuse memory from memory planning, so here we need to select a
// format that has the expected memory size requirements (a plain format)
// When fwd_pd uses padding, impose a plain format
const auto &dst_md = fwd_pd.dst_desc();
if (IsUsingPadding(dst_md)) {
auto plain_dst_tag = static_cast<mkldnn::memory::format_tag>(
GetDefaultFormat(dst_md.data.ndims));
auto plain_dst_md = mkldnn::memory::desc(dst_md.dims(), dst_md.data_type(), plain_dst_tag);
fwd_pd = mkldnn::concat::primitive_desc(plain_dst_md, concat_dim, data_md,
CpuEngine::Get()->get_engine());
}
fwd_ = std::make_shared<mkldnn::concat>(fwd_pd);
}
void MKLDNNConcatForward(const nnvm::NodeAttrs& attrs, const OpContext &ctx,
const std::vector<NDArray> &in_data,
const std::vector<OpReqType> &req,
const std::vector<NDArray> &out_data) {
TmpMemMgr::Get()->Init(ctx.requested[concat_enum::kTempSpace]);
const ConcatParam& param = nnvm::get<ConcatParam>(attrs.parsed);
const int num_in_data = param.num_args;
const int concat_dim = param.dim;
std::vector<mkldnn::memory::desc> data_md;
std::vector<const mkldnn::memory *> data_mem;
data_md.reserve(num_in_data);
data_mem.reserve(num_in_data);
for (int i = 0; i < num_in_data; i++) {
const mkldnn::memory *tmp_mem = in_data[i].GetMKLDNNData();
mkldnn::memory::desc tmp_md = tmp_mem->get_desc();
data_md.push_back(tmp_md);
data_mem.push_back(tmp_mem);
}
MKLDNNConcatFwd &fwd = GetConcatForward(concat_dim, in_data, data_md);
mxnet::mkldnn_output_t out_mem = CreateMKLDNNMem(out_data[concat_enum::kOut],
fwd.fwd_pd.dst_desc(),
req[concat_enum::kOut]);
std::unordered_map<int, mkldnn::memory> net_args;
net_args.insert({MKLDNN_ARG_DST, *out_mem.second});
for (int i = 0; i < num_in_data; i++) {
net_args.insert({MKLDNN_ARG_MULTIPLE_SRC + i, *data_mem[i]});
}
MKLDNNStream::Get()->RegisterPrimArgs(fwd.GetFwd(), net_args);
CommitOutput(out_data[concat_enum::kOut], out_mem);
MKLDNNStream::Get()->Submit();
}
void MKLDNNConcatBackward(const nnvm::NodeAttrs& attrs, const OpContext &ctx,
const std::vector<NDArray>& inputs,
const std::vector<OpReqType>& req,
const std::vector<NDArray>& outputs) {
TmpMemMgr::Get()->Init(ctx.requested[concat_enum::kTempSpace]);
const ConcatParam& param = nnvm::get<ConcatParam>(attrs.parsed);
const int num_in_data = param.num_args;
const int axis = param.dim;
const auto gradz_mem = inputs[0].GetMKLDNNData();
/* init the offset */
mkldnn::memory::dims offsets(outputs[0].shape().ndim());
for (auto &v : offsets) {
v = 0;
}
for (int i = 0; i < num_in_data; i++) {
mkldnn::memory::dims diff_src_tz(outputs[i].shape().begin(), outputs[i].shape().end());
auto diff_src_md = outputs[i].GetMKLDNNData()->get_desc();
auto gradi_mem = CreateMKLDNNMem(outputs[i], diff_src_md, req[i]);
auto from_md = gradz_mem->get_desc().submemory_desc(diff_src_tz, offsets);
auto from_mem = new mkldnn::memory(from_md, gradz_mem->get_engine(),
gradz_mem->get_data_handle());
offsets[axis] += diff_src_tz[axis];
std::unordered_map<int, mkldnn::memory> net_args({
{MKLDNN_ARG_FROM, *gradz_mem},
{MKLDNN_ARG_TO, *gradi_mem.second}
});
MKLDNNStream::Get()->RegisterPrimArgs(mkldnn::reorder(*from_mem, *gradi_mem.second), net_args);
CommitOutput(outputs[i], gradi_mem);
}
MKLDNNStream::Get()->Submit();
}
} // namespace op
} // namespace mxnet
#endif // MXNET_USE_ONEDNN == 1
|
#pragma once
#include "../../types.hpp"
#include "simultaneous_options.hpp"
#include <pqrs/json.hpp>
#include <set>
#include <vector>
namespace krbn {
namespace manipulator {
namespace manipulators {
namespace basic {
class from_event_definition final {
public:
from_event_definition(void) {
}
virtual ~from_event_definition(void) {
}
const std::vector<event_definition>& get_event_definitions(void) const {
return event_definitions_;
}
void set_event_definitions(const std::vector<event_definition>& value) {
event_definitions_ = value;
}
const from_modifiers_definition& get_from_modifiers_definition(void) const {
return from_modifiers_definition_;
}
void set_from_modifiers_definition(const from_modifiers_definition& value) {
from_modifiers_definition_ = value;
}
const simultaneous_options& get_simultaneous_options(void) const {
return simultaneous_options_;
}
void set_simultaneous_options(const simultaneous_options& value) {
simultaneous_options_ = value;
}
static bool test_event(const event_queue::event& event,
const event_definition& event_definition) {
if (auto key_code = event.get_key_code()) {
if (event_definition.get_key_code() == key_code ||
event_definition.get_any_type() == event_definition::type::key_code) {
return true;
}
}
if (auto consumer_key_code = event.get_consumer_key_code()) {
if (event_definition.get_consumer_key_code() == consumer_key_code ||
event_definition.get_any_type() == event_definition::type::consumer_key_code) {
return true;
}
}
if (auto pointing_button = event.get_pointing_button()) {
if (event_definition.get_pointing_button() == pointing_button ||
event_definition.get_any_type() == event_definition::type::pointing_button) {
return true;
}
}
return false;
}
static bool test_event(const event_queue::event& event,
const from_event_definition& from_event_definition) {
for (const auto& d : from_event_definition.get_event_definitions()) {
if (test_event(event, d)) {
return true;
}
}
return false;
}
static bool test_key_order(const std::vector<event_queue::event>& events,
simultaneous_options::key_order key_order,
const std::vector<event_definition>& event_definitions) {
switch (key_order) {
case simultaneous_options::key_order::insensitive:
// Do nothing
break;
case simultaneous_options::key_order::strict:
for (auto events_it = std::begin(events); events_it != std::end(events); std::advance(events_it, 1)) {
auto event_definitions_index = static_cast<size_t>(std::distance(std::begin(events), events_it));
if (event_definitions_index < event_definitions.size()) {
if (!test_event(*events_it, event_definitions[event_definitions_index])) {
return false;
}
}
}
break;
case simultaneous_options::key_order::strict_inverse:
for (auto events_it = std::begin(events); events_it != std::end(events); std::advance(events_it, 1)) {
auto event_definitions_index = static_cast<size_t>(std::distance(std::begin(events), events_it));
if (event_definitions_index < event_definitions.size()) {
if (!test_event(*events_it, event_definitions[event_definitions.size() - 1 - event_definitions_index])) {
return false;
}
}
}
break;
}
return true;
}
private:
std::vector<event_definition> event_definitions_;
from_modifiers_definition from_modifiers_definition_;
simultaneous_options simultaneous_options_;
};
inline void from_json(const nlohmann::json& json, from_event_definition& d) {
if (!json.is_object()) {
throw pqrs::json::unmarshal_error(fmt::format("json must be object, but is `{0}`", json.dump()));
}
std::vector<event_definition> event_definitions;
event_definition default_event_definition;
for (const auto& [key, value] : json.items()) {
// key is always std::string.
if (default_event_definition.handle_json(key, value, json)) {
// Do nothing
} else if (key == "modifiers") {
try {
d.set_from_modifiers_definition(value.get<from_modifiers_definition>());
} catch (const pqrs::json::unmarshal_error& e) {
throw pqrs::json::unmarshal_error(fmt::format("`{0}` error: {1}", key, e.what()));
}
} else if (key == "simultaneous") {
if (!value.is_array()) {
throw pqrs::json::unmarshal_error(fmt::format("`{0}` must be array, but is `{1}`", key, value.dump()));
}
for (const auto& j : value) {
if (!j.is_object()) {
throw pqrs::json::unmarshal_error(fmt::format("`{0}` entry must be object, but is `{1}`", key, j.dump()));
}
event_definition d;
for (const auto& [k, v] : j.items()) {
// k is always std::string.
if (d.handle_json(k, v, j)) {
// Do nothing
} else {
throw pqrs::json::unmarshal_error(fmt::format("unknown key: `{0}` in `{1}", k, j.dump()));
}
}
if (d.get_type() == event_definition::type::none) {
throw pqrs::json::unmarshal_error(fmt::format("event type is invalid: `{0}`", json.dump()));
}
event_definitions.push_back(d);
}
} else if (key == "simultaneous_options") {
try {
d.set_simultaneous_options(value.get<simultaneous_options>());
} catch (const pqrs::json::unmarshal_error& e) {
throw pqrs::json::unmarshal_error(fmt::format("`{0}` error: {1}", key, e.what()));
}
} else {
throw pqrs::json::unmarshal_error(fmt::format("`from` error: unknown key `{0}` in `{1}`", key, json.dump()));
}
}
if (event_definitions.empty() &&
default_event_definition.get_type() != event_definition::type::none) {
event_definitions.push_back(default_event_definition);
}
// ----------------------------------------
if (event_definitions.empty()) {
throw pqrs::json::unmarshal_error(fmt::format("event is not specified: `{0}`", json.dump()));
}
for (const auto& d : event_definitions) {
switch (d.get_type()) {
case event_definition::type::key_code:
case event_definition::type::consumer_key_code:
case event_definition::type::pointing_button:
case event_definition::type::any:
break;
case event_definition::type::none:
case event_definition::type::shell_command:
case event_definition::type::select_input_source:
case event_definition::type::set_variable:
case event_definition::type::mouse_key:
throw pqrs::json::unmarshal_error(fmt::format("event type is invalid: `{0}`", json.dump()));
}
}
d.set_event_definitions(event_definitions);
}
} // namespace basic
} // namespace manipulators
} // namespace manipulator
} // namespace krbn
|
///////////////////////////////////////////////////////////////////////////////////
/// OpenGL Mathematics (glm.g-truc.net)
///
/// Copyright (c) 2005 - 2013 G-Truc Creation (www.g-truc.net)
/// 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.
///
/// @ref core
/// @file glm/core/intrinsic_geometric.hpp
/// @date 2009-05-08 / 2011-06-15
/// @author Christophe Riccio
///////////////////////////////////////////////////////////////////////////////////
#ifndef glm_core_intrinsic_geometric
#define glm_core_intrinsic_geometric
#include "setup.hpp"
#if(!(GLM_ARCH & GLM_ARCH_SSE2))
# error "SSE2 instructions not supported or enabled"
#else
#include "intrinsic_common.hpp"
namespace glm{
namespace detail
{
//length
__m128 sse_len_ps(__m128 x);
//distance
__m128 sse_dst_ps(__m128 p0, __m128 p1);
//dot
__m128 sse_dot_ps(__m128 v1, __m128 v2);
// SSE1
__m128 sse_dot_ss(__m128 v1, __m128 v2);
//cross
__m128 sse_xpd_ps(__m128 v1, __m128 v2);
//normalize
__m128 sse_nrm_ps(__m128 v);
//faceforward
__m128 sse_ffd_ps(__m128 N, __m128 I, __m128 Nref);
//reflect
__m128 sse_rfe_ps(__m128 I, __m128 N);
//refract
__m128 sse_rfa_ps(__m128 I, __m128 N, __m128 eta);
}//namespace detail
}//namespace glm
#include "intrinsic_geometric.inl"
#endif//GLM_ARCH
#endif//glm_core_intrinsic_geometric
|
/* ----------------------------------------------------------------------------
* 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 timeVirtual.cpp
* @brief Time the overhead of using virtual destructors and methods
* @author Richard Roberts
* @date Dec 3, 2010
*/
#include <gtsam/slam/dataset.h>
#include <gtsam/slam/PriorFactor.h>
#include <gtsam/slam/lago.h>
#include <gtsam/nonlinear/GaussNewtonOptimizer.h>
#include <gtsam/linear/Sampler.h>
#include <gtsam/base/timing.h>
#include <iostream>
using namespace std;
using namespace gtsam;
int main(int argc, char *argv[]) {
size_t trials = 1;
// read graph
Values::shared_ptr solution;
NonlinearFactorGraph::shared_ptr g;
string inputFile = findExampleDataFile("w10000");
SharedDiagonal model = noiseModel::Diagonal::Sigmas((Vector(3) << 0.05, 0.05, 5.0 * M_PI / 180.0));
boost::tie(g, solution) = load2D(inputFile, model);
// add noise to create initial estimate
Values initial;
Sampler sampler(42u);
Values::ConstFiltered<Pose2> poses = solution->filter<Pose2>();
SharedDiagonal noise = noiseModel::Diagonal::Sigmas((Vector(3) << 0.5, 0.5, 15.0 * M_PI / 180.0));
BOOST_FOREACH(const Values::ConstFiltered<Pose2>::KeyValuePair& it, poses)
initial.insert(it.key, it.value.retract(sampler.sampleNewModel(noise)));
// Add prior on the pose having index (key) = 0
noiseModel::Diagonal::shared_ptr priorModel = //
noiseModel::Diagonal::Sigmas(Vector3(1e-6, 1e-6, 1e-8));
g->add(PriorFactor<Pose2>(0, Pose2(), priorModel));
// LAGO
for (size_t i = 0; i < trials; i++) {
{
gttic_(lago);
gttic_(init);
Values lagoInitial = lago::initialize(*g);
gttoc_(init);
gttic_(refine);
GaussNewtonOptimizer optimizer(*g, lagoInitial);
Values result = optimizer.optimize();
gttoc_(refine);
}
{
gttic_(optimize);
GaussNewtonOptimizer optimizer(*g, initial);
Values result = optimizer.optimize();
}
tictoc_finishedIteration_();
}
tictoc_print_();
return 0;
}
|
#pragma once
#include "types.hpp"
#include "utils.hpp"
#include <memory>
#include <sdbusplus/bus.hpp>
#include <utility>
namespace phosphor
{
namespace inventory
{
namespace manager
{
class Manager;
/** @brief make_action
*
* Adapt an action function object.
*
* @param[in] action - The action being adapted.
* @returns - The adapted action.
*
* @tparam T - The type of the action being adapted.
*/
template <typename T>
auto make_action(T&& action)
{
return Action(std::forward<T>(action));
}
/** @brief make_filter
*
* Adapt a filter function object.
*
* @param[in] filter - The filter being adapted.
* @returns - The adapted filter.
*
* @tparam T - The type of the filter being adapted.
*/
template <typename T>
auto make_filter(T&& filter)
{
return Filter(std::forward<T>(filter));
}
/** @brief make_path_condition
*
* Adapt a path_condition function object.
*
* @param[in] filter - The functor being adapted.
* @returns - The adapted functor.
*
* @tparam T - The type of the functor being adapted.
*/
template <typename T>
auto make_path_condition(T&& condition)
{
return PathCondition(std::forward<T>(condition));
}
/** @brief make_get_property
*
* Adapt a get_property function object.
*
* @param[in] method - The functor being adapted.
* @returns - The adapted functor.
*
* @tparam T - The return type of the function object.
* @tparam U - The type of the functor being adapted.
*/
template <typename T, typename U>
auto make_get_property(U&& method)
{
return GetProperty<T>(std::forward<U>(method));
}
template <typename T, typename... Args>
auto callArrayWithStatus(T&& container, Args&&... args)
{
for (auto f : container)
{
if (!f(std::forward<Args>(args)...))
{
return false;
}
}
return true;
}
namespace functor
{
/** @brief Destroy objects action. */
inline auto destroyObjects(std::vector<const char*>&& paths,
std::vector<PathCondition>&& conditions)
{
return [=](auto& b, auto& m) {
for (const auto& p : paths)
{
if (callArrayWithStatus(conditions, p, b, m))
{
m.destroyObjects({p});
}
}
};
}
/** @brief Create objects action. */
inline auto
createObjects(std::map<sdbusplus::message::object_path, Object>&& objs)
{
return [=](auto&, auto& m) { m.createObjects(objs); };
}
/** @brief Set a property action.
*
* Invoke the requested method with a reference to the requested
* sdbusplus server binding interface as a parameter.
*
* @tparam T - The sdbusplus server binding interface type.
* @tparam U - The type of the sdbusplus server binding member
* function that sets the property.
* @tparam V - The property value type.
*
* @param[in] paths - The DBus paths on which the property should
* be set.
* @param[in] iface - The DBus interface hosting the property.
* @param[in] member - Pointer to sdbusplus server binding member.
* @param[in] value - The value the property should be set to.
*
* @returns - A function object that sets the requested property
* to the requested value.
*/
template <typename T, typename U, typename V>
auto setProperty(std::vector<const char*>&& paths,
std::vector<PathCondition>&& conditions, const char* iface,
U&& member, V&& value)
{
// The manager is the only parameter passed to actions.
// Bind the path, interface, interface member function pointer,
// and value to a lambda. When it is called, forward the
// path, interface and value on to the manager member function.
return [paths, conditions = conditions, iface, member,
value = std::forward<V>(value)](auto& b, auto& m) {
for (auto p : paths)
{
if (callArrayWithStatus(conditions, p, b, m))
{
m.template invokeMethod<T>(p, iface, member, value);
}
}
};
}
/** @brief Get a property.
*
* Invoke the requested method with a reference to the requested
* sdbusplus server binding interface as a parameter.
*
* @tparam T - The sdbusplus server binding interface type.
* @tparam U - The type of the sdbusplus server binding member
* function that sets the property.
*
* @param[in] path - The DBus path to get the property from.
* @param[in] iface - The DBus interface hosting the property.
* @param[in] member - Pointer to sdbusplus server binding member.
* @param[in] prop - The property name to get the value from.
*
* @returns - A function object that gets the requested property.
*/
template <typename T, typename U>
inline auto getProperty(const char* path, const char* iface, U&& member,
const char* prop)
{
return [path, iface, member, prop](auto& mgr) {
return mgr.template invokeMethod<T>(path, iface, member, prop);
};
}
/** @struct PropertyChangedCondition
* @brief Match filter functor that tests a property value.
*
* @tparam T - The type of the property being tested.
* @tparam U - The type of the condition checking functor.
*/
template <typename T, typename U>
struct PropertyChangedCondition
{
PropertyChangedCondition() = delete;
~PropertyChangedCondition() = default;
PropertyChangedCondition(const PropertyChangedCondition&) = default;
PropertyChangedCondition&
operator=(const PropertyChangedCondition&) = default;
PropertyChangedCondition(PropertyChangedCondition&&) = default;
PropertyChangedCondition& operator=(PropertyChangedCondition&&) = default;
PropertyChangedCondition(const char* iface, const char* property,
U&& condition) :
_iface(iface),
_property(property), _condition(std::forward<U>(condition))
{
}
/** @brief Test a property value.
*
* Extract the property from the PropertiesChanged
* message and run the condition test.
*/
bool operator()(sdbusplus::bus::bus&, sdbusplus::message::message& msg,
Manager&) const
{
std::map<std::string, sdbusplus::message::variant<T>> properties;
const char* iface = nullptr;
msg.read(iface);
if (!iface || strcmp(iface, _iface))
{
return false;
}
msg.read(properties);
auto it = properties.find(_property);
if (it == properties.cend())
{
return false;
}
return _condition(std::forward<T>(it->second.template get<T>()));
}
private:
const char* _iface;
const char* _property;
U _condition;
};
/** @struct PropertyConditionBase
* @brief Match filter functor that tests a property value.
*
* Base class for PropertyCondition - factored out code that
* doesn't need to be templated.
*/
struct PropertyConditionBase
{
PropertyConditionBase() = delete;
virtual ~PropertyConditionBase() = default;
PropertyConditionBase(const PropertyConditionBase&) = default;
PropertyConditionBase& operator=(const PropertyConditionBase&) = default;
PropertyConditionBase(PropertyConditionBase&&) = default;
PropertyConditionBase& operator=(PropertyConditionBase&&) = default;
/** @brief Constructor
*
* The service argument can be nullptr. If something
* else is provided the function will call the the
* service directly. If omitted, the function will
* look up the service in the ObjectMapper.
*
* @param path - The path of the object containing
* the property to be tested.
* @param iface - The interface hosting the property
* to be tested.
* @param property - The property to be tested.
* @param service - The DBus service hosting the object.
*/
PropertyConditionBase(const char* path, const char* iface,
const char* property, const char* service) :
_path(path ? path : std::string()),
_iface(iface), _property(property), _service(service)
{
}
/** @brief Forward comparison to type specific implementation. */
virtual bool eval(sdbusplus::message::message&) const = 0;
/** @brief Forward comparison to type specific implementation. */
virtual bool eval(Manager&) const = 0;
/** @brief Test a property value.
*
* Make a DBus call and test the value of any property.
*/
bool operator()(sdbusplus::bus::bus&, sdbusplus::message::message&,
Manager&) const;
/** @brief Test a property value.
*
* Make a DBus call and test the value of any property.
*/
bool operator()(const std::string&, sdbusplus::bus::bus&, Manager&) const;
private:
std::string _path;
std::string _iface;
std::string _property;
const char* _service;
};
/** @struct PropertyCondition
* @brief Match filter functor that tests a property value.
*
* @tparam T - The type of the property being tested.
* @tparam U - The type of the condition checking functor.
* @tparam V - The getProperty functor return type.
*/
template <typename T, typename U, typename V>
struct PropertyCondition final : public PropertyConditionBase
{
PropertyCondition() = delete;
~PropertyCondition() = default;
PropertyCondition(const PropertyCondition&) = default;
PropertyCondition& operator=(const PropertyCondition&) = default;
PropertyCondition(PropertyCondition&&) = default;
PropertyCondition& operator=(PropertyCondition&&) = default;
/** @brief Constructor
*
* The service & getProperty arguments can be nullptrs.
* If something else is provided the function will call the the
* service directly. If omitted, the function will
* look up the service in the ObjectMapper.
* The getProperty function will be called to retrieve a property
* value when given and the property is hosted by inventory manager.
* When not given, the condition will default to return that the
* condition failed and will not be executed.
*
* @param path - The path of the object containing
* the property to be tested.
* @param iface - The interface hosting the property
* to be tested.
* @param property - The property to be tested.
* @param condition - The test to run on the property.
* @param service - The DBus service hosting the object.
* @param getProperty - The function to get a property value
* for the condition.
*/
PropertyCondition(const char* path, const char* iface, const char* property,
U&& condition, const char* service,
GetProperty<V>&& getProperty = nullptr) :
PropertyConditionBase(path, iface, property, service),
_condition(std::forward<decltype(condition)>(condition)),
_getProperty(getProperty)
{
}
/** @brief Test a property value.
*
* Make a DBus call and test the value of any property.
*/
bool eval(sdbusplus::message::message& msg) const override
{
sdbusplus::message::variant<T> value;
msg.read(value);
return _condition(std::forward<T>(value.template get<T>()));
}
/** @brief Retrieve a property value from inventory and test it.
*
* Get a property from the inventory manager and test the value.
* Default to fail the test where no function is given to get the
* property from the inventory manager.
*/
bool eval(Manager& mgr) const override
{
if (_getProperty)
{
auto variant = _getProperty(mgr);
auto value = sdbusplus::message::variant_ns::get<T>(variant);
return _condition(std::forward<T>(value));
}
return false;
}
private:
U _condition;
GetProperty<V> _getProperty;
};
/** @brief Implicit type deduction for constructing PropertyChangedCondition. */
template <typename T>
auto propertyChangedTo(const char* iface, const char* property, T&& val)
{
auto condition = [val = std::forward<T>(val)](T&& arg) {
return arg == val;
};
using U = decltype(condition);
return PropertyChangedCondition<T, U>(iface, property,
std::move(condition));
}
/** @brief Implicit type deduction for constructing PropertyCondition. */
template <typename T, typename V = InterfaceVariantType>
auto propertyIs(const char* path, const char* iface, const char* property,
T&& val, const char* service = nullptr,
GetProperty<V>&& getProperty = nullptr)
{
auto condition = [val = std::forward<T>(val)](T&& arg) {
return arg == val;
};
using U = decltype(condition);
return PropertyCondition<T, U, V>(path, iface, property,
std::move(condition), service,
std::move(getProperty));
}
} // namespace functor
} // namespace manager
} // namespace inventory
} // namespace phosphor
// vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
|
//-----------------------------------------------
//
// This file is part of the Siv3D Engine.
//
// Copyright (c) 2008-2021 Ryo Suzuki
// Copyright (c) 2016-2021 OpenSiv3D Project
//
// Licensed under the MIT License.
//
//-----------------------------------------------
# pragma once
# include "String.hpp"
# include "Array.hpp"
# include "detail/FormatLiteral_impl.ipp"
namespace s3d
{
namespace detail
{
struct FormatHelper;
template <class ParseContext>
inline auto GetFormatTag(std::u32string& representation, ParseContext& ctx)
{
auto it = ctx.begin();
const auto itEnd = ctx.end();
while (it != itEnd && (*it != '}'))
{
representation.push_back(*it++);
}
return it;
}
}
[[nodiscard]]
inline constexpr detail::FormatHelper Fmt(const char32* s) noexcept;
[[nodiscard]]
inline constexpr detail::FormatHelper Fmt(StringView s) noexcept;
[[nodiscard]]
inline detail::FormatHelper Fmt(const String& s) noexcept;
[[nodiscard]]
inline detail::FormatHelper Fmt(const std::u32string& s) noexcept;
inline namespace Literals
{
inline namespace FormatLiterals
{
[[nodiscard]]
inline constexpr detail::FormatHelper operator ""_fmt(const char32* s, size_t length) noexcept;
}
}
}
# include "detail/FormatLiteral.ipp"
template <>
struct SIV3D_HIDDEN fmt::formatter<s3d::String, s3d::char32>
{
std::u32string tag;
auto parse(basic_format_parse_context<s3d::char32>& ctx)
{
return s3d::detail::GetFormatTag(tag, ctx);
}
template <class FormatContext>
auto format(const s3d::String& value, FormatContext& ctx)
{
const basic_string_view<s3d::char32> sv(value.data(), value.size());
if (tag.empty())
{
return format_to(ctx.out(), sv);
}
else
{
const std::u32string format = (U"{:" + tag + U'}');
return format_to(ctx.out(), format, sv);
}
}
};
template <>
struct SIV3D_HIDDEN fmt::formatter<s3d::StringView, s3d::char32>
{
std::u32string tag;
auto parse(basic_format_parse_context<s3d::char32>& ctx)
{
return s3d::detail::GetFormatTag(tag, ctx);
}
template <class FormatContext>
auto format(const s3d::StringView& value, FormatContext& ctx)
{
const basic_string_view<s3d::char32> sv(value.data(), value.size());
if (tag.empty())
{
return format_to(ctx.out(), sv);
}
else
{
const std::u32string format = (U"{:" + tag + U'}');
return format_to(ctx.out(), format, sv);
}
}
};
template <class Type, class Allocator>
struct SIV3D_HIDDEN fmt::formatter<s3d::Array<Type, Allocator>, s3d::char32>
{
std::u32string tag;
auto parse(basic_format_parse_context<s3d::char32>& ctx)
{
return s3d::detail::GetFormatTag(tag, ctx);
}
template <class FormatContext>
auto format(const s3d::Array<Type, Allocator>& value, FormatContext& ctx)
{
if (tag.empty())
{
const s3d::String s = s3d::Format(value).replace(U"{", U"{{").replace(U"}", U"}}");
const basic_string_view<s3d::char32> sv(s.data(), s.size());
return format_to(ctx.out(), sv);
}
else
{
const s3d::String format = U"{:" + tag + U'}';
const auto formatHelper = s3d::Fmt(format);
const s3d::String s = s3d::Format(value.map([&formatHelper](const auto& e) { return formatHelper(e); })).replace(U"{", U"{{").replace(U"}", U"}}");
const basic_string_view<s3d::char32> sv(s.data(), s.size());
return format_to(ctx.out(), sv);
}
}
};
|
// 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 "chrome/browser/extensions/api/record/record_api.h"
#include "base/bind.h"
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/memory/ref_counted.h"
#include "base/process_util.h"
#include "base/string_number_conversions.h"
#include "base/string_split.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/extensions/api/experimental_record.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/common/content_switches.h"
namespace extensions {
namespace record = api::experimental_record;
ProcessStrategy::~ProcessStrategy() {}
void ProductionProcessStrategy::RunProcess(const CommandLine& line,
std::vector<std::string>* errors) {
base::LaunchOptions options;
base::ProcessHandle handle;
base::LaunchProcess(line, options, &handle);
int exit_code = 0;
if (!base::WaitForExitCode(handle, &exit_code) || exit_code != 0)
errors->push_back("Test browser exited abnormally");
}
RunPageCyclerFunction::RunPageCyclerFunction(ProcessStrategy* strategy)
: repeat_count_(1), base_command_line_(*CommandLine::ForCurrentProcess()),
process_strategy_(strategy) {}
RunPageCyclerFunction::~RunPageCyclerFunction() {}
bool RunPageCyclerFunction::RunImpl() {
if (!ParseJSParameters())
return false;
// If we've had any errors reportable to the JS caller so far (in
// parameter parsing) then return a list of such errors, else perform
// RunTestBrowser on the BlockingPool.
if (!errors_.empty()) {
results_ = record::CaptureURLs::Results::Create(errors_);
SendResponse(true);
} else {
content::BrowserThread::PostBlockingPoolTask(FROM_HERE,
base::Bind(&RunPageCyclerFunction::RunTestBrowser, this));
process_strategy_->PumpBlockingPool(); // Test purposes only.
}
return true;
}
CommandLine RunPageCyclerFunction::RemoveSwitches(const CommandLine& original,
const std::vector<std::string>& to_remove) {
std::vector<const char*> to_keep;
const CommandLine::SwitchMap& current_switches = original.GetSwitches();
CommandLine filtered(original.GetProgram());
// Retain in |to_keep| all current swtiches *not* in |to_remove|.
for (CommandLine::SwitchMap::const_iterator itr = current_switches.begin();
itr != current_switches.end(); ++itr) {
if (std::find(to_remove.begin(), to_remove.end(), (*itr).first) ==
to_remove.end()) {
to_keep.push_back((*itr).first.c_str());
}
}
// Rely on std::vector keeping its contents in contiguous order.
// (This is documented STL spec.)
filtered.CopySwitchesFrom(original, &to_keep.front(), to_keep.size());
return filtered;
}
// Runs on BlockingPool thread. Invoked from UI thread and passes back to
// UI thread for |Final()| callback to JS side.
void RunPageCyclerFunction::RunTestBrowser() {
// Remove any current switch settings that would interfere with test browser
// commandline setup.
std::vector<std::string> remove_switches;
remove_switches.push_back(switches::kUserDataDir);
remove_switches.push_back(switches::kVisitURLs);
remove_switches.push_back(switches::kPlaybackMode);
remove_switches.push_back(switches::kRecordStats);
remove_switches.push_back(switches::kLoadExtension);
CommandLine line = RemoveSwitches(base_command_line_, remove_switches);
// Add the user-data-dir switch, since this is common to both call types.
line.AppendSwitchPath(switches::kUserDataDir, user_data_dir_);
// Test browsers must run as if they are not in first-run mode
line.AppendSwitch(switches::kNoFirstRun);
// Create and fill a temp file to communicate the URL list to the test
// browser.
FilePath url_path;
file_util::CreateTemporaryFile(&url_path);
file_util::WriteFile(url_path, url_contents_.c_str(), url_contents_.size());
line.AppendSwitchPath(switches::kVisitURLs, url_path);
// Set up Capture- or Replay-specific commandline switches.
AddSwitches(&line);
FilePath error_file_path = url_path.DirName().
Append(url_path.BaseName().value() +
FilePath::StringType(kURLErrorsSuffix));
LOG(ERROR) << "Test browser commandline: " << line.GetCommandLineString() <<
" will be repeated " << repeat_count_ << " times....";
// Run the test browser (or a mockup, depending on |process_strategy_|.
while (repeat_count_-- && errors_.empty() &&
!file_util::PathExists(error_file_path))
process_strategy_->RunProcess(line, &errors_);
// Read URL errors file if there is one, and save errors in |errors_|.
// Odd extension handling needed because temp files have lots of "."s in
// their names, and we need to cleanly add kURLErrorsSuffix as a final
// extension.
if (errors_.empty() && file_util::PathExists(error_file_path)) {
std::string error_content;
file_util::ReadFileToString(error_file_path, &error_content);
base::SplitString(error_content, '\n', &errors_);
}
// Do any special post-test-browser file reading (e.g. stats report))
// while we're on the BlockingPool thread.
ReadReplyFiles();
// Back to UI thread to finish up the JS call.
content::BrowserThread::PostTask(content::BrowserThread::UI, FROM_HERE,
base::Bind(&RunPageCyclerFunction::Finish, this));
}
const ProcessStrategy &RunPageCyclerFunction::GetProcessStrategy() {
return *process_strategy_;
}
// CaptureURLsFunction ------------------------------------------------
CaptureURLsFunction::CaptureURLsFunction()
: RunPageCyclerFunction(new ProductionProcessStrategy()) {}
CaptureURLsFunction::CaptureURLsFunction(ProcessStrategy* strategy)
: RunPageCyclerFunction(strategy) {}
// Fetch data for possible optional switch for an extension to load.
bool CaptureURLsFunction::ParseJSParameters() {
scoped_ptr<record::CaptureURLs::Params> params(
record::CaptureURLs::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get());
url_contents_ = JoinString(params->urls, '\n');
// TODO(cstaley): Can't just use captureName -- gotta stick it in a temp dir.
// TODO(cstaley): Ensure that capture name is suitable as directory name.
user_data_dir_ = FilePath::FromUTF8Unsafe(params->capture_name);
return true;
}
// CaptureURLsFunction adds "record-mode" to sub-browser call, and returns
// just the (possibly empty) error list.
void CaptureURLsFunction::AddSwitches(CommandLine* line) {
if (!line->HasSwitch(switches::kRecordMode))
line->AppendSwitch(switches::kRecordMode);
}
void CaptureURLsFunction::Finish() {
results_ = record::CaptureURLs::Results::Create(errors_);
SendResponse(true);
}
// ReplayURLsFunction ------------------------------------------------
ReplayURLsFunction::ReplayURLsFunction()
: RunPageCyclerFunction(new ProductionProcessStrategy()),
run_time_ms_(0.0) {
}
ReplayURLsFunction::ReplayURLsFunction(ProcessStrategy* strategy)
: RunPageCyclerFunction(strategy), run_time_ms_(0.0) {
}
ReplayURLsFunction::~ReplayURLsFunction() {}
// Fetch data for possible optional switches for a repeat count and an
// extension to load.
bool ReplayURLsFunction::ParseJSParameters() {
scoped_ptr<record::ReplayURLs::Params> params(
record::ReplayURLs::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get());
// TODO(cstaley): Must build full temp dir from capture_name
user_data_dir_ = FilePath::FromUTF8Unsafe(params->capture_name);
// TODO(cstaley): Get this from user data dir ultimately
url_contents_ = "http://www.google.com\nhttp://www.amazon.com";
repeat_count_ = params->repeat_count;
if (params->details.get()) {
if (params->details->extension_path.get())
extension_path_ =
FilePath::FromUTF8Unsafe(*params->details->extension_path);
}
return true;
}
// Add special switches, if indicated, for repeat count and extension to load,
// plus temp file into which to place stats. (Can't do this in
// ParseJSParameters because file creation can't go on the UI thread.)
// Plus, initialize time to create run time statistic.
void ReplayURLsFunction::AddSwitches(CommandLine* line) {
file_util::CreateTemporaryFile(&stats_file_path_);
if (!extension_path_.empty())
line->AppendSwitchPath(switches::kLoadExtension, extension_path_);
line->AppendSwitch(switches::kPlaybackMode);
line->AppendSwitchPath(switches::kRecordStats, stats_file_path_);
timer_ = base::Time::NowFromSystemTime();
}
// Read stats file, and get run time.
void ReplayURLsFunction::ReadReplyFiles() {
file_util::ReadFileToString(stats_file_path_, &stats_);
run_time_ms_ = (base::Time::NowFromSystemTime() - timer_).InMillisecondsF();
}
void ReplayURLsFunction::Finish() {
record::ReplayURLsResult result;
result.run_time = run_time_ms_;
result.stats = stats_;
result.errors = errors_;
results_ = record::ReplayURLs::Results::Create(result);
SendResponse(true);
}
} // namespace extensions
|
/*
* Copyright (c) 2017-2018 Arm Limited.
*
* SPDX-License-Identifier: MIT
*
* 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.
*/
#ifdef __aarch64__
#include <arm_neon.h>
#include "../../asmlib.hpp"
namespace arm_gemm {
void a64_gemm_u8_8x12(const uint8_t *Apanel, const uint8_t *Bpanel, uint32_t *Cpanel, int ablocks, int bblocks, int K) {
const uint8_t *a_ptr = Apanel;
uint32_t *c_ptr = Cpanel;
// We divide K by 4 because the udot instruction processes 4 elements at a time.
const int W = K/4;
// Fix up for odd lengths - set a flag if K is odd, but make
// sure we round up the iteration count.
const int oddk = (W & 1);
const int init_value_k = ((W+1)/2) - 1;
for (int yb=0; yb<ablocks; yb++) {
const uint8_t *a_ptr0 = a_ptr;
const uint8_t *b_ptr = Bpanel;
for (int xb=0; xb<bblocks; xb++) {
a_ptr = a_ptr0;
int k = init_value_k;
register uint8x16_t a0 asm("v0");
register uint8x16_t a1 asm("v1");
register uint8x16_t b0 asm("v2");
register uint8x16_t b1 asm("v3");
register uint8x16_t b2 asm("v4");
register uint8x16_t a0a asm("v5");
register uint8x16_t a1a asm("v6");
__asm __volatile (
// Initialize result registers, load initial operands, prime prefetches.
"movi v8.4s, #0x0\n"
"ldr %q[a0], [%[a_ptr]]\n"
"movi v9.4s, #0x0\n"
"ldr %q[b0], [%[b_ptr]]\n"
"movi v10.4s, #0x0\n"
"ldr %q[a1], [%[a_ptr], #16]\n"
"movi v11.4s, #0x0\n"
"ldr %q[b1], [%[b_ptr], #16]\n"
"movi v12.4s, #0x0\n"
ASM_PREFETCH("[%[b_ptr], #64]")
"movi v13.4s, #0x0\n"
ASM_PREFETCH("[%[a_ptr], #64]")
"movi v14.4s, #0x0\n"
ASM_PREFETCH("[%[b_ptr], #128]")
"movi v15.4s, #0x0\n"
ASM_PREFETCH("[%[a_ptr], #128]")
"movi v16.4s, #0x0\n"
ASM_PREFETCH("[%[b_ptr], #192]")
"movi v17.4s, #0x0\n"
ASM_PREFETCH("[%[b_ptr], #256]")
"movi v18.4s, #0x0\n"
ASM_PREFETCH("[%[a_ptr], #192]")
"movi v19.4s, #0x0\n"
ASM_PREFETCH("[%[b_ptr], #320]")
"movi v20.4s, #0x0\n"
ASM_PREFETCH("[%[a_ptr], #256]")
"movi v21.4s, #0x0\n"
ASM_PREFETCH("[%[b_ptr], #384]")
"movi v22.4s, #0x0\n"
"movi v23.4s, #0x0\n"
"movi v24.4s, #0x0\n"
"movi v25.4s, #0x0\n"
"movi v26.4s, #0x0\n"
"movi v27.4s, #0x0\n"
"movi v28.4s, #0x0\n"
"movi v29.4s, #0x0\n"
"movi v30.4s, #0x0\n"
"movi v31.4s, #0x0\n"
// Skip loop if we are doing zero iterations of it.
"cbz %w[k], 4f\n"
// Loop proper
"1:\n"
".word 0x6f80e048 // udot v8.4s , %[b0].16b, %[a0].4b[0]\n"
".word 0x6fa0e049 // udot v9.4s , %[b0].16b, %[a0].4b[1]\n"
"ldr %q[b2], [%[b_ptr], #32]\n"
".word 0x6f80e84a // udot v10.4s, %[b0].16b, %[a0].4b[2]\n"
".word 0x6fa0e84b // udot v11.4s, %[b0].16b, %[a0].4b[3]\n"
"ldr %q[a0a], [%[a_ptr], #32]\n"
".word 0x6f81e04c // udot v12.4s, %[b0].16b, %[a1].4b[0]\n"
".word 0x6fa1e04d // udot v13.4s, %[b0].16b, %[a1].4b[1]\n"
"ldr %q[a1a], [%[a_ptr], #48]\n"
".word 0x6f81e84e // udot v14.4s, %[b0].16b, %[a1].4b[2]\n"
".word 0x6fa1e84f // udot v15.4s, %[b0].16b, %[a1].4b[3]\n"
"ldr %q[b0], [%[b_ptr], #48]\n"
".word 0x6f80e070 // udot v16.4s, %[b1].16b, %[a0].4b[0]\n"
".word 0x6fa0e071 // udot v17.4s, %[b1].16b, %[a0].4b[1]\n"
ASM_PREFETCH("[%[a_ptr], #320]")
".word 0x6f80e872 // udot v18.4s, %[b1].16b, %[a0].4b[2]\n"
".word 0x6fa0e873 // udot v19.4s, %[b1].16b, %[a0].4b[3]\n"
".word 0x6f81e074 // udot v20.4s, %[b1].16b, %[a1].4b[0]\n"
".word 0x6fa1e075 // udot v21.4s, %[b1].16b, %[a1].4b[1]\n"
".word 0x6f81e876 // udot v22.4s, %[b1].16b, %[a1].4b[2]\n"
".word 0x6fa1e877 // udot v23.4s, %[b1].16b, %[a1].4b[3]\n"
"ldr %q[b1], [%[b_ptr], #64]\n"
".word 0x6f80e098 // udot v24.4s, %[b2].16b, %[a0].4b[0]\n"
".word 0x6fa0e099 // udot v25.4s, %[b2].16b, %[a0].4b[1]\n"
ASM_PREFETCH("[%[b_ptr], #448]")
".word 0x6f80e89a // udot v26.4s, %[b2].16b, %[a0].4b[2]\n"
".word 0x6fa0e89b // udot v27.4s, %[b2].16b, %[a0].4b[3]\n"
".word 0x6f81e09c // udot v28.4s, %[b2].16b, %[a1].4b[0]\n"
".word 0x6fa1e09d // udot v29.4s, %[b2].16b, %[a1].4b[1]\n"
".word 0x6f81e89e // udot v30.4s, %[b2].16b, %[a1].4b[2]\n"
".word 0x6fa1e89f // udot v31.4s, %[b2].16b, %[a1].4b[3]\n"
"ldr %q[b2], [%[b_ptr], #80]\n"
".word 0x6f85e048 // udot v8.4s , %[b0].16b, %[a0a].4b[0]\n"
".word 0x6fa5e049 // udot v9.4s , %[b0].16b, %[a0a].4b[1]\n"
"ldr %q[a0], [%[a_ptr], #64]\n"
".word 0x6f85e84a // udot v10.4s, %[b0].16b, %[a0a].4b[2]\n"
".word 0x6fa5e84b // udot v11.4s, %[b0].16b, %[a0a].4b[3]\n"
".word 0x6f86e04c // udot v12.4s, %[b0].16b, %[a1a].4b[0]\n"
"ldr %q[a1], [%[a_ptr], #80]\n"
".word 0x6fa6e04d // udot v13.4s, %[b0].16b, %[a1a].4b[1]\n"
".word 0x6f86e84e // udot v14.4s, %[b0].16b, %[a1a].4b[2]\n"
".word 0x6fa6e84f // udot v15.4s, %[b0].16b, %[a1a].4b[3]\n"
"ldr %q[b0], [%[b_ptr], #96]\n"
".word 0x6f85e070 // udot v16.4s, %[b1].16b, %[a0a].4b[0]\n"
".word 0x6fa5e071 // udot v17.4s, %[b1].16b, %[a0a].4b[1]\n"
ASM_PREFETCH("[%[b_ptr], #512]")
".word 0x6f85e872 // udot v18.4s, %[b1].16b, %[a0a].4b[2]\n"
".word 0x6fa5e873 // udot v19.4s, %[b1].16b, %[a0a].4b[3]\n"
".word 0x6f86e074 // udot v20.4s, %[b1].16b, %[a1a].4b[0]\n"
".word 0x6fa6e075 // udot v21.4s, %[b1].16b, %[a1a].4b[1]\n"
".word 0x6f86e876 // udot v22.4s, %[b1].16b, %[a1a].4b[2]\n"
".word 0x6fa6e877 // udot v23.4s, %[b1].16b, %[a1a].4b[3]\n"
"ldr %q[b1], [%[b_ptr], #112]\n"
".word 0x6f85e098 // udot v24.4s, %[b2].16b, %[a0a].4b[0]\n"
".word 0x6fa5e099 // udot v25.4s, %[b2].16b, %[a0a].4b[1]\n"
"add %[a_ptr], %[a_ptr], #64\n"
".word 0x6f85e89a // udot v26.4s, %[b2].16b, %[a0a].4b[2]\n"
".word 0x6fa5e89b // udot v27.4s, %[b2].16b, %[a0a].4b[3]\n"
"add %[b_ptr], %[b_ptr], #96\n"
".word 0x6f86e09c // udot v28.4s, %[b2].16b, %[a1a].4b[0]\n"
".word 0x6fa6e09d // udot v29.4s, %[b2].16b, %[a1a].4b[1]\n"
"subs %w[k], %w[k], #1\n"
".word 0x6f86e89e // udot v30.4s, %[b2].16b, %[a1a].4b[2]\n"
".word 0x6fa6e89f // udot v31.4s, %[b2].16b, %[a1a].4b[3]\n"
"bne 1b\n"
// Target to use when K is 1 or 2 (i.e. zero iterations of main loop)
"4:\n"
// Branch to alternative tail for odd K
"cbnz %w[oddk], 2f\n"
// Detached final iteration (even K)
".word 0x6f80e048 // udot v8.4s , %[b0].16b, %[a0].4b[0]\n"
".word 0x6fa0e049 // udot v9.4s , %[b0].16b, %[a0].4b[1]\n"
"ldr %q[b2], [%[b_ptr], #32]\n"
".word 0x6f80e84a // udot v10.4s, %[b0].16b, %[a0].4b[2]\n"
".word 0x6fa0e84b // udot v11.4s, %[b0].16b, %[a0].4b[3]\n"
"ldr %q[a0a], [%[a_ptr], #32]\n"
".word 0x6f81e04c // udot v12.4s, %[b0].16b, %[a1].4b[0]\n"
".word 0x6fa1e04d // udot v13.4s, %[b0].16b, %[a1].4b[1]\n"
"ldr %q[a1a], [%[a_ptr], #48]\n"
".word 0x6f81e84e // udot v14.4s, %[b0].16b, %[a1].4b[2]\n"
".word 0x6fa1e84f // udot v15.4s, %[b0].16b, %[a1].4b[3]\n"
"ldr %q[b0], [%[b_ptr], #48]\n"
".word 0x6f80e070 // udot v16.4s, %[b1].16b, %[a0].4b[0]\n"
".word 0x6fa0e071 // udot v17.4s, %[b1].16b, %[a0].4b[1]\n"
".word 0x6f80e872 // udot v18.4s, %[b1].16b, %[a0].4b[2]\n"
".word 0x6fa0e873 // udot v19.4s, %[b1].16b, %[a0].4b[3]\n"
".word 0x6f81e074 // udot v20.4s, %[b1].16b, %[a1].4b[0]\n"
".word 0x6fa1e075 // udot v21.4s, %[b1].16b, %[a1].4b[1]\n"
".word 0x6f81e876 // udot v22.4s, %[b1].16b, %[a1].4b[2]\n"
".word 0x6fa1e877 // udot v23.4s, %[b1].16b, %[a1].4b[3]\n"
"ldr %q[b1], [%[b_ptr], #64]\n"
".word 0x6f80e098 // udot v24.4s, %[b2].16b, %[a0].4b[0]\n"
".word 0x6fa0e099 // udot v25.4s, %[b2].16b, %[a0].4b[1]\n"
"add %[a_ptr], %[a_ptr], #64\n"
".word 0x6f80e89a // udot v26.4s, %[b2].16b, %[a0].4b[2]\n"
".word 0x6fa0e89b // udot v27.4s, %[b2].16b, %[a0].4b[3]\n"
".word 0x6f81e09c // udot v28.4s, %[b2].16b, %[a1].4b[0]\n"
".word 0x6fa1e09d // udot v29.4s, %[b2].16b, %[a1].4b[1]\n"
".word 0x6f81e89e // udot v30.4s, %[b2].16b, %[a1].4b[2]\n"
".word 0x6fa1e89f // udot v31.4s, %[b2].16b, %[a1].4b[3]\n"
"ldr %q[b2], [%[b_ptr], #80]\n"
".word 0x6f85e048 // udot v8.4s , %[b0].16b, %[a0a].4b[0]\n"
".word 0x6f85e070 // udot v16.4s, %[b1].16b, %[a0a].4b[0]\n"
"add %[b_ptr], %[b_ptr], #96\n"
".word 0x6fa5e049 // udot v9.4s , %[b0].16b, %[a0a].4b[1]\n"
"str q8, [%[c_ptr], #0]\n"
".word 0x6fa5e071 // udot v17.4s, %[b1].16b, %[a0a].4b[1]\n"
"str q16, [%[c_ptr], #16]\n"
".word 0x6f85e098 // udot v24.4s, %[b2].16b, %[a0a].4b[0]\n"
"str q24, [%[c_ptr], #32]\n"
".word 0x6fa5e099 // udot v25.4s, %[b2].16b, %[a0a].4b[1]\n"
"str q9, [%[c_ptr], #48]\n"
".word 0x6f85e84a // udot v10.4s, %[b0].16b, %[a0a].4b[2]\n"
"str q17, [%[c_ptr], #64]\n"
".word 0x6f85e872 // udot v18.4s, %[b1].16b, %[a0a].4b[2]\n"
"str q25, [%[c_ptr], #80]\n"
".word 0x6f85e89a // udot v26.4s, %[b2].16b, %[a0a].4b[2]\n"
"str q10, [%[c_ptr], #96]\n"
".word 0x6fa5e84b // udot v11.4s, %[b0].16b, %[a0a].4b[3]\n"
"str q18, [%[c_ptr], #112]\n"
".word 0x6fa5e873 // udot v19.4s, %[b1].16b, %[a0a].4b[3]\n"
"str q26, [%[c_ptr], #128]\n"
".word 0x6fa5e89b // udot v27.4s, %[b2].16b, %[a0a].4b[3]\n"
"str q11, [%[c_ptr], #144]\n"
".word 0x6f86e04c // udot v12.4s, %[b0].16b, %[a1a].4b[0]\n"
"str q19, [%[c_ptr], #160]\n"
".word 0x6f86e074 // udot v20.4s, %[b1].16b, %[a1a].4b[0]\n"
"str q27, [%[c_ptr], #176]\n"
".word 0x6f86e09c // udot v28.4s, %[b2].16b, %[a1a].4b[0]\n"
"str q12, [%[c_ptr], #192]\n"
".word 0x6fa6e04d // udot v13.4s, %[b0].16b, %[a1a].4b[1]\n"
"str q20, [%[c_ptr], #208]\n"
".word 0x6fa6e075 // udot v21.4s, %[b1].16b, %[a1a].4b[1]\n"
"str q28, [%[c_ptr], #224]\n"
".word 0x6fa6e09d // udot v29.4s, %[b2].16b, %[a1a].4b[1]\n"
"str q13, [%[c_ptr], #240]\n"
".word 0x6f86e84e // udot v14.4s, %[b0].16b, %[a1a].4b[2]\n"
"str q21, [%[c_ptr], #256]\n"
".word 0x6f86e876 // udot v22.4s, %[b1].16b, %[a1a].4b[2]\n"
"str q29, [%[c_ptr], #272]\n"
".word 0x6f86e89e // udot v30.4s, %[b2].16b, %[a1a].4b[2]\n"
"str q14, [%[c_ptr], #288]\n"
".word 0x6fa6e84f // udot v15.4s, %[b0].16b, %[a1a].4b[3]\n"
"str q22, [%[c_ptr], #304]\n"
".word 0x6fa6e877 // udot v23.4s, %[b1].16b, %[a1a].4b[3]\n"
"str q30, [%[c_ptr], #320]\n"
".word 0x6fa6e89f // udot v31.4s, %[b2].16b, %[a1a].4b[3]\n"
"str q15, [%[c_ptr], #336]\n"
"b 3f\n"
// Detached final iteration (odd K)
"2:\n"
".word 0x6f80e048 // udot v8.4s , %[b0].16b, %[a0].4b[0]\n"
"ldr %q[b2], [%[b_ptr], #32]\n"
".word 0x6f80e070 // udot v16.4s, %[b1].16b, %[a0].4b[0]\n"
".word 0x6fa0e049 // udot v9.4s , %[b0].16b, %[a0].4b[1]\n"
"str q8, [%[c_ptr], #0]\n"
".word 0x6fa0e071 // udot v17.4s, %[b1].16b, %[a0].4b[1]\n"
"str q16, [%[c_ptr], #16]\n"
".word 0x6f80e098 // udot v24.4s, %[b2].16b, %[a0].4b[0]\n"
"add %[b_ptr], %[b_ptr], #48\n"
"add %[a_ptr], %[a_ptr], #32\n"
"str q24, [%[c_ptr], #32]\n"
".word 0x6fa0e099 // udot v25.4s, %[b2].16b, %[a0].4b[1]\n"
"str q9, [%[c_ptr], #48]\n"
".word 0x6f80e84a // udot v10.4s, %[b0].16b, %[a0].4b[2]\n"
"str q17, [%[c_ptr], #64]\n"
".word 0x6f80e872 // udot v18.4s, %[b1].16b, %[a0].4b[2]\n"
"str q25, [%[c_ptr], #80]\n"
".word 0x6f80e89a // udot v26.4s, %[b2].16b, %[a0].4b[2]\n"
"str q10, [%[c_ptr], #96]\n"
".word 0x6fa0e84b // udot v11.4s, %[b0].16b, %[a0].4b[3]\n"
"str q18, [%[c_ptr], #112]\n"
".word 0x6fa0e873 // udot v19.4s, %[b1].16b, %[a0].4b[3]\n"
"str q26, [%[c_ptr], #128]\n"
".word 0x6fa0e89b // udot v27.4s, %[b2].16b, %[a0].4b[3]\n"
"str q11, [%[c_ptr], #144]\n"
".word 0x6f81e04c // udot v12.4s, %[b0].16b, %[a1].4b[0]\n"
"str q19, [%[c_ptr], #160]\n"
".word 0x6f81e074 // udot v20.4s, %[b1].16b, %[a1].4b[0]\n"
"str q27, [%[c_ptr], #176]\n"
".word 0x6f81e09c // udot v28.4s, %[b2].16b, %[a1].4b[0]\n"
"str q12, [%[c_ptr], #192]\n"
".word 0x6fa1e04d // udot v13.4s, %[b0].16b, %[a1].4b[1]\n"
"str q20, [%[c_ptr], #208]\n"
".word 0x6fa1e075 // udot v21.4s, %[b1].16b, %[a1].4b[1]\n"
"str q28, [%[c_ptr], #224]\n"
".word 0x6fa1e09d // udot v29.4s, %[b2].16b, %[a1].4b[1]\n"
"str q13, [%[c_ptr], #240]\n"
".word 0x6f81e84e // udot v14.4s, %[b0].16b, %[a1].4b[2]\n"
"str q21, [%[c_ptr], #256]\n"
".word 0x6f81e876 // udot v22.4s, %[b1].16b, %[a1].4b[2]\n"
"str q29, [%[c_ptr], #272]\n"
".word 0x6f81e89e // udot v30.4s, %[b2].16b, %[a1].4b[2]\n"
"str q14, [%[c_ptr], #288]\n"
".word 0x6fa1e84f // udot v15.4s, %[b0].16b, %[a1].4b[3]\n"
"str q22, [%[c_ptr], #304]\n"
".word 0x6fa1e877 // udot v23.4s, %[b1].16b, %[a1].4b[3]\n"
"str q30, [%[c_ptr], #320]\n"
".word 0x6fa1e89f // udot v31.4s, %[b2].16b, %[a1].4b[3]\n"
"str q15, [%[c_ptr], #336]\n"
// Common tail
"3:\n"
"str q23, [%[c_ptr], #352]\n"
"str q31, [%[c_ptr], #368]\n"
"add %[c_ptr], %[c_ptr], #384\n"
:
[a_ptr] "+r" (a_ptr), [b_ptr] "+r" (b_ptr), [c_ptr] "+r" (c_ptr),
[a0] "+w" (a0), [a1] "+w" (a1), [a0a] "+w" (a0a), [a1a] "+w" (a1a),
[b0] "+w" (b0), [b1] "+w" (b1), [b2] "+w" (b2), [k] "+r" (k)
: [oddk] "r" (oddk)
: "x20", "x21", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18",
"v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31", "cc"
);
}
}
}
} // namespace arm_gemm
#endif
|
//==============================================================================
// Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II
// Copyright 2009 - 2011 LRI UMR 8623 CNRS/Univ Paris Sud XI
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef BOOST_SIMD_ARITHMETIC_FUNCTIONS_SIMD_COMMON_REC_HPP_INCLUDED
#define BOOST_SIMD_ARITHMETIC_FUNCTIONS_SIMD_COMMON_REC_HPP_INCLUDED
#include <boost/simd/arithmetic/functions/rec.hpp>
#include <boost/dispatch/meta/as_floating.hpp>
#include <boost/simd/sdk/simd/meta/is_real_convertible.hpp>
#include <boost/simd/include/constants/digits.hpp>
#include <boost/simd/include/functions/simd/divides.hpp>
#include <boost/simd/include/functions/simd/tofloat.hpp>
namespace boost { namespace simd { namespace ext
{
BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::rec_, tag::cpu_
, (A0)(X)
, ((simd_<arithmetic_<A0>,X>))
)
{
typedef typename dispatch::meta::as_floating<A0>::type result_type;
BOOST_SIMD_FUNCTOR_CALL(1)
{
return One<result_type>()/boost::simd::tofloat(a0);
}
};
} } }
#endif
|
// Copyright Benoit Blanchon 2014-2015
// MIT License
//
// Arduino JSON library
// https://github.com/bblanchon/ArduinoJson
#include "../../include/ArduinoJson/Internals/JsonParser.hpp"
#include <stdlib.h> // for strtol, strtod
#include <ctype.h>
#include "../../include/ArduinoJson/Internals/QuotedString.hpp"
#include "../../include/ArduinoJson/JsonArray.hpp"
#include "../../include/ArduinoJson/JsonBuffer.hpp"
#include "../../include/ArduinoJson/JsonObject.hpp"
using namespace ArduinoJson;
using namespace ArduinoJson::Internals;
void JsonParser::skipSpaces() {
while (isspace(*_ptr)) _ptr++;
}
bool JsonParser::skip(char charToSkip) {
skipSpaces();
if (*_ptr != charToSkip) return false;
_ptr++;
skipSpaces();
return true;
}
bool JsonParser::skip(const char *wordToSkip) {
const char *charToSkip = wordToSkip;
while (*charToSkip && *_ptr == *charToSkip) {
charToSkip++;
_ptr++;
}
return *charToSkip == '\0';
}
void JsonParser::parseAnythingTo(JsonVariant &destination) {
if (_nestingLimit == 0) return;
_nestingLimit--;
skipSpaces();
switch (*_ptr) {
case '[':
destination = parseArray();
break;
case '{':
destination = parseObject();
break;
case 't':
case 'f':
parseBooleanTo(destination);
break;
case '-':
case '.':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
parseNumberTo(destination);
break;
case 'n':
parseNullTo(destination);
break;
case '\'':
case '\"':
destination = parseString();
break;
}
_nestingLimit++;
}
JsonArray &JsonParser::parseArray() {
// Create an empty array
JsonArray &array = _buffer->createArray();
// Check opening braket
if (!skip('[')) goto ERROR_MISSING_BRACKET;
if (skip(']')) goto SUCCESS_EMPTY_ARRAY;
// Read each value
for (;;) {
// 1 - Parse value
JsonVariant &value = array.add();
parseAnythingTo(value);
if (!value.success()) goto ERROR_INVALID_VALUE;
// 2 - More values?
if (skip(']')) goto SUCCES_NON_EMPTY_ARRAY;
if (!skip(',')) goto ERROR_MISSING_COMMA;
}
SUCCESS_EMPTY_ARRAY:
SUCCES_NON_EMPTY_ARRAY:
return array;
ERROR_INVALID_VALUE:
ERROR_MISSING_BRACKET:
ERROR_MISSING_COMMA:
return JsonArray::invalid();
}
JsonObject &JsonParser::parseObject() {
// Create an empty object
JsonObject &object = _buffer->createObject();
// Check opening brace
if (!skip('{')) goto ERROR_MISSING_BRACE;
if (skip('}')) goto SUCCESS_EMPTY_OBJECT;
// Read each key value pair
for (;;) {
// 1 - Parse key
const char *key = parseString();
if (!key) goto ERROR_INVALID_KEY;
if (!skip(':')) goto ERROR_MISSING_COLON;
// 2 - Parse value
JsonVariant &value = object.add(key);
parseAnythingTo(value);
if (!value.success()) goto ERROR_INVALID_VALUE;
// 3 - More keys/values?
if (skip('}')) goto SUCCESS_NON_EMPTY_OBJECT;
if (!skip(',')) goto ERROR_MISSING_COMMA;
}
SUCCESS_EMPTY_OBJECT:
SUCCESS_NON_EMPTY_OBJECT:
return object;
ERROR_INVALID_KEY:
ERROR_INVALID_VALUE:
ERROR_MISSING_BRACE:
ERROR_MISSING_COLON:
ERROR_MISSING_COMMA:
return JsonObject::invalid();
}
void JsonParser::parseBooleanTo(JsonVariant &destination) {
if (skip("true"))
destination = true;
else if (skip("false"))
destination = false;
else
destination = JsonVariant::invalid();
}
void JsonParser::parseNumberTo(JsonVariant &destination) {
char *endOfLong;
long longValue = strtol(_ptr, &endOfLong, 10);
char stopChar = *endOfLong;
// Could it be a floating point value?
bool couldBeFloat = stopChar == '.' || stopChar == 'e' || stopChar == 'E';
if (couldBeFloat) {
// Yes => parse it as a double
double doubleValue = strtod(_ptr, &_ptr);
// Count the decimal digits
uint8_t decimals = static_cast<uint8_t>(_ptr - endOfLong - 1);
// Set the variant as a double
destination.set(doubleValue, decimals);
} else {
// No => set the variant as a long
_ptr = endOfLong;
destination = longValue;
}
}
void JsonParser::parseNullTo(JsonVariant &destination) {
const char *NULL_STRING = NULL;
if (skip("null"))
destination = NULL_STRING;
else
destination = JsonVariant::invalid();
}
const char *JsonParser::parseString() {
return QuotedString::extractFrom(_ptr, &_ptr);
}
|
#include "StatsTestsQ31.h"
#include <stdio.h>
#include "Error.h"
#include "Test.h"
//#include <cstdio>
#define SNR_THRESHOLD 100
#define SNR_THRESHOLD_MSE 100
/*
Reference patterns are generated with
a double precision computation.
*/
#define ABS_ERROR_Q31 ((q31_t)(100))
#define ABS_ERROR_Q31_MSE ((q31_t)(100))
#define ABS_ERROR_Q63 ((q63_t)(1<<18))
void StatsTestsQ31::test_max_q31()
{
const q31_t *inp = inputA.ptr();
q31_t result;
uint32_t indexval;
q31_t *refp = ref.ptr();
int16_t *refind = maxIndexes.ptr();
q31_t *outp = output.ptr();
int16_t *ind = index.ptr();
arm_max_q31(inp,
inputA.nbSamples(),
&result,
&indexval);
outp[0] = result;
ind[0] = indexval;
ASSERT_EQ(result,refp[this->refOffset]);
ASSERT_EQ((int16_t)indexval,refind[this->refOffset]);
}
void StatsTestsQ31::test_absmax_q31()
{
const q31_t *inp = inputA.ptr();
q31_t result;
uint32_t indexval;
q31_t *refp = ref.ptr();
int16_t *refind = maxIndexes.ptr();
q31_t *outp = output.ptr();
int16_t *ind = index.ptr();
arm_absmax_q31(inp,
inputA.nbSamples(),
&result,
&indexval);
outp[0] = result;
ind[0] = indexval;
ASSERT_EQ(result,refp[this->refOffset]);
ASSERT_EQ((int16_t)indexval,refind[this->refOffset]);
}
void StatsTestsQ31::test_min_q31()
{
const q31_t *inp = inputA.ptr();
q31_t result;
uint32_t indexval;
q31_t *refp = ref.ptr();
int16_t *refind = minIndexes.ptr();
q31_t *outp = output.ptr();
int16_t *ind = index.ptr();
arm_min_q31(inp,
inputA.nbSamples(),
&result,
&indexval);
outp[0] = result;
ind[0] = indexval;
ASSERT_EQ(result,refp[this->refOffset]);
ASSERT_EQ((int16_t)indexval,refind[this->refOffset]);
}
void StatsTestsQ31::test_min_no_idx_q31()
{
const q31_t *inp = inputA.ptr();
q31_t result;
q31_t *refp = ref.ptr();
q31_t *outp = output.ptr();
arm_min_no_idx_q31(inp,
inputA.nbSamples(),
&result);
outp[0] = result;
ASSERT_EQ(result,refp[this->refOffset]);
}
void StatsTestsQ31::test_absmin_no_idx_q31()
{
const q31_t *inp = inputA.ptr();
q31_t result;
q31_t *refp = ref.ptr();
q31_t *outp = output.ptr();
arm_absmin_no_idx_q31(inp,
inputA.nbSamples(),
&result);
outp[0] = result;
ASSERT_EQ(result,refp[this->refOffset]);
}
void StatsTestsQ31::test_absmin_q31()
{
const q31_t *inp = inputA.ptr();
q31_t result;
uint32_t indexval;
q31_t *refp = ref.ptr();
int16_t *refind = minIndexes.ptr();
q31_t *outp = output.ptr();
int16_t *ind = index.ptr();
arm_absmin_q31(inp,
inputA.nbSamples(),
&result,
&indexval);
outp[0] = result;
ind[0] = indexval;
ASSERT_EQ(result,refp[this->refOffset]);
ASSERT_EQ((int16_t)indexval,refind[this->refOffset]);
}
void StatsTestsQ31::test_mean_q31()
{
const q31_t *inp = inputA.ptr();
q31_t result;
q31_t *refp = ref.ptr();
q31_t *outp = output.ptr();
arm_mean_q31(inp,
inputA.nbSamples(),
&result);
outp[0] = result;
ASSERT_SNR(result,refp[this->refOffset],(float32_t)SNR_THRESHOLD);
ASSERT_NEAR_EQ(result,refp[this->refOffset],ABS_ERROR_Q31);
}
void StatsTestsQ31::test_power_q31()
{
const q31_t *inp = inputA.ptr();
q63_t result;
q63_t *refp = refPower.ptr();
q63_t *outp = outputPower.ptr();
arm_power_q31(inp,
inputA.nbSamples(),
&result);
outp[0] = result;
ASSERT_SNR(result,refp[this->refOffset],(float32_t)SNR_THRESHOLD);
ASSERT_NEAR_EQ(result,refp[this->refOffset],(q63_t)ABS_ERROR_Q63);
}
void StatsTestsQ31::test_rms_q31()
{
const q31_t *inp = inputA.ptr();
q31_t result;
q31_t *refp = ref.ptr();
q31_t *outp = output.ptr();
arm_rms_q31(inp,
inputA.nbSamples(),
&result);
outp[0] = result;
ASSERT_SNR(result,refp[this->refOffset],(float32_t)SNR_THRESHOLD);
ASSERT_NEAR_EQ(result,refp[this->refOffset],ABS_ERROR_Q31);
}
void StatsTestsQ31::test_std_q31()
{
const q31_t *inp = inputA.ptr();
q31_t result;
q31_t *refp = ref.ptr();
q31_t *outp = output.ptr();
arm_std_q31(inp,
inputA.nbSamples(),
&result);
outp[0] = result;
ASSERT_SNR(result,refp[this->refOffset],(float32_t)SNR_THRESHOLD);
ASSERT_NEAR_EQ(result,refp[this->refOffset],ABS_ERROR_Q31);
}
void StatsTestsQ31::test_var_q31()
{
const q31_t *inp = inputA.ptr();
q31_t result;
q31_t *refp = ref.ptr();
q31_t *outp = output.ptr();
arm_var_q31(inp,
inputA.nbSamples(),
&result);
outp[0] = result;
ASSERT_SNR(result,refp[this->refOffset],(float32_t)SNR_THRESHOLD);
ASSERT_NEAR_EQ(result,refp[this->refOffset],ABS_ERROR_Q31);
}
void StatsTestsQ31::test_max_no_idx_q31()
{
const q31_t *inp = inputA.ptr();
q31_t result;
q31_t *refp = ref.ptr();
q31_t *outp = output.ptr();
arm_max_no_idx_q31(inp,
inputA.nbSamples(),
&result);
outp[0] = result;
ASSERT_EQ(result,refp[this->refOffset]);
}
void StatsTestsQ31::test_absmax_no_idx_q31()
{
const q31_t *inp = inputA.ptr();
q31_t result;
q31_t *refp = ref.ptr();
q31_t *outp = output.ptr();
arm_absmax_no_idx_q31(inp,
inputA.nbSamples(),
&result);
outp[0] = result;
ASSERT_EQ(result,refp[this->refOffset]);
}
void StatsTestsQ31::test_mse_q31()
{
const q31_t *inpA = inputA.ptr();
const q31_t *inpB = inputB.ptr();
q31_t result;
q31_t *refp = ref.ptr();
q31_t *outp = output.ptr();
arm_mse_q31(inpA,inpB,
inputA.nbSamples(),
&result);
outp[0] = result;
ASSERT_SNR(result,refp[this->refOffset],(float32_t)SNR_THRESHOLD_MSE);
ASSERT_NEAR_EQ(result,refp[this->refOffset],(q31_t)ABS_ERROR_Q31_MSE);
}
void StatsTestsQ31::setUp(Testing::testID_t id,std::vector<Testing::param_t>& paramsArgs,Client::PatternMgr *mgr)
{
(void)paramsArgs;
switch(id)
{
case StatsTestsQ31::TEST_MAX_Q31_1:
{
inputA.reload(StatsTestsQ31::INPUT1_Q31_ID,mgr,3);
maxIndexes.reload(StatsTestsQ31::MAXINDEXES_S16_ID,mgr);
ref.reload(StatsTestsQ31::MAXVALS_Q31_ID,mgr);
output.create(1,StatsTestsQ31::OUT_Q31_ID,mgr);
index.create(1,StatsTestsQ31::OUT_S16_ID,mgr);
refOffset = 0;
}
break;
case StatsTestsQ31::TEST_MAX_Q31_2:
{
inputA.reload(StatsTestsQ31::INPUT1_Q31_ID,mgr,8);
maxIndexes.reload(StatsTestsQ31::MAXINDEXES_S16_ID,mgr);
ref.reload(StatsTestsQ31::MAXVALS_Q31_ID,mgr);
output.create(1,StatsTestsQ31::OUT_Q31_ID,mgr);
index.create(1,StatsTestsQ31::OUT_S16_ID,mgr);
refOffset = 1;
}
break;
case StatsTestsQ31::TEST_MAX_Q31_3:
{
inputA.reload(StatsTestsQ31::INPUT1_Q31_ID,mgr,11);
maxIndexes.reload(StatsTestsQ31::MAXINDEXES_S16_ID,mgr);
ref.reload(StatsTestsQ31::MAXVALS_Q31_ID,mgr);
output.create(1,StatsTestsQ31::OUT_Q31_ID,mgr);
index.create(1,StatsTestsQ31::OUT_S16_ID,mgr);
refOffset = 2;
}
break;
case StatsTestsQ31::TEST_MEAN_Q31_4:
{
inputA.reload(StatsTestsQ31::INPUT2_Q31_ID,mgr,3);
ref.reload(StatsTestsQ31::MEANVALS_Q31_ID,mgr);
output.create(1,StatsTestsQ31::OUT_Q31_ID,mgr);
refOffset = 0;
}
break;
case StatsTestsQ31::TEST_MEAN_Q31_5:
{
inputA.reload(StatsTestsQ31::INPUT2_Q31_ID,mgr,8);
ref.reload(StatsTestsQ31::MEANVALS_Q31_ID,mgr);
output.create(1,StatsTestsQ31::OUT_Q31_ID,mgr);
refOffset = 1;
}
break;
case StatsTestsQ31::TEST_MEAN_Q31_6:
{
inputA.reload(StatsTestsQ31::INPUT2_Q31_ID,mgr,11);
ref.reload(StatsTestsQ31::MEANVALS_Q31_ID,mgr);
output.create(1,StatsTestsQ31::OUT_Q31_ID,mgr);
refOffset = 2;
}
break;
case StatsTestsQ31::TEST_MIN_Q31_7:
{
inputA.reload(StatsTestsQ31::INPUT1_Q31_ID,mgr,3);
minIndexes.reload(StatsTestsQ31::MININDEXES_S16_ID,mgr);
ref.reload(StatsTestsQ31::MINVALS_Q31_ID,mgr);
output.create(1,StatsTestsQ31::OUT_Q31_ID,mgr);
index.create(1,StatsTestsQ31::OUT_S16_ID,mgr);
refOffset = 0;
}
break;
case StatsTestsQ31::TEST_MIN_Q31_8:
{
inputA.reload(StatsTestsQ31::INPUT1_Q31_ID,mgr,8);
minIndexes.reload(StatsTestsQ31::MININDEXES_S16_ID,mgr);
ref.reload(StatsTestsQ31::MINVALS_Q31_ID,mgr);
output.create(1,StatsTestsQ31::OUT_Q31_ID,mgr);
index.create(1,StatsTestsQ31::OUT_S16_ID,mgr);
refOffset = 1;
}
break;
case StatsTestsQ31::TEST_MIN_Q31_9:
{
inputA.reload(StatsTestsQ31::INPUT1_Q31_ID,mgr,11);
minIndexes.reload(StatsTestsQ31::MININDEXES_S16_ID,mgr);
ref.reload(StatsTestsQ31::MINVALS_Q31_ID,mgr);
output.create(1,StatsTestsQ31::OUT_Q31_ID,mgr);
index.create(1,StatsTestsQ31::OUT_S16_ID,mgr);
refOffset = 2;
}
break;
case StatsTestsQ31::TEST_POWER_Q31_10:
{
inputA.reload(StatsTestsQ31::INPUT1_Q31_ID,mgr,3);
refPower.reload(StatsTestsQ31::POWERVALS_Q63_ID,mgr);
outputPower.create(1,StatsTestsQ31::OUT_Q31_ID,mgr);
refOffset = 0;
}
break;
case StatsTestsQ31::TEST_POWER_Q31_11:
{
inputA.reload(StatsTestsQ31::INPUT1_Q31_ID,mgr,8);
refPower.reload(StatsTestsQ31::POWERVALS_Q63_ID,mgr);
outputPower.create(1,StatsTestsQ31::OUT_Q31_ID,mgr);
refOffset = 1;
}
break;
case StatsTestsQ31::TEST_POWER_Q31_12:
{
inputA.reload(StatsTestsQ31::INPUT1_Q31_ID,mgr,11);
refPower.reload(StatsTestsQ31::POWERVALS_Q63_ID,mgr);
outputPower.create(1,StatsTestsQ31::OUT_Q31_ID,mgr);
refOffset = 2;
}
break;
case StatsTestsQ31::TEST_RMS_Q31_13:
{
inputA.reload(StatsTestsQ31::INPUT1_Q31_ID,mgr,3);
ref.reload(StatsTestsQ31::RMSVALS_Q31_ID,mgr);
output.create(1,StatsTestsQ31::OUT_Q31_ID,mgr);
refOffset = 0;
}
break;
case StatsTestsQ31::TEST_RMS_Q31_14:
{
inputA.reload(StatsTestsQ31::INPUT1_Q31_ID,mgr,8);
ref.reload(StatsTestsQ31::RMSVALS_Q31_ID,mgr);
output.create(1,StatsTestsQ31::OUT_Q31_ID,mgr);
refOffset = 1;
}
break;
case StatsTestsQ31::TEST_RMS_Q31_15:
{
inputA.reload(StatsTestsQ31::INPUT1_Q31_ID,mgr,11);
ref.reload(StatsTestsQ31::RMSVALS_Q31_ID,mgr);
output.create(1,StatsTestsQ31::OUT_Q31_ID,mgr);
refOffset = 2;
}
break;
case StatsTestsQ31::TEST_STD_Q31_16:
{
inputA.reload(StatsTestsQ31::INPUT1_Q31_ID,mgr,3);
ref.reload(StatsTestsQ31::STDVALS_Q31_ID,mgr);
output.create(1,StatsTestsQ31::OUT_Q31_ID,mgr);
refOffset = 0;
}
break;
case StatsTestsQ31::TEST_STD_Q31_17:
{
inputA.reload(StatsTestsQ31::INPUT1_Q31_ID,mgr,8);
ref.reload(StatsTestsQ31::STDVALS_Q31_ID,mgr);
output.create(1,StatsTestsQ31::OUT_Q31_ID,mgr);
refOffset = 1;
}
break;
case StatsTestsQ31::TEST_STD_Q31_18:
{
inputA.reload(StatsTestsQ31::INPUT1_Q31_ID,mgr,11);
ref.reload(StatsTestsQ31::STDVALS_Q31_ID,mgr);
output.create(1,StatsTestsQ31::OUT_Q31_ID,mgr);
refOffset = 2;
}
break;
case StatsTestsQ31::TEST_VAR_Q31_19:
{
inputA.reload(StatsTestsQ31::INPUT1_Q31_ID,mgr,3);
ref.reload(StatsTestsQ31::VARVALS_Q31_ID,mgr);
output.create(1,StatsTestsQ31::OUT_Q31_ID,mgr);
refOffset = 0;
}
break;
case StatsTestsQ31::TEST_VAR_Q31_20:
{
inputA.reload(StatsTestsQ31::INPUT1_Q31_ID,mgr,8);
ref.reload(StatsTestsQ31::VARVALS_Q31_ID,mgr);
output.create(1,StatsTestsQ31::OUT_Q31_ID,mgr);
refOffset = 1;
}
break;
case StatsTestsQ31::TEST_VAR_Q31_21:
{
inputA.reload(StatsTestsQ31::INPUT1_Q31_ID,mgr,11);
ref.reload(StatsTestsQ31::VARVALS_Q31_ID,mgr);
output.create(1,StatsTestsQ31::OUT_Q31_ID,mgr);
refOffset = 2;
}
break;
case StatsTestsQ31::TEST_ABSMAX_Q31_22:
{
inputA.reload(StatsTestsQ31::INPUTNEW1_Q31_ID,mgr,3);
maxIndexes.reload(StatsTestsQ31::ABSMAXINDEXES_S16_ID,mgr);
ref.reload(StatsTestsQ31::ABSMAXVALS_Q31_ID,mgr);
output.create(1,StatsTestsQ31::OUT_Q31_ID,mgr);
index.create(1,StatsTestsQ31::OUT_S16_ID,mgr);
refOffset = 0;
}
break;
case StatsTestsQ31::TEST_ABSMAX_Q31_23:
{
inputA.reload(StatsTestsQ31::INPUTNEW1_Q31_ID,mgr,8);
maxIndexes.reload(StatsTestsQ31::ABSMAXINDEXES_S16_ID,mgr);
ref.reload(StatsTestsQ31::ABSMAXVALS_Q31_ID,mgr);
output.create(1,StatsTestsQ31::OUT_Q31_ID,mgr);
index.create(1,StatsTestsQ31::OUT_S16_ID,mgr);
refOffset = 1;
}
break;
case StatsTestsQ31::TEST_ABSMAX_Q31_24:
{
inputA.reload(StatsTestsQ31::INPUTNEW1_Q31_ID,mgr,11);
maxIndexes.reload(StatsTestsQ31::ABSMAXINDEXES_S16_ID,mgr);
ref.reload(StatsTestsQ31::ABSMAXVALS_Q31_ID,mgr);
output.create(1,StatsTestsQ31::OUT_Q31_ID,mgr);
index.create(1,StatsTestsQ31::OUT_S16_ID,mgr);
refOffset = 2;
}
break;
case StatsTestsQ31::TEST_ABSMIN_Q31_25:
{
inputA.reload(StatsTestsQ31::INPUTNEW1_Q31_ID,mgr,3);
minIndexes.reload(StatsTestsQ31::ABSMININDEXES_S16_ID,mgr);
ref.reload(StatsTestsQ31::ABSMINVALS_Q31_ID,mgr);
output.create(1,StatsTestsQ31::OUT_Q31_ID,mgr);
index.create(1,StatsTestsQ31::OUT_S16_ID,mgr);
refOffset = 0;
}
break;
case StatsTestsQ31::TEST_ABSMIN_Q31_26:
{
inputA.reload(StatsTestsQ31::INPUTNEW1_Q31_ID,mgr,8);
minIndexes.reload(StatsTestsQ31::ABSMININDEXES_S16_ID,mgr);
ref.reload(StatsTestsQ31::ABSMINVALS_Q31_ID,mgr);
output.create(1,StatsTestsQ31::OUT_Q31_ID,mgr);
index.create(1,StatsTestsQ31::OUT_S16_ID,mgr);
refOffset = 1;
}
break;
case StatsTestsQ31::TEST_ABSMIN_Q31_27:
{
inputA.reload(StatsTestsQ31::INPUTNEW1_Q31_ID,mgr,11);
minIndexes.reload(StatsTestsQ31::ABSMININDEXES_S16_ID,mgr);
ref.reload(StatsTestsQ31::ABSMINVALS_Q31_ID,mgr);
output.create(1,StatsTestsQ31::OUT_Q31_ID,mgr);
index.create(1,StatsTestsQ31::OUT_S16_ID,mgr);
refOffset = 2;
}
break;
case StatsTestsQ31::TEST_MAX_NO_IDX_Q31_28:
{
inputA.reload(StatsTestsQ31::INPUT1_Q31_ID,mgr,3);
ref.reload(StatsTestsQ31::MAXVALS_Q31_ID,mgr);
output.create(1,StatsTestsQ31::OUT_Q31_ID,mgr);
refOffset = 0;
}
break;
case StatsTestsQ31::TEST_MAX_NO_IDX_Q31_29:
{
inputA.reload(StatsTestsQ31::INPUT1_Q31_ID,mgr,8);
ref.reload(StatsTestsQ31::MAXVALS_Q31_ID,mgr);
output.create(1,StatsTestsQ31::OUT_Q31_ID,mgr);
refOffset = 1;
}
break;
case StatsTestsQ31::TEST_MAX_NO_IDX_Q31_30:
{
inputA.reload(StatsTestsQ31::INPUT1_Q31_ID,mgr,11);
ref.reload(StatsTestsQ31::MAXVALS_Q31_ID,mgr);
output.create(1,StatsTestsQ31::OUT_Q31_ID,mgr);
refOffset = 2;
}
break;
case StatsTestsQ31::TEST_MIN_NO_IDX_Q31_31:
{
inputA.reload(StatsTestsQ31::INPUT1_Q31_ID,mgr,3);
ref.reload(StatsTestsQ31::MINVALS_Q31_ID,mgr);
output.create(1,StatsTestsQ31::OUT_Q31_ID,mgr);
refOffset = 0;
}
break;
case StatsTestsQ31::TEST_MIN_NO_IDX_Q31_32:
{
inputA.reload(StatsTestsQ31::INPUT1_Q31_ID,mgr,8);
ref.reload(StatsTestsQ31::MINVALS_Q31_ID,mgr);
output.create(1,StatsTestsQ31::OUT_Q31_ID,mgr);
refOffset = 1;
}
break;
case StatsTestsQ31::TEST_MIN_NO_IDX_Q31_33:
{
inputA.reload(StatsTestsQ31::INPUT1_Q31_ID,mgr,11);
ref.reload(StatsTestsQ31::MINVALS_Q31_ID,mgr);
output.create(1,StatsTestsQ31::OUT_Q31_ID,mgr);
refOffset = 2;
}
break;
case StatsTestsQ31::TEST_ABSMAX_NO_IDX_Q31_34:
{
inputA.reload(StatsTestsQ31::INPUTNEW1_Q31_ID,mgr,3);
ref.reload(StatsTestsQ31::ABSMAXVALS_Q31_ID,mgr);
output.create(1,StatsTestsQ31::OUT_Q31_ID,mgr);
refOffset = 0;
}
break;
case StatsTestsQ31::TEST_ABSMAX_NO_IDX_Q31_35:
{
inputA.reload(StatsTestsQ31::INPUTNEW1_Q31_ID,mgr,8);
ref.reload(StatsTestsQ31::ABSMAXVALS_Q31_ID,mgr);
output.create(1,StatsTestsQ31::OUT_Q31_ID,mgr);
refOffset = 1;
}
break;
case StatsTestsQ31::TEST_ABSMAX_NO_IDX_Q31_36:
{
inputA.reload(StatsTestsQ31::INPUTNEW1_Q31_ID,mgr,11);
ref.reload(StatsTestsQ31::ABSMAXVALS_Q31_ID,mgr);
output.create(1,StatsTestsQ31::OUT_Q31_ID,mgr);
refOffset = 2;
}
break;
case StatsTestsQ31::TEST_ABSMIN_NO_IDX_Q31_37:
{
inputA.reload(StatsTestsQ31::INPUTNEW1_Q31_ID,mgr,3);
ref.reload(StatsTestsQ31::ABSMINVALS_Q31_ID,mgr);
output.create(1,StatsTestsQ31::OUT_Q31_ID,mgr);
refOffset = 0;
}
break;
case StatsTestsQ31::TEST_ABSMIN_NO_IDX_Q31_38:
{
inputA.reload(StatsTestsQ31::INPUTNEW1_Q31_ID,mgr,8);
ref.reload(StatsTestsQ31::ABSMINVALS_Q31_ID,mgr);
output.create(1,StatsTestsQ31::OUT_Q31_ID,mgr);
refOffset = 1;
}
break;
case StatsTestsQ31::TEST_ABSMIN_NO_IDX_Q31_39:
{
inputA.reload(StatsTestsQ31::INPUTNEW1_Q31_ID,mgr,11);
ref.reload(StatsTestsQ31::ABSMINVALS_Q31_ID,mgr);
output.create(1,StatsTestsQ31::OUT_Q31_ID,mgr);
refOffset = 2;
}
break;
case StatsTestsQ31::TEST_MSE_Q31_40:
{
inputA.reload(StatsTestsQ31::INPUTNEW1_Q31_ID,mgr,3);
inputB.reload(StatsTestsQ31::INPUTNEW2_Q31_ID,mgr,3);
ref.reload(StatsTestsQ31::MSE_Q31_ID,mgr);
output.create(1,StatsTestsQ31::OUT_Q31_ID,mgr);
refOffset = 0;
}
break;
case StatsTestsQ31::TEST_MSE_Q31_41:
{
inputA.reload(StatsTestsQ31::INPUTNEW1_Q31_ID,mgr,8);
inputB.reload(StatsTestsQ31::INPUTNEW2_Q31_ID,mgr,8);
ref.reload(StatsTestsQ31::MSE_Q31_ID,mgr);
output.create(1,StatsTestsQ31::OUT_Q31_ID,mgr);
refOffset = 1;
}
break;
case StatsTestsQ31::TEST_MSE_Q31_42:
{
inputA.reload(StatsTestsQ31::INPUTNEW1_Q31_ID,mgr,11);
inputB.reload(StatsTestsQ31::INPUTNEW2_Q31_ID,mgr,11);
ref.reload(StatsTestsQ31::MSE_Q31_ID,mgr);
output.create(1,StatsTestsQ31::OUT_Q31_ID,mgr);
refOffset = 2;
}
break;
case StatsTestsQ31::TEST_MSE_Q31_43:
{
inputA.reload(StatsTestsQ31::INPUTNEW1_Q31_ID,mgr,100);
inputB.reload(StatsTestsQ31::INPUTNEW2_Q31_ID,mgr,100);
ref.reload(StatsTestsQ31::MSE_Q31_ID,mgr);
output.create(1,StatsTestsQ31::OUT_Q31_ID,mgr);
refOffset = 3;
}
break;
}
}
void StatsTestsQ31::tearDown(Testing::testID_t id,Client::PatternMgr *mgr)
{
(void)id;
switch(id)
{
case StatsTestsQ31::TEST_MAX_Q31_1:
case StatsTestsQ31::TEST_MAX_Q31_2:
case StatsTestsQ31::TEST_MAX_Q31_3:
index.dump(mgr);
output.dump(mgr);
break;
case TEST_POWER_Q31_10:
case TEST_POWER_Q31_11:
case TEST_POWER_Q31_12:
outputPower.dump(mgr);
break;
default:
output.dump(mgr);
}
}
|
/**
* Team Antelope, Sprint Otono
*
* @file SQLExec.cpp - implementation of SQLExec class
* @author Kevin Lundeen
* @author Lili Hao
* @author Jara Lindsay
* @author Bryn Lasher
* @see "Seattle University, CPSC5300, Spring 2021"
*/
#include "SQLExec.h"
using namespace std;
using namespace hsql;
// define static data
Tables *SQLExec::tables = nullptr;
/**
* Makes the query result printable
* @param out Ostream
* @param qres the QueryResult to print
* @return out Ostream
*/
ostream &operator<<(ostream &out, const QueryResult &qres) {
if (qres.column_names != nullptr) {
for (auto const &column_name: *qres.column_names)
out << column_name << " ";
out << endl << "+";
for (unsigned int i = 0; i < qres.column_names->size(); i++)
out << "----------+";
out << endl;
for (auto const &row: *qres.rows) {
for (auto const &column_name: *qres.column_names) {
Value value = row->at(column_name);
switch (value.data_type) {
case ColumnAttribute::INT:
out << value.n;
break;
case ColumnAttribute::TEXT:
out << "\"" << value.s << "\"";
break;
case ColumnAttribute::BOOLEAN:
out << (value.n == 0 ? "false" : "true");
break;
default:
out << "???";
}
out << " ";
}
out << endl;
}
}
out << qres.message;
return out;
}
/**
* Destructor
*/
QueryResult::~QueryResult() {
if (column_names != nullptr)
delete column_names;
if (column_attributes != nullptr)
delete column_attributes;
if (rows != nullptr) {
for (auto row: *rows)
delete row;
delete rows;
}
}
/**
* Execute the given SQL statement.
* @param statement the Hyrise AST of the SQL statement to execute
* @returns the query result (freed by caller)
*/
QueryResult *SQLExec::execute(const SQLStatement *statement) {
// initialize _tables table, if not yet present
if (SQLExec::tables == nullptr)
SQLExec::tables = new Tables();
try {
switch (statement->type()) {
case kStmtCreate:
return create((const CreateStatement *) statement);
case kStmtDrop:
return drop((const DropStatement *) statement);
case kStmtShow:
return show((const ShowStatement *) statement);
default:
return new QueryResult("not implemented");
}
} catch (DbRelationError &e) {
throw SQLExecError(string("DbRelationError: ") + e.what());
}
}
/**
* Pull out column name and attributes from AST's column definition clause.
* @param col AST column definition
* @param column_name returned by reference
* @param column_attributes returned by reference
*/
void
SQLExec::column_definition(const ColumnDefinition *col, Identifier &column_name, ColumnAttribute &column_attribute) {
column_name = col->name;
switch (col->type) {
case ColumnDefinition::INT:
column_attribute.set_data_type(ColumnAttribute::INT);
break;
case ColumnDefinition::TEXT:
column_attribute.set_data_type(ColumnAttribute::TEXT);
break;
case ColumnDefinition::DOUBLE:
default:
throw SQLExecError("unrecognized data type");
}
}
/**
* Create a new table or index.
* @param statement The table or index to create
* @return QueryResult The result of the create query
*/
QueryResult *SQLExec::create(const CreateStatement *statement) {
switch (statement->type) {
case CreateStatement::kTable:
return create_table(statement);
case CreateStatement::kIndex:
return create_index(statement);
default:
return new QueryResult("Only CREATE TABLE and CREATE INDEX are implemented");
}
}
/**
* Create a new table.
* @param statement The table to create
* @return QueryResult The result of the query
*/
QueryResult *SQLExec::create_table(const CreateStatement *statement) {
Identifier table_name = statement->tableName;
ColumnNames column_names;
ColumnAttributes column_attributes;
Identifier column_name;
ColumnAttribute column_attribute;
for (ColumnDefinition *col : *statement->columns) {
column_definition(col, column_name, column_attribute);
column_names.push_back(column_name);
column_attributes.push_back(column_attribute);
}
// Add to schema: _tables and _columns
ValueDict row;
row["table_name"] = table_name;
Handle t_handle = SQLExec::tables->insert(&row); // Insert into _tables
try {
Handles c_handles;
DbRelation &columns = SQLExec::tables->get_table(Columns::TABLE_NAME);
try {
for (uint i = 0; i < column_names.size(); i++) {
row["column_name"] = column_names[i];
row["data_type"] = Value(column_attributes[i].get_data_type() == ColumnAttribute::INT ? "INT" : "TEXT");
c_handles.push_back(columns.insert(&row)); // Insert into _columns
}
// Finally, actually create the relation
DbRelation &table = SQLExec::tables->get_table(table_name);
if (statement->ifNotExists)
table.create_if_not_exists();
else
table.create();
} catch (exception &e) {
// attempt to remove from _columns
try {
for (auto const &handle: c_handles)
columns.del(handle);
} catch (...) {}
throw;
}
} catch (exception &e) {
try {
// attempt to remove from _tables
SQLExec::tables->del(t_handle);
} catch (...) {}
throw;
}
return new QueryResult("created " + table_name);
}
/**
* Create a new index.
* @param statement The statement with a table to create the index for
* @return QueryResult The result of the create index query
*/
QueryResult *SQLExec::create_index(const CreateStatement *statement) {
// get the table name and index name from statement
Identifier table_name = statement->tableName;
Identifier index_name = statement->indexName;
Identifier index_type = statement->indexType;
//ColumnNames column_names;
//ColumnAttributes column_attributes;
Identifier column_name;
//ColumnAttribute column_attribute;
// Add to schema: _indices
ValueDict row;
row["table_name"] = table_name;
row["index_name"] = index_name;
row["index_type"] = index_type;
if (index_type == "BTREE") {
row["is_unique"] = Value(true);
} else {
row["is_unique"] = Value(false);
}
uint16_t idx = 0;
row["seq_in_index"] = Value(idx);
DbRelation &indices = SQLExec::tables->get_table(Indices::TABLE_NAME);
// check if the index on given table already created
// DbIndex *index = SQLExec::indices->get_index(table_name, index_name);
ValueDict where;
where["table_name"] = Value(table_name);
where["index_name"] = Value(index_name);
Handles *handles = indices.select(&where);
// the number of returned matching rows
u_long n = handles->size();
if (n > 0) {
delete handles;
//delete &where;
//delete &row;
return new QueryResult("Error: DbRelationError: duplicate index " + table_name);
}
//Handles i_handles;
for (auto const *col : *statement->indexColumns) {
row["column_name"] = Value(col);
// increase idx
idx += 1;
row["seq_in_index"] = Value(idx);
handles->push_back(indices.insert(&row)); // Insert into _indices
}
delete handles;
return new QueryResult("created index " + index_name);
}
/**
* Drop the specified table or index.
* @param statement The table or index to drop
* @return QueryResult The result of the drop query
*/
QueryResult *SQLExec::drop(const DropStatement *statement) {
switch (statement->type) {
case DropStatement::kTable:
return drop_table(statement);
case DropStatement::kIndex:
return drop_index(statement);
default:
return new QueryResult("Only DROP TABLE and DROP INDEX are implemented");
}
}
/**
* Drop the specified table.
* @param statement Table to drop
* @return QueryResult The result of the drop query
*/
QueryResult *SQLExec::drop_table(const DropStatement *statement) {
Identifier table_name = statement->name;
if (table_name == Tables::TABLE_NAME || table_name == Columns::TABLE_NAME)
throw SQLExecError("cannot drop a schema table");
ValueDict where;
where["table_name"] = Value(table_name);
// get the table
DbRelation &table = SQLExec::tables->get_table(table_name);
// remove from _columns schema
DbRelation &columns = SQLExec::tables->get_table(Columns::TABLE_NAME);
Handles *handles = columns.select(&where);
for (auto const &handle: *handles)
columns.del(handle);
delete handles;
// remove table
table.drop();
// finally, remove from _tables schema
handles = SQLExec::tables->select(&where);
SQLExec::tables->del(*handles->begin()); // expect only one row from select
delete handles;
return new QueryResult(string("dropped ") + table_name);
}
/**
* Drop the index from the table.
* @param statement Index to drop
* @return QueryResult The result of the drop index query
*/
QueryResult *SQLExec::drop_index(const DropStatement *statement) {
Identifier table_name = statement->name;
Identifier index_name = statement->indexName;
if (table_name == Tables::TABLE_NAME || table_name == Columns::TABLE_NAME || table_name == Indices::TABLE_NAME)
throw SQLExecError("cannot drop index for schema table");
// the query filter
ValueDict where;
where["table_name"] = Value(table_name);
where["index_name"] = Value(index_name);
// remove from _indices schema
DbRelation &indices = SQLExec::tables->get_table(Indices::TABLE_NAME);
Handles *i_handles = indices.select(&where);
for (auto const &handle: *i_handles)
indices.del(handle);
delete i_handles;
return new QueryResult(string("dropped index ") + index_name);
}
/**
* Show tables or columns.
* @param statement Item to show
* @return QueryResult The result of the show query
*/
QueryResult *SQLExec::show(const ShowStatement *statement) {
switch (statement->type) {
case ShowStatement::kTables:
return show_tables();
case ShowStatement::kColumns:
return show_columns(statement);
case ShowStatement::kIndex:
return show_index(statement);
default:
throw SQLExecError("unrecognized SHOW type");
}
}
/**
* Show the index from the table.
* @param statement Index to show
* @return QueryResult The result of the show index query
*/
QueryResult *SQLExec::show_index(const ShowStatement *statement) {
Identifier table_name = statement->tableName;
ColumnNames *column_names = new ColumnNames;
column_names->push_back("table_name");
column_names->push_back("index_name");
column_names->push_back("column_name");
column_names->push_back("seq_in_index");
column_names->push_back("index_type");
column_names->push_back("is_unique");
ColumnAttributes *column_attributes = new ColumnAttributes;
column_attributes->push_back(ColumnAttribute(ColumnAttribute::TEXT));
DbRelation &indices = SQLExec::tables->get_table(Indices::TABLE_NAME);
ValueDict where;
where["table_name"] = Value(table_name);
Handles *i_handles = indices.select(&where);
u_long n = i_handles->size();
ValueDicts *rows = new ValueDicts;
for (auto const &handle: *i_handles) {
ValueDict *row = indices.project(handle, column_names);
rows->push_back(row);
}
delete i_handles;
string ret("successfully returned ");
ret += to_string(n);
ret += " rows";
return new QueryResult(column_names, column_attributes, rows, ret);
}
/**
* Show all current tables.
* @return QueryResult The result of the show tables query
*/
QueryResult *SQLExec::show_tables() {
ColumnNames *column_names = new ColumnNames;
column_names->push_back("table_name");
ColumnAttributes *column_attributes = new ColumnAttributes;
column_attributes->push_back(ColumnAttribute(ColumnAttribute::TEXT));
Handles *handles = SQLExec::tables->select();
u_long n = handles->size() - 3;
ValueDicts *rows = new ValueDicts;
for (auto const &handle: *handles) {
ValueDict *row = SQLExec::tables->project(handle, column_names);
Identifier table_name = row->at("table_name").s;
if (table_name != Tables::TABLE_NAME && table_name != Columns::TABLE_NAME && table_name != Indices::TABLE_NAME)
rows->push_back(row);
else
delete row;
}
delete handles;
return new QueryResult(column_names, column_attributes, rows, "successfully returned " + to_string(n) + " rows");
}
/**
* Shows all current columns.
* @param statement The columns to show
* @return QueryResult The result of the show columns query
*/
QueryResult *SQLExec::show_columns(const ShowStatement *statement) {
DbRelation &columns = SQLExec::tables->get_table(Columns::TABLE_NAME);
ColumnNames *column_names = new ColumnNames;
column_names->push_back("table_name");
column_names->push_back("column_name");
column_names->push_back("data_type");
ColumnAttributes *column_attributes = new ColumnAttributes;
column_attributes->push_back(ColumnAttribute(ColumnAttribute::TEXT));
ValueDict where;
where["table_name"] = Value(statement->tableName);
Handles *handles = columns.select(&where);
u_long n = handles->size();
ValueDicts *rows = new ValueDicts;
for (auto const &handle: *handles) {
ValueDict *row = columns.project(handle, column_names);
rows->push_back(row);
}
delete handles;
return new QueryResult(column_names, column_attributes, rows, "successfully returned " + to_string(n) + " rows");
}
|
/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: wrap_itkBinaryBallStructuringElement.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "itkBinaryBallStructuringElement.h"
#ifdef CABLE_CONFIGURATION
#include "itkCSwigMacros.h"
#include "itkCSwigBinaryBallStructuringElement.h"
namespace _cable_
{
const char* const group = ITK_WRAP_GROUP(itkBinaryBallStructuringElement);
namespace wrappers
{
typedef structuringElement::F2 itkBinaryBallStructuringElementF2;
typedef structuringElement::F3 itkBinaryBallStructuringElementF3;
typedef structuringElement::UC2 itkBinaryBallStructuringElementUC2;
typedef structuringElement::UC3 itkBinaryBallStructuringElementUC3;
typedef structuringElement::US2 itkBinaryBallStructuringElementUS2;
typedef structuringElement::US3 itkBinaryBallStructuringElementUS3;
}
}
#endif
|
//===-- DiffEngine.cpp - Structural file comparison -----------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file defines the implementation of the llvm-tapi difference
// engine, which structurally compares two tbd files.
//
//===----------------------------------------------------------------------===/
#include "DiffEngine.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/TextAPI/InterfaceFile.h"
#include "llvm/TextAPI/Symbol.h"
#include "llvm/TextAPI/Target.h"
using namespace llvm;
using namespace MachO;
using namespace object;
StringRef setOrderIndicator(InterfaceInputOrder Order) {
return ((Order == lhs) ? "< " : "> ");
}
// The following template specialization implementations
// need to be explicitly placed into the llvm namespace
// to work around a GCC 4.8 bug.
namespace llvm {
template <typename T, DiffAttrKind U>
inline void DiffScalarVal<T, U>::print(raw_ostream &OS, std::string Indent) {
OS << Indent << "\t" << setOrderIndicator(Order) << Val << "\n";
}
template <>
inline void
DiffScalarVal<StringRef, AD_Diff_Scalar_Str>::print(raw_ostream &OS,
std::string Indent) {
OS << Indent << "\t\t" << setOrderIndicator(Order) << Val << "\n";
}
template <>
inline void
DiffScalarVal<uint8_t, AD_Diff_Scalar_Unsigned>::print(raw_ostream &OS,
std::string Indent) {
OS << Indent << "\t" << setOrderIndicator(Order) << std::to_string(Val)
<< "\n";
}
template <>
inline void
DiffScalarVal<bool, AD_Diff_Scalar_Bool>::print(raw_ostream &OS,
std::string Indent) {
OS << Indent << "\t" << setOrderIndicator(Order)
<< ((Val == true) ? "true" : "false") << "\n";
}
} // end namespace llvm
StringLiteral SymScalar::getSymbolNamePrefix(MachO::SymbolKind Kind) {
switch (Kind) {
case MachO::SymbolKind::GlobalSymbol:
return StringLiteral("");
case MachO::SymbolKind::ObjectiveCClass:
return ObjC2MetaClassNamePrefix;
case MachO::SymbolKind ::ObjectiveCClassEHType:
return ObjC2EHTypePrefix;
case MachO::SymbolKind ::ObjectiveCInstanceVariable:
return ObjC2IVarPrefix;
}
llvm_unreachable("Unknown llvm::MachO::SymbolKind enum");
}
std::string SymScalar::stringifySymbolFlag(MachO::SymbolFlags Flag) {
switch (Flag) {
case MachO::SymbolFlags::None:
return "";
case MachO::SymbolFlags::ThreadLocalValue:
return "Thread-Local";
case MachO::SymbolFlags::WeakDefined:
return "Weak-Defined";
case MachO::SymbolFlags::WeakReferenced:
return "Weak-Referenced";
case MachO::SymbolFlags::Undefined:
return "Undefined";
case MachO::SymbolFlags::Rexported:
return "Reexported";
}
llvm_unreachable("Unknown llvm::MachO::SymbolFlags enum");
}
void SymScalar::print(raw_ostream &OS, std::string Indent, MachO::Target Targ) {
if (Val->getKind() == MachO::SymbolKind::ObjectiveCClass) {
if (Targ.Arch == MachO::AK_i386 &&
Targ.Platform == MachO::PlatformKind::macOS) {
OS << Indent << "\t\t" << ((Order == lhs) ? "< " : "> ")
<< ObjC1ClassNamePrefix << Val->getName()
<< getFlagString(Val->getFlags()) << "\n";
return;
}
OS << Indent << "\t\t" << ((Order == lhs) ? "< " : "> ")
<< ObjC2ClassNamePrefix << Val->getName()
<< getFlagString(Val->getFlags()) << "\n";
}
OS << Indent << "\t\t" << ((Order == lhs) ? "< " : "> ")
<< getSymbolNamePrefix(Val->getKind()) << Val->getName()
<< getFlagString(Val->getFlags()) << "\n";
}
bool checkSymbolEquality(llvm::MachO::InterfaceFile::const_symbol_range LHS,
llvm::MachO::InterfaceFile::const_symbol_range RHS) {
return std::equal(LHS.begin(), LHS.end(), RHS.begin(),
[&](auto LHS, auto RHS) { return *LHS == *RHS; });
}
template <typename TargetVecT, typename ValTypeT, typename V>
void addDiffForTargSlice(V Val, Target Targ, DiffOutput &Diff,
InterfaceInputOrder Order) {
auto TargetVector = llvm::find_if(
Diff.Values, [&](const std::unique_ptr<AttributeDiff> &RawTVec) {
if (TargetVecT *TVec = dyn_cast<TargetVecT>(RawTVec.get()))
return TVec->Targ == Targ;
return false;
});
if (TargetVector != Diff.Values.end()) {
ValTypeT NewVal(Order, Val);
cast<TargetVecT>(TargetVector->get())->TargValues.push_back(NewVal);
} else {
auto NewTargetVec = std::make_unique<TargetVecT>(Targ);
ValTypeT NewVal(Order, Val);
NewTargetVec->TargValues.push_back(NewVal);
Diff.Values.push_back(std::move(NewTargetVec));
}
}
DiffOutput getSingleAttrDiff(const std::vector<InterfaceFileRef> &IRefVec,
std::string Name, InterfaceInputOrder Order) {
DiffOutput Diff(Name);
Diff.Kind = AD_Str_Vec;
for (const auto &IRef : IRefVec)
for (auto Targ : IRef.targets())
addDiffForTargSlice<DiffStrVec,
DiffScalarVal<StringRef, AD_Diff_Scalar_Str>>(
IRef.getInstallName(), Targ, Diff, Order);
return Diff;
}
DiffOutput
getSingleAttrDiff(const std::vector<std::pair<Target, std::string>> &PairVec,
std::string Name, InterfaceInputOrder Order) {
DiffOutput Diff(Name);
Diff.Kind = AD_Str_Vec;
for (const auto &Pair : PairVec)
addDiffForTargSlice<DiffStrVec,
DiffScalarVal<StringRef, AD_Diff_Scalar_Str>>(
StringRef(Pair.second), Pair.first, Diff, Order);
return Diff;
}
DiffOutput getSingleAttrDiff(InterfaceFile::const_symbol_range SymRange,
std::string Name, InterfaceInputOrder Order) {
DiffOutput Diff(Name);
Diff.Kind = AD_Sym_Vec;
for (const auto *Sym : SymRange)
for (auto Targ : Sym->targets())
addDiffForTargSlice<DiffSymVec, SymScalar>(Sym, Targ, Diff, Order);
return Diff;
}
template <typename T>
DiffOutput getSingleAttrDiff(T SingleAttr, std::string Attribute) {
DiffOutput Diff(Attribute);
Diff.Kind = SingleAttr.getKind();
Diff.Values.push_back(std::make_unique<T>(SingleAttr));
return Diff;
}
template <typename T, DiffAttrKind U>
void diffAttribute(std::string Name, std::vector<DiffOutput> &Output,
DiffScalarVal<T, U> Attr) {
Output.push_back(getSingleAttrDiff(Attr, Name));
}
template <typename T>
void diffAttribute(std::string Name, std::vector<DiffOutput> &Output,
const T &Val, InterfaceInputOrder Order) {
Output.push_back(getSingleAttrDiff(Val, Name, Order));
}
std::vector<DiffOutput> getSingleIF(InterfaceFile *Interface,
InterfaceInputOrder Order) {
std::vector<DiffOutput> Output;
diffAttribute("Install Name", Output,
DiffScalarVal<StringRef, AD_Diff_Scalar_Str>(
Order, Interface->getInstallName()));
diffAttribute("Current Version", Output,
DiffScalarVal<PackedVersion, AD_Diff_Scalar_PackedVersion>(
Order, Interface->getCurrentVersion()));
diffAttribute("Compatibility Version", Output,
DiffScalarVal<PackedVersion, AD_Diff_Scalar_PackedVersion>(
Order, Interface->getCompatibilityVersion()));
diffAttribute("Swift ABI Version", Output,
DiffScalarVal<uint8_t, AD_Diff_Scalar_Unsigned>(
Order, Interface->getSwiftABIVersion()));
diffAttribute("InstallAPI", Output,
DiffScalarVal<bool, AD_Diff_Scalar_Bool>(
Order, Interface->isInstallAPI()));
diffAttribute("Two Level Namespace", Output,
DiffScalarVal<bool, AD_Diff_Scalar_Bool>(
Order, Interface->isTwoLevelNamespace()));
diffAttribute("Application Extension Safe", Output,
DiffScalarVal<bool, AD_Diff_Scalar_Bool>(
Order, Interface->isApplicationExtensionSafe()));
diffAttribute("Reexported Libraries", Output,
Interface->reexportedLibraries(), Order);
diffAttribute("Allowable Clients", Output, Interface->allowableClients(),
Order);
diffAttribute("Parent Umbrellas", Output, Interface->umbrellas(), Order);
diffAttribute("Symbols", Output, Interface->symbols(), Order);
for (auto Doc : Interface->documents()) {
DiffOutput Documents("Inlined Reexported Frameworks/Libraries");
Documents.Kind = AD_Inline_Doc;
Documents.Values.push_back(std::make_unique<InlineDoc>(
InlineDoc(Doc->getInstallName(), getSingleIF(Doc.get(), Order))));
Output.push_back(std::move(Documents));
}
return Output;
}
void findAndAddDiff(const std::vector<InterfaceFileRef> &CollectedIRefVec,
const std::vector<InterfaceFileRef> &LookupIRefVec,
DiffOutput &Result, InterfaceInputOrder Order) {
Result.Kind = AD_Str_Vec;
for (const auto &IRef : CollectedIRefVec)
for (auto Targ : IRef.targets()) {
auto FoundIRef = llvm::find_if(LookupIRefVec, [&](const auto LIRef) {
auto FoundTarg = llvm::find(LIRef.targets(), Targ);
return (FoundTarg != LIRef.targets().end() &&
IRef.getInstallName() == LIRef.getInstallName());
});
if (FoundIRef == LookupIRefVec.end())
addDiffForTargSlice<DiffStrVec,
DiffScalarVal<StringRef, AD_Diff_Scalar_Str>>(
IRef.getInstallName(), Targ, Result, Order);
}
}
void findAndAddDiff(
const std::vector<std::pair<Target, std::string>> &CollectedPairs,
const std::vector<std::pair<Target, std::string>> &LookupPairs,
DiffOutput &Result, InterfaceInputOrder Order) {
Result.Kind = AD_Str_Vec;
for (const auto &Pair : CollectedPairs) {
auto FoundPair = llvm::find(LookupPairs, Pair);
if (FoundPair == LookupPairs.end())
addDiffForTargSlice<DiffStrVec,
DiffScalarVal<StringRef, AD_Diff_Scalar_Str>>(
StringRef(Pair.second), Pair.first, Result, Order);
}
}
void findAndAddDiff(InterfaceFile::const_symbol_range CollectedSyms,
InterfaceFile::const_symbol_range LookupSyms,
DiffOutput &Result, InterfaceInputOrder Order) {
Result.Kind = AD_Sym_Vec;
for (const auto *Sym : CollectedSyms)
for (const auto Targ : Sym->targets()) {
auto FoundSym = llvm::find_if(LookupSyms, [&](const auto LSym) {
auto FoundTarg = llvm::find(LSym->targets(), Targ);
return (Sym->getName() == LSym->getName() &&
Sym->getKind() == LSym->getKind() &&
Sym->getFlags() == LSym->getFlags() &&
FoundTarg != LSym->targets().end());
});
if (FoundSym == LookupSyms.end())
addDiffForTargSlice<DiffSymVec, SymScalar>(Sym, Targ, Result, Order);
}
}
template <typename T>
DiffOutput recordDifferences(T LHS, T RHS, std::string Attr) {
DiffOutput Diff(Attr);
if (LHS.getKind() == RHS.getKind()) {
Diff.Kind = LHS.getKind();
Diff.Values.push_back(std::make_unique<T>(LHS));
Diff.Values.push_back(std::make_unique<T>(RHS));
}
return Diff;
}
template <typename T>
DiffOutput recordDifferences(const std::vector<T> &LHS,
const std::vector<T> &RHS, std::string Attr) {
DiffOutput Diff(Attr);
Diff.Kind = AD_Str_Vec;
findAndAddDiff(LHS, RHS, Diff, lhs);
findAndAddDiff(RHS, LHS, Diff, rhs);
return Diff;
}
DiffOutput recordDifferences(llvm::MachO::InterfaceFile::const_symbol_range LHS,
llvm::MachO::InterfaceFile::const_symbol_range RHS,
std::string Attr) {
DiffOutput Diff(Attr);
Diff.Kind = AD_Sym_Vec;
findAndAddDiff(LHS, RHS, Diff, lhs);
findAndAddDiff(RHS, LHS, Diff, rhs);
return Diff;
}
std::vector<DiffOutput>
DiffEngine::findDifferences(const InterfaceFile *IFLHS,
const InterfaceFile *IFRHS) {
std::vector<DiffOutput> Output;
if (IFLHS->getInstallName() != IFRHS->getInstallName())
Output.push_back(recordDifferences(
DiffScalarVal<StringRef, AD_Diff_Scalar_Str>(lhs,
IFLHS->getInstallName()),
DiffScalarVal<StringRef, AD_Diff_Scalar_Str>(rhs,
IFRHS->getInstallName()),
"Install Name"));
if (IFLHS->getCurrentVersion() != IFRHS->getCurrentVersion())
Output.push_back(recordDifferences(
DiffScalarVal<PackedVersion, AD_Diff_Scalar_PackedVersion>(
lhs, IFLHS->getCurrentVersion()),
DiffScalarVal<PackedVersion, AD_Diff_Scalar_PackedVersion>(
rhs, IFRHS->getCurrentVersion()),
"Current Version"));
if (IFLHS->getCompatibilityVersion() != IFRHS->getCompatibilityVersion())
Output.push_back(recordDifferences(
DiffScalarVal<PackedVersion, AD_Diff_Scalar_PackedVersion>(
lhs, IFLHS->getCompatibilityVersion()),
DiffScalarVal<PackedVersion, AD_Diff_Scalar_PackedVersion>(
rhs, IFRHS->getCompatibilityVersion()),
"Compatibility Version"));
if (IFLHS->getSwiftABIVersion() != IFRHS->getSwiftABIVersion())
Output.push_back(
recordDifferences(DiffScalarVal<uint8_t, AD_Diff_Scalar_Unsigned>(
lhs, IFLHS->getSwiftABIVersion()),
DiffScalarVal<uint8_t, AD_Diff_Scalar_Unsigned>(
rhs, IFRHS->getSwiftABIVersion()),
"Swift ABI Version"));
if (IFLHS->isInstallAPI() != IFRHS->isInstallAPI())
Output.push_back(recordDifferences(
DiffScalarVal<bool, AD_Diff_Scalar_Bool>(lhs, IFLHS->isInstallAPI()),
DiffScalarVal<bool, AD_Diff_Scalar_Bool>(rhs, IFRHS->isInstallAPI()),
"InstallAPI"));
if (IFLHS->isTwoLevelNamespace() != IFRHS->isTwoLevelNamespace())
Output.push_back(recordDifferences(DiffScalarVal<bool, AD_Diff_Scalar_Bool>(
lhs, IFLHS->isTwoLevelNamespace()),
DiffScalarVal<bool, AD_Diff_Scalar_Bool>(
rhs, IFRHS->isTwoLevelNamespace()),
"Two Level Namespace"));
if (IFLHS->isApplicationExtensionSafe() !=
IFRHS->isApplicationExtensionSafe())
Output.push_back(
recordDifferences(DiffScalarVal<bool, AD_Diff_Scalar_Bool>(
lhs, IFLHS->isApplicationExtensionSafe()),
DiffScalarVal<bool, AD_Diff_Scalar_Bool>(
rhs, IFRHS->isApplicationExtensionSafe()),
"Application Extension Safe"));
if (IFLHS->reexportedLibraries() != IFRHS->reexportedLibraries())
Output.push_back(recordDifferences(IFLHS->reexportedLibraries(),
IFRHS->reexportedLibraries(),
"Reexported Libraries"));
if (IFLHS->allowableClients() != IFRHS->allowableClients())
Output.push_back(recordDifferences(IFLHS->allowableClients(),
IFRHS->allowableClients(),
"Allowable Clients"));
if (IFLHS->umbrellas() != IFRHS->umbrellas())
Output.push_back(recordDifferences(IFLHS->umbrellas(), IFRHS->umbrellas(),
"Parent Umbrellas"));
if (!checkSymbolEquality(IFLHS->symbols(), IFRHS->symbols()))
Output.push_back(
recordDifferences(IFLHS->symbols(), IFRHS->symbols(), "Symbols"));
if (IFLHS->documents() != IFRHS->documents()) {
DiffOutput Docs("Inlined Reexported Frameworks/Libraries");
Docs.Kind = AD_Inline_Doc;
std::vector<StringRef> DocsInserted;
// Iterate through inline frameworks/libraries from interface file and find
// match based on install name.
for (auto DocLHS : IFLHS->documents()) {
auto Pair = llvm::find_if(IFRHS->documents(), [&](const auto &DocRHS) {
return (DocLHS->getInstallName() == DocRHS->getInstallName());
});
// If a match found, recursively get differences between the pair.
if (Pair != IFRHS->documents().end()) {
InlineDoc PairDiff =
InlineDoc(DocLHS->getInstallName(),
findDifferences(DocLHS.get(), Pair->get()));
if (!PairDiff.DocValues.empty())
Docs.Values.push_back(
std::make_unique<InlineDoc>(std::move(PairDiff)));
}
// If a match is not found, get attributes from single item.
else
Docs.Values.push_back(std::make_unique<InlineDoc>(InlineDoc(
DocLHS->getInstallName(), getSingleIF(DocLHS.get(), lhs))));
DocsInserted.push_back(DocLHS->getInstallName());
}
for (auto DocRHS : IFRHS->documents()) {
auto WasGathered =
llvm::find_if(DocsInserted, [&](const auto &GatheredDoc) {
return (GatheredDoc == DocRHS->getInstallName());
});
if (WasGathered == DocsInserted.end())
Docs.Values.push_back(std::make_unique<InlineDoc>(InlineDoc(
DocRHS->getInstallName(), getSingleIF(DocRHS.get(), rhs))));
}
if (!Docs.Values.empty())
Output.push_back(std::move(Docs));
}
return Output;
}
template <typename T>
void printSingleVal(std::string Indent, const DiffOutput &Attr,
raw_ostream &OS) {
if (Attr.Values.empty())
return;
OS << Indent << Attr.Name << "\n";
for (auto &RawItem : Attr.Values)
if (T *Item = dyn_cast<T>(RawItem.get()))
Item->print(OS, Indent);
}
template <typename T>
T *castValues(const std::unique_ptr<AttributeDiff> &RawAttr) {
T *CastAttr = cast<T>(RawAttr.get());
return CastAttr;
}
template <typename T> void sortTargetValues(std::vector<T> &TargValues) {
llvm::stable_sort(TargValues, [](const auto &ValA, const auto &ValB) {
return ValA.getOrder() < ValB.getOrder();
});
llvm::stable_sort(TargValues, [](const auto &ValA, const auto &ValB) {
return ValA.getOrder() == ValB.getOrder() && ValA.getVal() < ValB.getVal();
});
}
template <typename T>
void printVecVal(std::string Indent, const DiffOutput &Attr, raw_ostream &OS) {
if (Attr.Values.empty())
return;
OS << Indent << Attr.Name << "\n";
std::vector<T *> SortedAttrs;
llvm::transform(Attr.Values, std::back_inserter(SortedAttrs), castValues<T>);
llvm::sort(SortedAttrs, [&](const auto &ValA, const auto &ValB) {
return ValA->Targ < ValB->Targ;
});
for (auto *Vec : SortedAttrs) {
sortTargetValues<DiffScalarVal<StringRef, AD_Diff_Scalar_Str>>(
Vec->TargValues);
OS << Indent << "\t" << getTargetTripleName(Vec->Targ) << "\n";
for (auto &Item : Vec->TargValues)
Item.print(OS, Indent);
}
}
template <>
void printVecVal<DiffSymVec>(std::string Indent, const DiffOutput &Attr,
raw_ostream &OS) {
if (Attr.Values.empty())
return;
OS << Indent << Attr.Name << "\n";
std::vector<DiffSymVec *> SortedAttrs;
llvm::transform(Attr.Values, std::back_inserter(SortedAttrs),
castValues<DiffSymVec>);
llvm::sort(SortedAttrs, [&](const auto &ValA, const auto &ValB) {
return ValA->Targ < ValB->Targ;
});
for (auto *SymVec : SortedAttrs) {
sortTargetValues<SymScalar>(SymVec->TargValues);
OS << Indent << "\t" << getTargetTripleName(SymVec->Targ) << "\n";
for (auto &Item : SymVec->TargValues)
Item.print(OS, Indent, SymVec->Targ);
}
}
void DiffEngine::printDifferences(raw_ostream &OS,
const std::vector<DiffOutput> &Diffs,
int IndentCounter) {
std::string Indent = std::string(IndentCounter, '\t');
for (auto &Attr : Diffs) {
switch (Attr.Kind) {
case AD_Diff_Scalar_Str:
if (IndentCounter == 0)
printSingleVal<DiffScalarVal<StringRef, AD_Diff_Scalar_Str>>(Indent,
Attr, OS);
break;
case AD_Diff_Scalar_PackedVersion:
printSingleVal<
DiffScalarVal<PackedVersion, AD_Diff_Scalar_PackedVersion>>(Indent,
Attr, OS);
break;
case AD_Diff_Scalar_Unsigned:
printSingleVal<DiffScalarVal<uint8_t, AD_Diff_Scalar_Unsigned>>(Indent,
Attr, OS);
break;
case AD_Diff_Scalar_Bool:
printSingleVal<DiffScalarVal<bool, AD_Diff_Scalar_Bool>>(Indent, Attr,
OS);
break;
case AD_Str_Vec:
printVecVal<DiffStrVec>(Indent, Attr, OS);
break;
case AD_Sym_Vec:
printVecVal<DiffSymVec>(Indent, Attr, OS);
break;
case AD_Inline_Doc:
if (!Attr.Values.empty()) {
OS << Indent << Attr.Name << "\n";
for (auto &Item : Attr.Values)
if (InlineDoc *Doc = dyn_cast<InlineDoc>(Item.get()))
if (!Doc->DocValues.empty()) {
OS << Indent << "\t" << Doc->InstallName << "\n";
printDifferences(OS, std::move(Doc->DocValues), 2);
}
}
break;
}
}
}
bool DiffEngine::compareFiles(raw_ostream &OS) {
const auto *IFLHS = &(FileLHS->getInterfaceFile());
const auto *IFRHS = &(FileRHS->getInterfaceFile());
if (*IFLHS == *IFRHS)
return false;
OS << "< " << std::string(IFLHS->getPath().data()) << "\n> "
<< std::string(IFRHS->getPath().data()) << "\n\n";
std::vector<DiffOutput> Diffs = findDifferences(IFLHS, IFRHS);
printDifferences(OS, Diffs, 0);
return true;
}
|
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <windows.h>
#include <conio.h>
#include <ctime>
#include <cstdlib>
using namespace std;
typedef struct user
{
string firstname;
string lastname;
string username;
string password;
} User;
// directly encrypts using a simple algorithm
void encrypt(string &str, int key)
{
int len = str.size();
for (int i = 0; i < len; i++)
{
if (i % 2 == 0)
{
str[i] = (char) (str[i] + key);
}
else
{
str[i] = (char) (str[i] + len);
}
}
}
// returns decrypted version of the string using the reverse algorithm
string decrypt(string str, int key)
{
string out = str;
int len = str.size();
for (int i = 0; i < len; i++)
{
if (i % 2 == 0)
{
out[i] = (char) (out[i] - key);
}
else
{
out[i] = (char) (out[i] - len);
}
}
return out;
}
/*
* splits a long string into pieces with delimiter
* returns the vector array of seperated strings
*/
vector<string> split(string str, char dl)
{
string word = "";
vector<string> substr_list;
// adding delimiter at the end of the string
str = str + dl;
int l = str.size();
// traversing 'str' from left to right
for (int i = 0; i < l; i++)
{
// adding character when no delimiter is spotted
if (str[i] != dl)
word = word + str[i];
else
{
// push the word to array if not empty
if ((int)word.size() != 0)
substr_list.push_back(word);
// reset the word after pushing it to array
word = "";
}
}
return substr_list;
}
/*
* Scans the database file to find the user
* shows information about the user
*/
void show_user_info(string userID)
{
string buffer, temp;
// reading the database file
ifstream database("database03.txt");
if (!database)
{
cout << "Error: Can't access log file!" << endl;
exit(0);
}
// scanning the file to find the user
while (getline(database, temp))
{
buffer = split(temp, ',')[0];
if (userID == buffer)
{
system("cls");
cout << "Name: ";
cout << split(temp, ',')[1] << " " << split(temp, ',')[2]<< endl;
cout << "Username: @" << userID << endl;
return;
}
}
database.close();
cout << "Didn't find any info for @" << userID << endl;
}
/*
* Scans the content file avialable
* prints the content to the stdout
*/
void show_content()
{
string buffer;
// reading the content file
ifstream content("content.txt");
if (!content)
{
cout << "Error: Can't access content file." << endl;
exit(0);
}
// printing the content of the file
system("cls");
while (getline(content, buffer))
{
cout << buffer << endl;
}
content.close();
}
/*
* Reads login data from database
* takes input from user
* reads password and key from the database
* decrypts the password with the key and compares
* it recurses until a successful login
*/
void login()
{
string buffer, temp;
User person;
// reading log file
ifstream log("database03.txt");
if (!log)
{
cout << "Can't access log file!" << endl;
exit(0);
}
// taking inputs from the user
cout << "LOGIN HERE ---------- " << endl;
cout << "Username: ";
cin >> person.username;
cout << "Password: ";
cin >> person.password;
// scanning the log file line by line
while (getline(log, temp))
{
// getting the username part
buffer = split(temp, ',')[0];
if (person.username == buffer)
{
// getting the key
stringstream s_temp(split(temp, ',')[4]);
int k = 0;
s_temp >> k; // string to integer
// getting the decrypted password
buffer = decrypt(split(temp, ',')[3], k);
if (person.password == buffer)
{
system("cls");
cout << "Login Successfull!" << endl;
// showing user details
show_user_info(person.username);
cout << "Press a key to progress..." << endl;
getch();
// showing the content and return
system("cls");
show_content();
return;
}
}
}
log.close(); // closing the file
system("cls");
cout << "Invalid UserID or Password.\n";
// recursing the function for another attempt
login();
}
/*
* Takes user information from stdin
* checks if the user is already exists
* generates a key and encrypts the password
* writes the information to the database
*/
void registration()
{
string buffer, temp;
User person;
// taking inputs from the user
cout << "REGISTER HERE ---------- " << endl;
cout << "Firstname: ";
cin >> person.firstname;
cout << "Lastname: ";
cin >> person.lastname;
cout << "Username: ";
cin >> person.username;
cout << "Password: ";
cin >> person.password;
// reading database
ifstream log_details("database03.txt");
if (!log_details)
{
cout << "Can't access log file!" << endl;
exit(0);
}
// scanning the file to check if the same user exists already
while (getline(log_details, temp))
{
buffer = split(temp, ',')[0];
if (person.username == buffer)
{
system("cls");
cout << "User already exists!" << endl;
// recursing the process for another attempt
registration();
}
}
log_details.close();
// appending to database
ofstream log("database03.txt", ios_base::app);
if (!log)
{
cout << "Can't access log file!" << endl;
exit(0);
}
// writing info into database
log << person.username << ",";
log << person.firstname << ",";
log << person.lastname << ",";
// generating random encrption key
srand(time(0));
int key = 1 + (rand() % 100); // random value from 1 to 100
encrypt(person.password, key);
log << person.password << ",";
log << key << endl;
show_user_info(person.username);
cout << "Registration Successful!" << endl;
log.close();
}
int main()
{
// clearing the terminal
system("cls");
int choice;
cout << "Enter 0 to Login." << endl;
cout << "Enter 1 to Register." << endl;
cin >> choice;
// determining which process to start
if (choice == 0)
login();
else if (choice == 1)
registration();
else
cout << "Your choice was not valid.\n";
// stopping the terminal
system("pause");
return 0;
}
|
/*
* Copyright (C) 2007 Apple Computer, Kevin Ollivier. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "Image.h"
#include "BitmapImage.h"
#include "FloatConversion.h"
#include "FloatRect.h"
#include "GraphicsContext.h"
#include "ImageObserver.h"
#include "NotImplemented.h"
#include "TransformationMatrix.h"
#include <math.h>
#include <stdio.h>
#include <wx/defs.h>
#include <wx/bitmap.h>
#include <wx/dc.h>
#include <wx/dcmemory.h>
#include <wx/dcgraph.h>
#include <wx/graphics.h>
#include <wx/image.h>
#include <wx/thread.h>
namespace WebCore {
// this is in GraphicsContextWx.cpp
int getWxCompositingOperation(CompositeOperator op, bool hasAlpha);
bool FrameData::clear(bool clearMetadata)
{
if (clearMetadata)
m_haveMetadata = false;
if (m_frame) {
delete m_frame;
m_frame = 0;
return true;
}
return false;
}
// ================================================
// Image Class
// ================================================
PassRefPtr<Image> Image::loadPlatformResource(const char *name)
{
// FIXME: We need to have some 'placeholder' graphics for things like missing
// plugins or broken images.
Vector<char> arr;
RefPtr<Image> img = BitmapImage::create();
RefPtr<SharedBuffer> buffer = SharedBuffer::create(arr.data(), arr.size());
img->setData(buffer, true);
return img.release();
}
void BitmapImage::initPlatformData()
{
// FIXME: NYI
}
// Drawing Routines
void BitmapImage::draw(GraphicsContext* ctxt, const FloatRect& dst, const FloatRect& src, ColorSpace styleColorSpace, CompositeOperator op)
{
if (!m_source.initialized())
return;
if (mayFillWithSolidColor()) {
fillWithSolidColor(ctxt, dst, solidColor(), styleColorSpace, op);
return;
}
#if USE(WXGC)
wxGCDC* context = (wxGCDC*)ctxt->platformContext();
wxGraphicsContext* gc = context->GetGraphicsContext();
wxGraphicsBitmap* bitmap = frameAtIndex(m_currentFrame);
#else
wxWindowDC* context = ctxt->platformContext();
wxBitmap* bitmap = frameAtIndex(m_currentFrame);
#endif
startAnimation();
if (!bitmap) // If it's too early we won't have an image yet.
return;
// If we're drawing a sub portion of the image or scaling then create
// a pattern transformation on the image and draw the transformed pattern.
// Test using example site at http://www.meyerweb.com/eric/css/edge/complexspiral/demo.html
// FIXME: NYI
ctxt->save();
// Set the compositing operation.
ctxt->setCompositeOperation(op);
#if USE(WXGC)
float scaleX = src.width() / dst.width();
float scaleY = src.height() / dst.height();
FloatRect adjustedDestRect = dst;
FloatSize selfSize = currentFrameSize();
if (src.size() != selfSize) {
adjustedDestRect.setLocation(FloatPoint(dst.x() - src.x() / scaleX, dst.y() - src.y() / scaleY));
adjustedDestRect.setSize(FloatSize(selfSize.width() / scaleX, selfSize.height() / scaleY));
}
gc->Clip(dst.x(), dst.y(), dst.width(), dst.height());
#if wxCHECK_VERSION(2,9,0)
gc->DrawBitmap(*bitmap, adjustedDestRect.x(), adjustedDestRect.y(), adjustedDestRect.width(), adjustedDestRect.height());
#else
gc->DrawGraphicsBitmap(*bitmap, adjustedDestRect.x(), adjustedDestRect.y(), adjustedDestRect.width(), adjustedDestRect.height());
#endif
#else // USE(WXGC)
IntRect srcIntRect(src);
IntRect dstIntRect(dst);
bool rescaling = false;
if ((dstIntRect.width() != srcIntRect.width()) || (dstIntRect.height() != srcIntRect.height()))
{
rescaling = true;
wxImage img = bitmap->ConvertToImage();
img.Rescale(dstIntRect.width(), dstIntRect.height());
bitmap = new wxBitmap(img);
}
wxMemoryDC mydc;
ASSERT(bitmap->GetRefData());
mydc.SelectObject(*bitmap);
context->Blit((wxCoord)dstIntRect.x(),(wxCoord)dstIntRect.y(), (wxCoord)dstIntRect.width(), (wxCoord)dstIntRect.height(), &mydc,
(wxCoord)srcIntRect.x(), (wxCoord)srcIntRect.y(), wxCOPY, true);
mydc.SelectObject(wxNullBitmap);
// NB: delete is causing crashes during page load, but not during the deletion
// itself. It occurs later on when a valid bitmap created in frameAtIndex
// suddenly becomes invalid after returning. It's possible these errors deal
// with reentrancy and threding problems.
//delete bitmap;
if (rescaling)
{
delete bitmap;
bitmap = NULL;
}
#endif
ctxt->restore();
if (ImageObserver* observer = imageObserver())
observer->didDraw(this);
}
void BitmapImage::drawPattern(GraphicsContext* ctxt, const FloatRect& srcRect, const TransformationMatrix& patternTransform, const FloatPoint& phase, ColorSpace, CompositeOperator, const FloatRect& dstRect)
{
if (!m_source.initialized())
return;
#if USE(WXGC)
wxGCDC* context = (wxGCDC*)ctxt->platformContext();
wxGraphicsBitmap* bitmap = frameAtIndex(m_currentFrame);
#else
wxWindowDC* context = ctxt->platformContext();
wxBitmap* bitmap = frameAtIndex(m_currentFrame);
#endif
if (!bitmap) // If it's too early we won't have an image yet.
return;
ctxt->save();
ctxt->clip(IntRect(dstRect.x(), dstRect.y(), dstRect.width(), dstRect.height()));
float currentW = 0;
float currentH = 0;
#if USE(WXGC)
wxGraphicsContext* gc = context->GetGraphicsContext();
float adjustedX = phase.x() + srcRect.x() *
narrowPrecisionToFloat(patternTransform.a());
float adjustedY = phase.y() + srcRect.y() *
narrowPrecisionToFloat(patternTransform.d());
gc->ConcatTransform(patternTransform);
#else
wxMemoryDC mydc;
mydc.SelectObject(*bitmap);
#endif
wxPoint origin(context->GetDeviceOrigin());
wxSize clientSize(context->GetSize());
while ( currentW < dstRect.width() && currentW < clientSize.x - origin.x ) {
while ( currentH < dstRect.height() && currentH < clientSize.y - origin.y) {
#if USE(WXGC)
#if wxCHECK_VERSION(2,9,0)
gc->DrawBitmap(*bitmap, adjustedX + currentW, adjustedY + currentH, (wxDouble)srcRect.width(), (wxDouble)srcRect.height());
#else
gc->DrawGraphicsBitmap(*bitmap, adjustedX + currentW, adjustedY + currentH, (wxDouble)srcRect.width(), (wxDouble)srcRect.height());
#endif
#else
context->Blit((wxCoord)dstRect.x() + currentW, (wxCoord)dstRect.y() + currentH,
(wxCoord)srcRect.width(), (wxCoord)srcRect.height(), &mydc,
(wxCoord)srcRect.x(), (wxCoord)srcRect.y(), wxCOPY, true);
#endif
currentH += srcRect.height();
}
currentW += srcRect.width();
currentH = 0;
}
ctxt->restore();
#if !USE(WXGC)
mydc.SelectObject(wxNullBitmap);
#endif
// NB: delete is causing crashes during page load, but not during the deletion
// itself. It occurs later on when a valid bitmap created in frameAtIndex
// suddenly becomes invalid after returning. It's possible these errors deal
// with reentrancy and threding problems.
//delete bitmap;
startAnimation();
if (ImageObserver* observer = imageObserver())
observer->didDraw(this);
}
void BitmapImage::checkForSolidColor()
{
m_checkedForSolidColor = true;
}
void BitmapImage::invalidatePlatformData()
{
}
void Image::drawPattern(GraphicsContext*, const FloatRect& srcRect, const TransformationMatrix& patternTransform, const FloatPoint& phase, ColorSpace, CompositeOperator, const FloatRect& destRect)
{
notImplemented();
}
}
|
/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2014 Case Western Reserve University
* Russell C Jackson <rcj33@case.edu>
*
* 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 Case Western Reserve Univeristy, 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.
*
*/
#include <ros/ros.h>
#include <image_transport/image_transport.h>
#include <cv_bridge/cv_bridge.h>
#include <sensor_msgs/image_encodings.h>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <vesselness_image_filter_cpu/vesselness_filter_node_cpu_bw.h>
using namespace cv;
void VesselnessNodeCPUBW::deallocateMem()
{
}
VesselnessNodeCPUBW::VesselnessNodeCPUBW(const char* subscriptionChar,const char* publicationChar):VesselnessNodeBase(subscriptionChar,publicationChar)
{
// initialize the kernels
outputChannels = 1;
initKernels();
setParamServer();
}
void VesselnessNodeCPUBW::initKernels(){
double var(filterParameters.hessProcess.variance);
//Allocate the matrices
gaussKernel_XX =Mat(filterParameters.hessProcess.side,filterParameters.hessProcess.side,CV_32F);
gaussKernel_XY =Mat(filterParameters.hessProcess.side,filterParameters.hessProcess.side,CV_32F);
gaussKernel_YY =Mat(filterParameters.hessProcess.side,filterParameters.hessProcess.side,CV_32F);
int kSizeEnd = (int) (filterParameters.hessProcess.side-1)/2;
for(int ix = -kSizeEnd; ix < kSizeEnd+1; ix++){
for(int iy = -kSizeEnd; iy < kSizeEnd+1; iy++){
float ixD = (float) ix;
float iyD = (float) iy;
gaussKernel_XX.at<float>(iy+kSizeEnd,ix+kSizeEnd) = (ixD*ixD)/(var*var)*gaussFnc(var,ixD,iyD)-1/(var)*gaussFnc(var,ixD,iyD);
gaussKernel_YY.at<float>(iy+kSizeEnd,ix+kSizeEnd) = (iyD*iyD)/(var*var)*gaussFnc(var,ixD,iyD)-1/(var)*gaussFnc(var,ixD,iyD);
gaussKernel_XY.at<float>(iy+kSizeEnd,ix+kSizeEnd) = (iyD*ixD)/(var*var)*gaussFnc(var,ixD,iyD);
}
}
}
void VesselnessNodeCPUBW::segmentImage(const Mat& src,Mat& dst) {
float betaParam(filterParameters.betaParam);
float cParam(filterParameters.cParam);
//Actual process segmentation code:
cvtColor(src,greyImage,CV_BGR2GRAY);
greyImage.convertTo(greyFloat,CV_32FC1,1.0,0.0);
float *greyFloatPtr = (float*) greyFloat.data;
greyFloat /= 255.0;
//Gaussian Blur filtering (XX,XY,YY);
filter2D(greyFloat,greyImage_xx,-1,gaussKernel_XX);
filter2D(greyFloat,greyImage_xy,-1,gaussKernel_XY);
filter2D(greyFloat,greyImage_yy,-1,gaussKernel_YY);
std::cout << "Blurred images" << std::endl;
//Compute the number of total pixels
int pixCount = greyImage_xx.rows*greyImage_xx.cols;
//pull out the image data pointers
float *gradPtr_xx = (float*) greyImage_xx.data;
float *gradPtr_yx = (float*) greyImage_xy.data;
float *gradPtr_xy = (float*) greyImage_xy.data;
float *gradPtr_yy = (float*) greyImage_yy.data;
preOutput.create(greyImage_xx.rows,greyImage_xx.cols,CV_32FC1);
char* preOutputImagePtr = (char*) preOutput.data;
int preOutputImageStep0 = preOutput.step[0];
int preOutputImageStep1 = preOutput.step[1];
char* inputMaskPtr = (char*) imageMask.data;
int inputMaskStep0 = imageMask.step[0];
int inputMaskStep1 = imageMask.step[1];
std::cout << "at while loop" << std::endl;
//From Frangi et al.
//for each image, evaluate its eigen vectors, then look at the cost
for(int i =0 ; i < pixCount; i++){
int xPos = i%greyImage_xx.cols;
int yPos = (int) floor(((float) i)/((float) greyImage.cols));
//construct the output pointer
float* prePointer = (float*) (preOutputImagePtr+ preOutputImageStep0*yPos + preOutputImageStep1*xPos);
//If the mask is valid, use it to select points
if(imageMask.rows == imageMask.rows && imageMask.cols == preOutput.cols){
char* maskVal = (inputMaskPtr+ inputMaskStep0*yPos + inputMaskStep1*xPos);
if(maskVal[0] == 0)
{
prePointer[0] = 0.0;
continue;
}
} //if(inputMask.rows == preOutput.rows && inputMask.cols == preOutput.cols)
float vMag =0.0;
float v_y =0.0;
float v_x =1.0;
float a2 =0.0;
float det = gradPtr_xx[i]*gradPtr_yy[i]-gradPtr_yx[i]*gradPtr_yx[i];
float b = -gradPtr_xx[i]-gradPtr_yy[i];
float c = det;
float descriminant = sqrt(b*b-4*c);
float eig0;
float eig1;
float r_Beta;
//adding safety for small values of the descriminant.
if(descriminant > 0.000000001)
{
eig0 = (-b+descriminant)/(2);
eig1 = (-b-descriminant)/(2);
r_Beta = eig0/eig1;
//find the dominant eigenvector:
if(abs(r_Beta) > 1.0) //indicates that eig0 is larger.
{
r_Beta = 1/r_Beta;
}
} //if(descriminant > 0.000000001)
else
{
eig0 = eig1 = -b/2;
r_Beta = 1.0;
v_y = 0.00;
v_x = 1.0;
}
//In this formulation, the image peak is 1.0;
vMag = exp(-r_Beta*r_Beta/(betaParam))*(1-exp(-(eig0*eig0+eig1*eig1)/(cParam)));
if(!(vMag <= 1) || !(vMag >= 0))
{
float test = 1;
}
prePointer[0] = vMag;
}
//Once all is said and done, blur the final image using a gaussian.
dst.create(src.size(),src.type());
Size kernelSize(filterParameters.postProcess.side,filterParameters.postProcess.side);
GaussianBlur(preOutput,dst,kernelSize,filterParameters.postProcess.variance,filterParameters.postProcess.variance);
return;
}
//destructor function
VesselnessNodeCPUBW::~VesselnessNodeCPUBW(){
//clean up the Mats and memory
}
Size VesselnessNodeCPUBW::allocateMem(const Size &sizeIn){
imgAllocSize = sizeIn;
outputImage.create(imgAllocSize,CV_32FC1);
return imgAllocSize;
}
|
#ifndef __OPENHAB_HANDLER_H__
#define __OPENHAB_HANDLER_H__
class OpenHabHandler
{
private:
time_t lastSendTimestamp;
void sendValueV1( const char* itemname, const float value );
void sendValueV2( const char* itemname, const float value );
public:
OpenHabHandler();
void sendValue( const char* itemname, const float value );
void handle( time_t now );
};
extern OpenHabHandler openHabHandler;
#endif
|
#include <Interpreters/BloomFilter.h>
#include <city.h>
#include <Columns/ColumnArray.h>
#include <Columns/ColumnNullable.h>
#include <Columns/ColumnLowCardinality.h>
#include <DataTypes/DataTypeArray.h>
#include <DataTypes/DataTypeNullable.h>
#include <DataTypes/DataTypeLowCardinality.h>
namespace DB
{
namespace ErrorCodes
{
extern const int BAD_ARGUMENTS;
}
static constexpr UInt64 SEED_GEN_A = 845897321;
static constexpr UInt64 SEED_GEN_B = 217728422;
static constexpr UInt64 MAX_BLOOM_FILTER_SIZE = 1 << 30;
BloomFilterParameters::BloomFilterParameters(size_t filter_size_, size_t filter_hashes_, size_t seed_)
: filter_size(filter_size_), filter_hashes(filter_hashes_), seed(seed_)
{
if (filter_size == 0)
throw Exception("The size of bloom filter cannot be zero", ErrorCodes::BAD_ARGUMENTS);
if (filter_hashes == 0)
throw Exception("The number of hash functions for bloom filter cannot be zero", ErrorCodes::BAD_ARGUMENTS);
if (filter_size > MAX_BLOOM_FILTER_SIZE)
throw Exception(ErrorCodes::BAD_ARGUMENTS, "The size of bloom filter cannot be more than {}", MAX_BLOOM_FILTER_SIZE);
}
BloomFilter::BloomFilter(const BloomFilterParameters & params)
: BloomFilter(params.filter_size, params.filter_hashes, params.seed)
{
}
BloomFilter::BloomFilter(size_t size_, size_t hashes_, size_t seed_)
: size(size_), hashes(hashes_), seed(seed_), words((size + sizeof(UnderType) - 1) / sizeof(UnderType)), filter(words, 0)
{
assert(size != 0);
assert(hashes != 0);
}
bool BloomFilter::find(const char * data, size_t len)
{
size_t hash1 = CityHash_v1_0_2::CityHash64WithSeed(data, len, seed);
size_t hash2 = CityHash_v1_0_2::CityHash64WithSeed(data, len, SEED_GEN_A * seed + SEED_GEN_B);
for (size_t i = 0; i < hashes; ++i)
{
size_t pos = (hash1 + i * hash2 + i * i) % (8 * size);
if (!(filter[pos / (8 * sizeof(UnderType))] & (1ULL << (pos % (8 * sizeof(UnderType))))))
return false;
}
return true;
}
void BloomFilter::add(const char * data, size_t len)
{
size_t hash1 = CityHash_v1_0_2::CityHash64WithSeed(data, len, seed);
size_t hash2 = CityHash_v1_0_2::CityHash64WithSeed(data, len, SEED_GEN_A * seed + SEED_GEN_B);
for (size_t i = 0; i < hashes; ++i)
{
size_t pos = (hash1 + i * hash2 + i * i) % (8 * size);
filter[pos / (8 * sizeof(UnderType))] |= (1ULL << (pos % (8 * sizeof(UnderType))));
}
}
void BloomFilter::clear()
{
filter.assign(words, 0);
}
bool BloomFilter::contains(const BloomFilter & bf)
{
for (size_t i = 0; i < words; ++i)
{
if ((filter[i] & bf.filter[i]) != bf.filter[i])
return false;
}
return true;
}
UInt64 BloomFilter::isEmpty() const
{
for (size_t i = 0; i < words; ++i)
if (filter[i] != 0)
return false;
return true;
}
bool operator== (const BloomFilter & a, const BloomFilter & b)
{
for (size_t i = 0; i < a.words; ++i)
if (a.filter[i] != b.filter[i])
return false;
return true;
}
void BloomFilter::addHashWithSeed(const UInt64 & hash, const UInt64 & hash_seed)
{
size_t pos = CityHash_v1_0_2::Hash128to64(CityHash_v1_0_2::uint128(hash, hash_seed)) % (8 * size);
filter[pos / (8 * sizeof(UnderType))] |= (1ULL << (pos % (8 * sizeof(UnderType))));
}
bool BloomFilter::findHashWithSeed(const UInt64 & hash, const UInt64 & hash_seed)
{
size_t pos = CityHash_v1_0_2::Hash128to64(CityHash_v1_0_2::uint128(hash, hash_seed)) % (8 * size);
return bool(filter[pos / (8 * sizeof(UnderType))] & (1ULL << (pos % (8 * sizeof(UnderType)))));
}
DataTypePtr BloomFilter::getPrimitiveType(const DataTypePtr & data_type)
{
if (const auto * array_type = typeid_cast<const DataTypeArray *>(data_type.get()))
{
if (!typeid_cast<const DataTypeArray *>(array_type->getNestedType().get()))
return getPrimitiveType(array_type->getNestedType());
else
throw Exception("Unexpected type " + data_type->getName() + " of bloom filter index.", ErrorCodes::BAD_ARGUMENTS);
}
if (const auto * nullable_type = typeid_cast<const DataTypeNullable *>(data_type.get()))
return getPrimitiveType(nullable_type->getNestedType());
if (const auto * low_cardinality_type = typeid_cast<const DataTypeLowCardinality *>(data_type.get()))
return getPrimitiveType(low_cardinality_type->getDictionaryType());
return data_type;
}
ColumnPtr BloomFilter::getPrimitiveColumn(const ColumnPtr & column)
{
if (const auto * array_col = typeid_cast<const ColumnArray *>(column.get()))
return getPrimitiveColumn(array_col->getDataPtr());
if (const auto * nullable_col = typeid_cast<const ColumnNullable *>(column.get()))
return getPrimitiveColumn(nullable_col->getNestedColumnPtr());
if (const auto * low_cardinality_col = typeid_cast<const ColumnLowCardinality *>(column.get()))
return getPrimitiveColumn(low_cardinality_col->convertToFullColumnIfLowCardinality());
return column;
}
}
|
//////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2004-2007. 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/interprocess for documentation.
//
//////////////////////////////////////////////////////////////////////////////
#include <boost/interprocess/detail/config_begin.hpp>
#include <set>
#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/containers/set.hpp>
#include <boost/interprocess/containers/map.hpp>
#include <boost/interprocess/allocators/allocator.hpp>
#include <boost/interprocess/indexes/map_index.hpp>
#include <boost/interprocess/indexes/iset_index.hpp>
#include <boost/interprocess/mem_algo/simple_seq_fit.hpp>
#include "print_container.hpp"
#include "movable_int.hpp"
#include "dummy_test_allocator.hpp"
#include "set_test.hpp"
#include "map_test.hpp"
#include "emplace_test.hpp"
///////////////////////////////////////////////////////////////////
// //
// This example repeats the same operations with std::set and //
// shmem_set using the node allocator //
// and compares the values of both containers //
// //
///////////////////////////////////////////////////////////////////
using namespace boost::interprocess;
//Customize managed_shared_memory class
typedef basic_managed_shared_memory
<char,
simple_seq_fit<mutex_family, offset_ptr<void> >,
map_index
> my_managed_shared_memory;
//We will work with narrow characters for shared memory objects
//Alias an integer node allocator type
typedef allocator<int, my_managed_shared_memory::segment_manager>
shmem_allocator_t;
typedef allocator<std::pair<const int, int>, my_managed_shared_memory::segment_manager>
shmem_node_pair_allocator_t;
typedef allocator<test::movable_int, my_managed_shared_memory::segment_manager>
shmem_movable_allocator_t;
typedef allocator<std::pair<const test::movable_int, test::movable_int>, my_managed_shared_memory::segment_manager>
shmem_movable_node_pair_allocator_t;
typedef allocator<test::movable_and_copyable_int, my_managed_shared_memory::segment_manager>
shmem_move_copy_allocator_t;
typedef allocator<std::pair<const test::movable_and_copyable_int, test::movable_and_copyable_int>, my_managed_shared_memory::segment_manager>
shmem_move_copy_node_pair_allocator_t;
//Alias standard types
typedef std::set<int> MyStdSet;
typedef std::multiset<int> MyStdMultiSet;
typedef std::map<int, int> MyStdMap;
typedef std::multimap<int, int> MyStdMultiMap;
//Alias non-movable types
typedef set<int, std::less<int>, shmem_allocator_t> MyShmSet;
typedef multiset<int, std::less<int>, shmem_allocator_t> MyShmMultiSet;
typedef map<int, int, std::less<int>, shmem_node_pair_allocator_t> MyShmMap;
typedef multimap<int, int, std::less<int>, shmem_node_pair_allocator_t> MyShmMultiMap;
//Alias movable types
typedef set<test::movable_int, std::less<test::movable_int>
,shmem_movable_allocator_t> MyMovableShmSet;
typedef multiset<test::movable_int,
std::less<test::movable_int>,
shmem_movable_allocator_t> MyMovableShmMultiSet;
typedef map<test::movable_int, test::movable_int,
std::less<test::movable_int>,
shmem_movable_node_pair_allocator_t> MyMovableShmMap;
typedef multimap<test::movable_int, test::movable_int,
std::less<test::movable_int>,
shmem_movable_node_pair_allocator_t> MyMovableShmMultiMap;
typedef set<test::movable_and_copyable_int
,std::less<test::movable_and_copyable_int>
,shmem_move_copy_allocator_t> MyMoveCopyShmSet;
typedef multiset<test::movable_and_copyable_int,
std::less<test::movable_and_copyable_int>,
shmem_move_copy_allocator_t> MyMoveCopyShmMultiSet;
typedef map<test::movable_and_copyable_int
,test::movable_and_copyable_int
,std::less<test::movable_and_copyable_int>
,shmem_move_copy_node_pair_allocator_t> MyMoveCopyShmMap;
typedef multimap<test::movable_and_copyable_int
,test::movable_and_copyable_int
,std::less<test::movable_and_copyable_int>
,shmem_move_copy_node_pair_allocator_t> MyMoveCopyShmMultiMap;
//Test recursive structures
class recursive_set
{
public:
int id_;
set<recursive_set> set_;
friend bool operator< (const recursive_set &a, const recursive_set &b)
{ return a.id_ < b.id_; }
};
class recursive_map
{
public:
int id_;
map<recursive_map, recursive_map> map_;
friend bool operator< (const recursive_map &a, const recursive_map &b)
{ return a.id_ < b.id_; }
};
//Test recursive structures
class recursive_multiset
{
public:
int id_;
multiset<recursive_multiset> multiset_;
friend bool operator< (const recursive_multiset &a, const recursive_multiset &b)
{ return a.id_ < b.id_; }
};
class recursive_multimap
{
public:
int id_;
multimap<recursive_multimap, recursive_multimap> multimap_;
friend bool operator< (const recursive_multimap &a, const recursive_multimap &b)
{ return a.id_ < b.id_; }
};
template<class C>
void test_move()
{
//Now test move semantics
C original;
C move_ctor(boost::interprocess::move(original));
C move_assign;
move_assign = boost::interprocess::move(move_ctor);
move_assign.swap(original);
}
int main ()
{
//Recursive container instantiation
{
set<recursive_set> set_;
multiset<recursive_multiset> multiset_;
map<recursive_map, recursive_map> map_;
multimap<recursive_multimap, recursive_multimap> multimap_;
}
//Now test move semantics
{
test_move<set<recursive_set> >();
test_move<multiset<recursive_multiset> >();
test_move<map<recursive_map, recursive_map> >();
test_move<multimap<recursive_multimap, recursive_multimap> >();
}
using namespace boost::interprocess::detail;
if(0 != test::set_test<my_managed_shared_memory
,MyShmSet
,MyStdSet
,MyShmMultiSet
,MyStdMultiSet>()){
return 1;
}
if(0 != test::set_test_copyable<my_managed_shared_memory
,MyShmSet
,MyStdSet
,MyShmMultiSet
,MyStdMultiSet>()){
return 1;
}
if(0 != test::set_test<my_managed_shared_memory
,MyMovableShmSet
,MyStdSet
,MyMovableShmMultiSet
,MyStdMultiSet>()){
return 1;
}
if(0 != test::set_test<my_managed_shared_memory
,MyMoveCopyShmSet
,MyStdSet
,MyMoveCopyShmMultiSet
,MyStdMultiSet>()){
return 1;
}
if (0 != test::map_test<my_managed_shared_memory
,MyShmMap
,MyStdMap
,MyShmMultiMap
,MyStdMultiMap>()){
return 1;
}
if(0 != test::map_test_copyable<my_managed_shared_memory
,MyShmMap
,MyStdMap
,MyShmMultiMap
,MyStdMultiMap>()){
return 1;
}
// if (0 != test::map_test<my_managed_shared_memory
// ,MyMovableShmMap
// ,MyStdMap
// ,MyMovableShmMultiMap
// ,MyStdMultiMap>()){
// return 1;
// }
if (0 != test::map_test<my_managed_shared_memory
,MyMoveCopyShmMap
,MyStdMap
,MyMoveCopyShmMultiMap
,MyStdMultiMap>()){
return 1;
}
const test::EmplaceOptions SetOptions = (test::EmplaceOptions)(test::EMPLACE_HINT | test::EMPLACE_ASSOC);
if(!boost::interprocess::test::test_emplace<set<test::EmplaceInt>, SetOptions>())
return 1;
if(!boost::interprocess::test::test_emplace<multiset<test::EmplaceInt>, SetOptions>())
return 1;
const test::EmplaceOptions MapOptions = (test::EmplaceOptions)(test::EMPLACE_HINT_PAIR | test::EMPLACE_ASSOC_PAIR);
if(!boost::interprocess::test::test_emplace<map<test::EmplaceInt, test::EmplaceInt>, MapOptions>())
return 1;
if(!boost::interprocess::test::test_emplace<multimap<test::EmplaceInt, test::EmplaceInt>, MapOptions>())
return 1;
return 0;
}
#include <boost/interprocess/detail/config_end.hpp>
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/greengrass/model/GetFunctionDefinitionRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Greengrass::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
GetFunctionDefinitionRequest::GetFunctionDefinitionRequest() :
m_functionDefinitionIdHasBeenSet(false)
{
}
Aws::String GetFunctionDefinitionRequest::SerializePayload() const
{
return {};
}
|
/* node_page_test.cc
Rémi Attab, 20 January 2012
Copyright (c) 2012 Datacratic. All rights reserved.
Tests for node_page.h
*/
#define BOOST_TEST_MAIN
#define BOOST_TEST_DYN_LINK
#include "mmap/node_page.h"
#include "soa/utils/threaded_test.h"
#include <boost/test/unit_test.hpp>
#include <iostream>
#include <thread>
#include <future>
#include <stack>
#include <array>
using namespace std;
using namespace boost;
using namespace Datacratic;
using namespace Datacratic::MMap;
using namespace ML;
// Testing utilities used in both para and seq tests.
template <uint32_t size> struct TestUtil {
typedef GenericNodePage<size> NodeT;
static void checkEmpty (NodeT& nodes) {
BOOST_REQUIRE_EQUAL(nodes.metadata.magic, NodeT::magicNum);
BOOST_REQUIRE_EQUAL(
nodes.metadata.full.numFull(), NodeT::metadataNodes);
}
static void checkSize () {
//Not all NodePages uses the full Page
if (sizeof(NodeT) >= page_size-size && sizeof(NodeT) <= page_size)
return;
cerr << "sizeof(GenericNodePage<" << size << ">)="
<< sizeof(NodeT) << endl;
cerr << "{ numNodes = " << NodeT::numNodes
<< ", sizeof(FullBitmap) = " << sizeof(FullBitmap<NodeT::numNodes>)
<< ", metadataSize = " << NodeT::metadataSize
<< ", metadataNodes = " << NodeT::metadataNodes
<< ", metadataPadding = " << NodeT::metadataPadding
<< "}" << endl;
BOOST_REQUIRE(sizeof(NodeT) == page_size);
}
};
// Test various behaviours when allocating and deallocating in a sequential test
template<uint32_t size> struct SequentialTest {
static void exec () {
typedef GenericNodePage<size> NodeT;
NodeT nodes;
nodes.init();
int64_t offset;
bool needUpdate;
TestUtil<size>::checkSize();
for (int k = 0; k < 3; ++k) {
// Exceptions are thrown but it pollutes the console output so disable it.
#if 0
// Try deallocating metadata nodes
for (int i = 0; i < NodeT::metadataNodes; ++i) {
BOOST_CHECK_THROW(
nodes.deallocate(i*size), ML::Assertion_Failure);
}
#endif
// Fully allocate the page.
for (int i = NodeT::metadataNodes; i < NodeT::numNodes; ++i) {
tie(offset, needUpdate) = nodes.allocate();
BOOST_REQUIRE_EQUAL(needUpdate, i == NodeT::numNodes-1);
BOOST_REQUIRE_EQUAL(offset, i*size);
}
// Over allocate the page.
for(int i = 0; i < 3; ++i) {
tie(offset, needUpdate) = nodes.allocate();
BOOST_REQUIRE_LE(offset, -1);
}
// De-allocate and reallocate a random node.
int64_t newOffset = (NodeT::numNodes/2) * size;
needUpdate = nodes.deallocate(newOffset);
BOOST_REQUIRE_EQUAL(needUpdate, true);
tie(offset, needUpdate) = nodes.allocate();
BOOST_REQUIRE_EQUAL(needUpdate, true);
BOOST_REQUIRE_EQUAL(offset, newOffset);
// Fully de-allocate the page.
for (int i = NodeT::metadataNodes; i < NodeT::numNodes; ++i) {
bool needUpdate = nodes.deallocate(i*size);
BOOST_REQUIRE_EQUAL(needUpdate, i == NodeT::metadataNodes);
}
// Exceptions are thrown but it pollutes the console output so disable it.
#if 0
// Over de-allocate the page
for (int i = NodeT::metadataNodes; i < NodeT::numNodes; ++i) {
BOOST_CHECK_THROW(nodes.deallocate(i*size), ML::Exception);
}
#endif
// Make sure everything is properly deallocated.
TestUtil<size>::checkEmpty(nodes);
}
}
};
BOOST_AUTO_TEST_CASE(test_seq) {
SequentialTest<8>::exec();
SequentialTest<12>::exec();
SequentialTest<32>::exec();
SequentialTest<64>::exec();
SequentialTest<96>::exec();
SequentialTest<192>::exec();
SequentialTest<256>::exec();
}
// Starts a truck load of tests that randomly allocates and frees nodes.
template<uint32_t size>
struct ParallelTest
{
enum {
threadCount = 4,
iterationCount = 10000
};
typedef GenericNodePage<size> NodeT;
NodeT nodes;
bool allocateNode (stack<int64_t>& s) {
int64_t offset = nodes.allocate().first;
if (offset >= 0) {
s.push(offset);
return true;
}
return false;
}
void deallocateHead(stack<int64_t>& s) {
nodes.deallocate(s.top());
s.pop();
}
void runThread (int id) {
mt19937 engine(id);
uniform_int_distribution<int> opDist(0, 1);
uniform_int_distribution<int> numDist(0, size);
stack<int64_t> allocatedOffsets;
for (int i = 0; i < iterationCount; ++i) {
if (allocatedOffsets.empty()) {
if (!allocateNode(allocatedOffsets)) {
// nothing to allocate or deallocate,
// take a nap and try again.
std::this_thread::yield();
}
continue;
}
else if (opDist(engine) && allocateNode(allocatedOffsets)) {
for (int j = numDist(engine); j > 0; --j) {
if (!allocateNode(allocatedOffsets)) {
break;
}
}
continue;
}
// De-allocate if space is full or we're randomly chosen.
for (int j = numDist(engine);
!allocatedOffsets.empty() && j > 0;
--j)
{
deallocateHead(allocatedOffsets);
}
}
// We're done, cleanup.
while (!allocatedOffsets.empty()) {
deallocateHead(allocatedOffsets);
}
}
void exec() {
nodes.init();
auto runFn = [&] (int id) {
this->runThread(id);
return 0;
};
ThreadedTest test;
test.start(runFn, threadCount);
test.joinAll(10000);
// Make sure everything is properly deallocated.
TestUtil<size>::checkEmpty(nodes);
}
};
BOOST_AUTO_TEST_CASE(test_para) {
ParallelTest<8>().exec();
ParallelTest<48>().exec();
ParallelTest<64>().exec();
ParallelTest<192>().exec();
ParallelTest<256>().exec();
}
|
#include "../submodel.h"
#include "../mat2D.h"
#include "../config.cpp"
class s5x5_minmax41: public Submodel
{
public:
s5x5_minmax41(float q, Config *config) : Submodel(q)
{
this->modelName = "s5x5_minmax41";
this->minmax = true;
this->coocDirs.push_back("horver");
Initialize(config);
}
~s5x5_minmax41()
{
}
virtual void ComputeFea(std::vector<mat2D<int> *> QResVect)
{
std::vector<std::vector<mat2D<int> *> > OpVect;
// [0] - Right, [1] - Left, [2] - Up, [3] - Down
// [4] - All
// Twice the same, vertical and horizontal co-occurrence
// Right Up Left Down
std::vector<mat2D<int> *> RLUD = std::vector<mat2D<int> *>();
RLUD.push_back(QResVect[0]);RLUD.push_back(QResVect[1]);RLUD.push_back(QResVect[2]);RLUD.push_back(QResVect[3]);
OpVect.push_back(RLUD);
this->AddFea(OpVect);
}
};
|
/*
* Copyright (c) 2018 Samsung Electronics Co., Ltd. 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 "ReshapeLayer.h"
namespace onert
{
namespace backend
{
namespace cpu
{
namespace ops
{
ReshapeLayer::ReshapeLayer() : _input(nullptr), _shape(nullptr), _output(nullptr)
{
// DO NOTHING
}
void ReshapeLayer::reshapeGeneric()
{
size_t count = _input->total_size();
memcpy(_output->buffer(), _input->buffer(), count);
}
void ReshapeLayer::configure(const Tensor *input, const Tensor *shape, Tensor *output)
{
_input = input;
/* note : shape is optional. If not provided from model, _shape is nullptr. */
_shape = shape;
_output = output;
}
void ReshapeLayer::run() { reshapeGeneric(); }
} // namespace ops
} // namespace cpu
} // namespace backend
} // namespace onert
|
/*
* Copyright (C) 2021 Open Source Robotics Foundation
*
* 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.
*
*/
#ifndef SYSTEM_PLUGIN_HELLOWORLD_HH_
#define SYSTEM_PLUGIN_HELLOWORLD_HH_
// The only required include in the header is this one.
// All others will depend on what your plugin does.
#include <ignition/gazebo/System.hh>
// It's good practice to use a custom namespace for your project.
namespace hello_world
{
// This is the main plugin's class. It must inherit from System and at least
// one other interface.
// Here we use `ISystemPostUpdate`, which is used to get results after
// physics runs. The opposite of that, `ISystemPreUpdate`, would be used by
// plugins that want to send commands.
class HelloWorld:
public ignition::gazebo::System,
public ignition::gazebo::ISystemPostUpdate
{
// Plugins inheriting ISystemPostUpdate must implement the PostUpdate
// callback. This is called at every simulation iteration after the physics
// updates the world. The _info variable provides information such as time,
// while the _ecm provides an interface to all entities and components in
// simulation.
public: void PostUpdate(const ignition::gazebo::UpdateInfo &_info,
const ignition::gazebo::EntityComponentManager &_ecm) override;
};
}
#endif
|
#include <iostream>
#include "node.h"
#include "bools.h"
// Funzioni di output dei nodi
int CBlock::globalid = 0;
// indicizzata per nodo
char * nodeTable[] = {
"Ndecl", // dichiarazione, binary: sx = declspec, dx = lista dirdecl
"Nargdecl", // dichiarazione di argomento di funzione.
"Ndirdecl", // declarator, binary: sx = declarators, dx = init list
"Nptrdecl", // puntatore, CUnExpr
"Narraydecl", // array, CBinExpe: sx = size expr, dx = argument
"Nfuncdecl", // function, CBinList: sx = declarators del ritorno, dx =lista arg
"Nstatic",
"Nextern",
"Nellipse",
"Nadd", "Nsub", "Nmul", "Ndiv", "Nmod", "Nlogand", "Nbinor", "Nbinxor",
"Nbinand", "Neq", "Nneq", "Nlt", "Ngt", "Nlteq", "Ngteq", "Nshl", "Nshr",
"Nassign", "Ncomma", "Nlogor","Ncall", "Ncast",
"Nlognot", "Nbinnot", "Nneg","Nconst","Nident","Narray",
"Nptr", "Naddr",
"Nexpr","Ndeclstat", "Nfuncbody", "Nblock", "Nreturn", "Nwhile", "Ndo",
"Nif", "Nfor", "Nsymbol",
"Norelse1", "Norelse2", "Nexpr2bool", "Nbool2expr","Ncmp",
"Ninc", "Ndec", "Nincpost", "Ndecpost",
};
// tabella usata per gli errori
char * nodeTable2[] = {
"", // dichiarazione, binary: sx = declspec, dx = lista dirdecl
"", // dichiarazione di argomento di funzione.
"", // declarator, binary: sx = declarators, dx = init list
"", // puntatore, CUnExpr
"", // array, CBinExpe: sx = size expr, dx = argument
"", // function, CBinList: sx = declarators del ritorno, dx =lista arg
"static",
"extern",
"...",
"+", "-", "*", "/", "%", "&&", "|", "^",
"&", "==", "!=", "<", ">", "<=", ">=", "<<", ">>",
"=", "Ncomma", "Nlogor","Ncall", "Ncast",
"!", "~", "-","","","[]",
"*", "&",
"","", "", "", "return", "while", "do",
"if", "for", "",
"", "", "", "","",
"++", "--", "++", "--",
};
// Gestione della visualizzazione dell'albero:
//
// C:
// |- Dev
// ||- Jdk
// |||- Bin
// ||\- Lib
//
//
// Level: 0x80000000 indica che e' l'ultimo dei figli del padre
// i bit settati indicano che deve aggiungere una stanghetta
//
// CHILD(level)
// LASTCHILD(level): in tal caso
//
char * CNode::stringOf(NodeType op)
{
return nodeTable2[op];
}
CConstExpr::CConstExpr(int i) :CExpression(Nconst)
{
//cvalue(true);
ival = i;
ptipo = CType::Int();
}
CConstExpr::CConstExpr(char c):CExpression(Nconst)
{
// cvalue(true);
cval = c;
ptipo = CType::Char();
}
CConstExpr::CConstExpr(float f):CExpression(Nconst)
{
// cvalue(true);
fval = f;
ptipo = CType::Float();
}
CConstExpr::CConstExpr(const char * s, int len):CExpression(Nconst)
{
// cvalue(true);
strval.cp = s;
strval.len = len;
ptipo = (CType::Char())->ptr();
}
CBlock::CBlock(lineRef no, CBlock*p): CStatement(Nblock,no)
{
m_frameSize = 0;
m_parent = p;
m_nestingLevel = p ? m_parent->level()+1 : 0;
m_blockID = globalid++;
}
CStatement::CStatement(NodeType nt, lineRef no) : CNode(nt), lineno(no){}
CExprStat::CExprStat(NodeType nt, PExpression e, lineRef num) : CStatement(nt, num)
{
expr = e;
assert(nt == Nreturn || nt == Ndeclstat || nt == Nexpr);
if(nt == Ndeclstat) assert(e->node() == Ndecl);
}
// Function name : CCondStat::mknode
// Description : creates a node for if, while, for, do..while
// statements.
// Return type : CCondStat*
// Argument : NodeType nt
// Argument : int lineno
// Argument : PExpression e
// Argument : PStatement s1 = 0
// Argument : PStatement s2 = 0
CCondStat* CCondStat::mknode(NodeType nt, int lineno, PExpression e, PStatement s1 , PStatement s2 )
{
assert(nt == Nif || nt == Nwhile);
CCondStat* p = new CCondStat(nt, lineno);
p->cond = e;
p->block = s1;
p->blockII = s2;
return p;
}
CCondStat* CCondStat::mknode_for(int lineno,
PStatement before,
PExpression cond,
PExpression incr,
PStatement body)
{
CCondStat* p = new CCondStat(Nfor, lineno);
p->cond = cond;
p->block = before;
p->blockII = body;
p->incr = incr;
return p;
}
CSymExpr::CSymExpr(CSymbol * sym) : CExpression(Nsymbol), m_symbol(sym)
{ptipo = sym->getTipo();}
CFuncBody::CFuncBody(int no, PBlock parent, PExpression e ) :
CStatement(Nfuncbody,no)
{
assert(e && *e == Ndecl);
decl = e;
}
#include "bools.h"
// **********************************************************************
void PrintVisitor::VisitCNode(CNode * pn)
{
spacer(o,level);
o << nodeTable[*pn] << std::endl;
doExprChild(pn);
}
void PrintVisitor::VisitCUnNode(CUnNode * pn)
{ VisitCNode(pn);}
void PrintVisitor::doExprChild(CNode* pn)
{
writeData tmp = level;
if(pn->left()) {
level = pn->right() ? CHILD(tmp) : LASTCHILD(tmp);
pn->left()->accept(*this);
}
if(pn->right()) {
level = LASTCHILD(tmp);
pn->right()->accept(*this);
}
level = tmp;
}
void PrintVisitor::VisitCExpression(CExpression * pn)
{
spacer(o,level);
o << nodeTable[*pn] << " ";
if(pn->ptipo) {
o << " " << *(pn->ptipo) << " ";
}
if(pn->lvalue()) { o << "L"; }
if(pn->cvalue()) { o << "C"; }
o << std::endl;
doExprChild(pn);
}
void PrintVisitor::VisitCUnExpr(CUnExpr * pn)
{ VisitCExpression(pn);}
void PrintVisitor::VisitCBinExpr(CBinExpr * pn)
{ VisitCExpression(pn);}
void PrintVisitor::VisitCComma(CComma * pn)
{
VisitCExpression(pn);
CComma::iterator it = pn->begin();
writeData tmp = level;
while(it != pn->end()) {
assert(*it);
CComma::iterator tmpit = it;
it++;
level = it == pn->end() ? LASTCHILD(tmp) : CHILD(tmp) ;
(*tmpit)->accept(*this);
}
level = tmp;
}
void PrintVisitor::VisitCDirDecl(CDirDecl * pn)
{
assert(pn->node() == Ndirdecl);
spacer(o,level);
o << nodeTable[*pn] << " " << (pn->identifer()? pn->identifer() : "") << '\n';
doExprChild(pn);
}
void PrintVisitor::VisitCConstExpr(CConstExpr * pn)
{
spacer(o, level);
o << "Nconst ";
switch(pn->ptipo->getType()) {
case tINT: o << "int = " << pn->ival; break;
case tCHAR: o << "char = " << pn->cval; break;
case tFLOAT : o << "float = " << pn->fval; break;
case tPTR: o << "string"; break;
default:
std::cerr << "ERRORE INTERNO!";
break;
}
o << std::endl;
}
void PrintVisitor::VisitCIdentifer(CIdentifer * pn)
{
spacer(o, level);
o << "\"" << (pn->identifer()? pn->identifer() : "") << "\"" << std::endl;
}
void PrintVisitor::VisitCStatement(CStatement * pn)
{ VisitCNode(pn);}
void PrintVisitor::VisitCBlock(CBlock * pn)
{
spacer(o,level);
o << nodeTable[pn->node()] << std::endl;
CBlock::iterator it = pn->begin();
while(it != pn->end()) {
assert(*it);
CBlock::iterator tmpit = it;
it++;
writeData tmp = level;
level = it == pn->end() ? LASTCHILD(level) : CHILD(level);
(*tmpit)->accept(*this);
level = tmp;
}
}
void PrintVisitor::VisitCExprStat(CExprStat * pn)
{ VisitCStatement(pn); }
void PrintVisitor::VisitCFuncBody(CFuncBody * pn)
{ VisitCStatement(pn);}
void PrintVisitor::stampaLogic(LogicDesc & ld)
{
static char * condt[] = {"cNIL", "cTRUE", "cFALSE", "cLT",
"cGT", "cLE", "cGE", "cEQ", "cNE"};
o << "<" << condt[CondType(ld.condizione)] << ", ";
// Qui c'e' il set
if(ld.vero.empty())
o << '*';
else
o << ld.vero;
o << ',';
if(ld.falso.empty())
o << '*';
else
o << ld.falso;
o << ',';
if(ld.unisci.empty())
o << '*';
else
o << ld.unisci;
o << '>' << std::endl;
}
void PrintVisitor::VisitCBoolNode(CBoolNode * pn)
{
spacer(o, level);
o << nodeTable[*pn] ;
stampaLogic(pn->ldesc);
doExprChild(pn);
}
void PrintVisitor::VisitCCondStat(CCondStat * pn)
{
spacer(o,level);
o << nodeTable[pn->node()] << std::endl;
writeData tmp = level;
switch(pn->node()) {
case Nif:
assert(pn->bcond);
assert(pn->block);
level = CHILD(tmp);
pn->bcond->accept(*this);
level = pn->blockII ? CHILD(tmp):LASTCHILD(tmp);
pn->block->accept(*this);
level = LASTCHILD(tmp);
if(pn->blockII) pn->blockII->accept(*this);
break;
case Nwhile:
assert(pn->bcond && pn->block);
level = CHILD(tmp);
pn->bcond->accept(*this);
level = LASTCHILD(tmp);
pn->block->accept(*this);
break;
default:
return;
}
level = tmp;
}
void PrintVisitor::VisitCSymExpr(CSymExpr * pn)
{
assert(pn->getSymbol()!= 0);
spacer(o, level);
o << "\"" << pn->getSymbol()->getNome() << "\" " << *(pn->getSymbol()->getTipo())<< "L \n";
}
void PrintVisitor::VisitCBoolExpr(CBoolExpr * pn)
{ VisitCBoolNode(pn);}
void PrintVisitor::VisitCExpr2Bool(CExpr2Bool * pn)
{
VisitCBoolNode(pn);
}
void PrintVisitor::VisitCBool2Expr(CBool2Expr * pn)
{
VisitCExpression(pn);
}
void PrintVisitor::VisitCRelBoolExpr(CRelBoolExpr * pn)
{
VisitCBoolNode(pn);
}
|
// Copyright information can be found in the file named COPYING
// located in the root directory of this distribution.
#include "platform/platform.h"
#include "gui/worldEditor/terrainEditor.h"
#include "core/frameAllocator.h"
#include "core/strings/stringUnit.h"
#include "console/consoleTypes.h"
#include "console/simEvents.h"
#include "sim/netConnection.h"
#include "math/mathUtils.h"
#include "gfx/primBuilder.h"
#include "gfx/gfxDrawUtil.h"
#include "gui/core/guiCanvas.h"
#include "gui/worldEditor/terrainActions.h"
#include "terrain/terrMaterial.h"
IMPLEMENT_CONOBJECT(TerrainEditor);
ConsoleDocClass( TerrainEditor,
"@brief The base Terrain Editor tool\n\n"
"Editor use only.\n\n"
"@internal"
);
Selection::Selection() :
Vector<GridInfo>(__FILE__, __LINE__),
mName(0),
mUndoFlags(0),
mHashListSize(1024)
{
VECTOR_SET_ASSOCIATION(mHashLists);
// clear the hash list
mHashLists.setSize(mHashListSize);
reset();
}
Selection::~Selection()
{
}
void Selection::reset()
{
PROFILE_SCOPE( TerrainEditor_Selection_Reset );
for(U32 i = 0; i < mHashListSize; i++)
mHashLists[i] = -1;
clear();
}
bool Selection::validate()
{
PROFILE_SCOPE( TerrainEditor_Selection_Validate );
// scan all the hashes and verify that the heads they point to point back to them
U32 hashesProcessed = 0;
for(U32 i = 0; i < mHashLists.size(); i++)
{
U32 entry = mHashLists[i];
if(entry == -1)
continue;
GridInfo info = (*this)[entry];
U32 hashIndex = getHashIndex(info.mGridPoint.gridPos);
if( entry != mHashLists[hashIndex] )
{
AssertFatal(false, "Selection hash lists corrupted");
return false;
}
hashesProcessed++;
}
// scan all the entries and verify that anything w/ a prev == -1 is correctly in the hash table
U32 headsProcessed = 0;
for(U32 i = 0; i < size(); i++)
{
GridInfo info = (*this)[i];
if(info.mPrev != -1)
continue;
U32 hashIndex = getHashIndex(info.mGridPoint.gridPos);
if(mHashLists[hashIndex] != i)
{
AssertFatal(false, "Selection list heads corrupted");
return false;
}
headsProcessed++;
}
AssertFatal(headsProcessed == hashesProcessed, "Selection's number of hashes and number of list heads differ.");
return true;
}
U32 Selection::getHashIndex(const Point2I & pos)
{
PROFILE_SCOPE( TerrainEditor_Selection_GetHashIndex );
Point2F pnt = Point2F((F32)pos.x, (F32)pos.y) + Point2F(1.3f,3.5f);
return( (U32)(mFloor(mHashLists.size() * mFmod(pnt.len() * 0.618f, 1.0f))) );
}
S32 Selection::lookup(const Point2I & pos)
{
PROFILE_SCOPE( TerrainEditor_Selection_Lookup );
U32 index = getHashIndex(pos);
S32 entry = mHashLists[index];
while(entry != -1)
{
if((*this)[entry].mGridPoint.gridPos == pos)
return(entry);
entry = (*this)[entry].mNext;
}
return(-1);
}
void Selection::insert(GridInfo info)
{
PROFILE_SCOPE( TerrainEditor_Selection_Insert );
//validate();
// get the index into the hash table
U32 index = getHashIndex(info.mGridPoint.gridPos);
// if there is an existing linked list, make it our next
info.mNext = mHashLists[index];
info.mPrev = -1;
// if there is an existing linked list, make us it's prev
U32 indexOfNewEntry = size();
if(info.mNext != -1)
(*this)[info.mNext].mPrev = indexOfNewEntry;
// the hash table holds the heads of the linked lists. make us the head of this list.
mHashLists[index] = indexOfNewEntry;
// copy us into the vector
push_back(info);
//validate();
}
bool Selection::remove(const GridInfo &info)
{
PROFILE_SCOPE( TerrainEditor_Selection_Remove );
if(size() < 1)
return false;
//AssertFatal( validate(), "Selection hashLists corrupted before Selection.remove()");
U32 hashIndex = getHashIndex(info.mGridPoint.gridPos);
S32 listHead = mHashLists[hashIndex];
//AssertFatal(listHead < size(), "A Selection's hash table is corrupt.");
if(listHead == -1)
return(false);
const S32 victimEntry = lookup(info.mGridPoint.gridPos);
if( victimEntry == -1 )
return(false);
const GridInfo victim = (*this)[victimEntry];
const S32 vicPrev = victim.mPrev;
const S32 vicNext = victim.mNext;
// remove us from the linked list, if there is one.
if(vicPrev != -1)
(*this)[vicPrev].mNext = vicNext;
if(vicNext != -1)
(*this)[vicNext].mPrev = vicPrev;
// if we were the head of the list, make our next the new head in the hash table.
if(vicPrev == -1)
mHashLists[hashIndex] = vicNext;
// if we're not the last element in the vector, copy the last element to our position.
if(victimEntry != size() - 1)
{
// copy last into victim, and re-cache next & prev
const GridInfo lastEntry = last();
const S32 lastPrev = lastEntry.mPrev;
const S32 lastNext = lastEntry.mNext;
(*this)[victimEntry] = lastEntry;
// update the new element's next and prev, to reestablish it in it's linked list.
if(lastPrev != -1)
(*this)[lastPrev].mNext = victimEntry;
if(lastNext != -1)
(*this)[lastNext].mPrev = victimEntry;
// if it was the head of it's list, update the hash table with its new position.
if(lastPrev == -1)
{
const U32 lastHash = getHashIndex(lastEntry.mGridPoint.gridPos);
AssertFatal(mHashLists[lastHash] == size() - 1, "Selection hashLists corrupted during Selection.remove() (oldmsg)");
mHashLists[lastHash] = victimEntry;
}
}
// decrement the vector, we're done here
pop_back();
//AssertFatal( validate(), "Selection hashLists corrupted after Selection.remove()");
return true;
}
bool Selection::add(const GridInfo &info)
{
PROFILE_SCOPE( TerrainEditor_Selection_Add );
S32 index = lookup(info.mGridPoint.gridPos);
if(index != -1)
return(false);
insert(info);
return(true);
}
bool Selection::getInfo(Point2I pos, GridInfo & info)
{
PROFILE_SCOPE( TerrainEditor_Selection_GetInfo );
S32 index = lookup(pos);
if(index == -1)
return(false);
info = (*this)[index];
return(true);
}
bool Selection::setInfo(GridInfo & info)
{
PROFILE_SCOPE( TerrainEditor_Selection_SetInfo );
S32 index = lookup(info.mGridPoint.gridPos);
if(index == -1)
return(false);
S32 next = (*this)[index].mNext;
S32 prev = (*this)[index].mPrev;
(*this)[index] = info;
(*this)[index].mNext = next;
(*this)[index].mPrev = prev;
return(true);
}
F32 Selection::getAvgHeight()
{
PROFILE_SCOPE( TerrainEditor_Selection_GetAvgHeight );
if(!size())
return(0);
F32 avg = 0.f;
for(U32 i = 0; i < size(); i++)
avg += (*this)[i].mHeight;
return(avg / size());
}
F32 Selection::getMinHeight()
{
PROFILE_SCOPE( TerrainEditor_Selection_GetMinHeight );
if(!size())
return(0);
F32 minHeight = (*this)[0].mHeight;
for(U32 i = 1; i < size(); i++)
minHeight = getMin(minHeight, (*this)[i].mHeight);
return minHeight;
}
F32 Selection::getMaxHeight()
{
PROFILE_SCOPE( TerrainEditor_Selection_GetMaxHeight );
if(!size())
return(0);
F32 maxHeight = (*this)[0].mHeight;
for(U32 i = 1; i < size(); i++)
maxHeight = getMax(maxHeight, (*this)[i].mHeight);
return maxHeight;
}
Brush::Brush(TerrainEditor * editor) :
mTerrainEditor(editor)
{
mSize = mTerrainEditor->getBrushSize();
}
const Point2I & Brush::getPosition()
{
return(mGridPoint.gridPos);
}
const GridPoint & Brush::getGridPoint()
{
return mGridPoint;
}
void Brush::setPosition(const Point3F & pos)
{
PROFILE_SCOPE( TerrainEditor_Brush_SetPosition_Point3F );
mTerrainEditor->worldToGrid(pos, mGridPoint);
update();
}
void Brush::setPosition(const Point2I & pos)
{
PROFILE_SCOPE( TerrainEditor_Brush_SetPosition_Point2I );
mGridPoint.gridPos = pos;
update();
}
void Brush::update()
{
PROFILE_SCOPE( TerrainEditor_Brush_update );
if ( mGridPoint.terrainBlock )
rebuild();
}
void Brush::render()
{
PROFILE_SCOPE( TerrainEditor_Brush_Render );
// Render the brush's outline via the derived brush class.
_renderOutline();
// Render the brush's interior grid points.
const U32 pointCount = mSize.x * mSize.y;
if ( pointCount == 0 )
return;
if ( mRenderList.empty() || empty() )
return;
Vector<GFXVertexPCT> pointList;
pointList.reserve( pointCount );
for(S32 x = 0; x < mSize.x; x++)
{
for(S32 y = 0; y < mSize.y; y++)
{
S32 id = mRenderList[x*mSize.x+y];
if ( id == -1 )
continue;
const GridInfo &gInfo = (*this)[ id ];
Point3F pos;
mTerrainEditor->gridToWorld( gInfo.mGridPoint.gridPos, pos, gInfo.mGridPoint.terrainBlock );
if ( !mTerrainEditor->project( pos, &pos ) )
continue;
pointList.increment();
GFXVertexPCT &pointInfo = pointList.last();
pointInfo.point = pos;
pointInfo.color.set( 255, 0, 255, gInfo.mWeight * 255 );
pointInfo.texCoord.set( 1.0f, 0.0f );
}
}
mTerrainEditor->renderPoints( pointList );
}
void BoxBrush::rebuild()
{
PROFILE_SCOPE( TerrainEditor_BoxBrush_Rebuild );
reset();
const F32 squareSize = mGridPoint.terrainBlock->getSquareSize();
mRenderList.setSize(mSize.x*mSize.y);
Point3F center( F32(mSize.x - 1) / 2.0f * squareSize, F32(mSize.y - 1) / 2.0f * squareSize, 0.0f );
Filter filter;
filter.set(1, &mTerrainEditor->mSoftSelectFilter);
const Point3F mousePos = mTerrainEditor->getMousePos();
F32 xFactorScale = center.x / ( center.x + 0.5f );
F32 yFactorScale = center.y / ( center.y + 0.5f );
const F32 softness = mTerrainEditor->getBrushSoftness();
const F32 pressure = mTerrainEditor->getBrushPressure();
Point3F posw( 0,0,0 );
Point2I posg( 0,0 );
Vector<GridInfo> infos;
for ( S32 x = 0; x < mSize.x; x++ )
{
for(S32 y = 0; y < mSize.y; y++)
{
F32 xFactor = 0.0f;
if ( center.x > 0 )
xFactor = mAbs( center.x - x ) / center.x * xFactorScale;
F32 yFactor = 0.0f;
if ( center.y > 0 )
yFactor = mAbs( center.y - y ) / center.y * yFactorScale;
S32 &rl = mRenderList[x*mSize.x+y];
posw.x = mousePos.x + (F32)x * squareSize - center.x;
posw.y = mousePos.y + (F32)y * squareSize - center.y;
// round to grid coords
GridPoint gridPoint = mGridPoint;
mTerrainEditor->worldToGrid( posw, gridPoint );
// Check that the grid point is valid within the terrain. This assumes
// that there is no wrap around past the edge of the terrain.
if(!mTerrainEditor->isPointInTerrain(gridPoint))
{
rl = -1;
continue;
}
infos.clear();
mTerrainEditor->getGridInfos( gridPoint, infos );
for (U32 z = 0; z < infos.size(); z++)
{
infos[z].mWeight = pressure *
mLerp( infos[z].mWeight, filter.getValue(xFactor > yFactor ? xFactor : yFactor), softness );
push_back(infos[z]);
}
rl = size()-1;
}
}
}
void BoxBrush::_renderOutline()
{
F32 squareSize = mGridPoint.terrainBlock->getSquareSize();
RayInfo ri;
Point3F start( 0, 0, 5000.0f );
Point3F end( 0, 0, -5000.0f );
bool hit;
Vector<Point3F> pointList;
pointList.reserve( 64 );
const ColorI col( 255, 0, 255, 255 );
const Point3F &mousePos = mTerrainEditor->getMousePos();
static const Point2F offsetArray [5] =
{
Point2F( -1, -1 ),
Point2F( 1, -1 ),
Point2F( 1, 1 ),
Point2F( -1, 1 ),
Point2F( -1, -1 ) // repeat of offset[0]
};
// 64 total steps, 4 sides to the box, 16 steps per side.
// 64 / 4 = 16
const U32 steps = 16;
for ( S32 i = 0; i < 4; i++ )
{
const Point2F &offset = offsetArray[i];
const Point2F &next = offsetArray[i+1];
for ( S32 j = 0; j < steps; j++ )
{
F32 frac = (F32)j / ( (F32)steps - 1.0f );
Point2F tmp;
tmp.interpolate( offset, next, frac );
start.x = end.x = mousePos.x + tmp.x * squareSize * 0.5f * (F32)mSize.x;
start.y = end.y = mousePos.y + tmp.y * squareSize * 0.5f * (F32)mSize.y;
hit = gServerContainer.castRay( start, end, TerrainObjectType, &ri );
if ( hit )
pointList.push_back( ri.point );
}
}
mTerrainEditor->drawLineList( pointList, col, 1.0f );
}
void EllipseBrush::rebuild()
{
PROFILE_SCOPE( TerrainEditor_EllipseBrush_Rebuild );
reset();
const F32 squareSize = mGridPoint.terrainBlock->getSquareSize();
mRenderList.setSize(mSize.x*mSize.y);
Point3F center( F32(mSize.x - 1) / 2.0f * squareSize, F32(mSize.y - 1) / 2.0f * squareSize, 0.0f );
Filter filter;
filter.set(1, &mTerrainEditor->mSoftSelectFilter);
const Point3F mousePos = mTerrainEditor->getMousePos();
// a point is in a circle if:
// x^2 + y^2 <= r^2
// a point is in an ellipse if:
// (ax)^2 + (by)^2 <= 1
// where a = 1/halfEllipseWidth and b = 1/halfEllipseHeight
// for a soft-selected ellipse,
// the factor is simply the filtered: ((ax)^2 + (by)^2)
F32 a = 1.0f / (F32(mSize.x) * squareSize * 0.5f);
F32 b = 1.0f / (F32(mSize.y) * squareSize * 0.5f);
const F32 softness = mTerrainEditor->getBrushSoftness();
const F32 pressure = mTerrainEditor->getBrushPressure();
Point3F posw( 0,0,0 );
Point2I posg( 0,0 );
Vector<GridInfo> infos;
for ( S32 x = 0; x < mSize.x; x++ )
{
for ( S32 y = 0; y < mSize.y; y++ )
{
F32 xp = center.x - x * squareSize;
F32 yp = center.y - y * squareSize;
F32 factor = (a * a * xp * xp) + (b * b * yp * yp);
if ( factor > 1 )
{
mRenderList[x*mSize.x+y] = -1;
continue;
}
S32 &rl = mRenderList[x*mSize.x+y];
posw.x = mousePos.x + (F32)x * squareSize - center.x;
posw.y = mousePos.y + (F32)y * squareSize - center.y;
// round to grid coords
GridPoint gridPoint = mGridPoint;
mTerrainEditor->worldToGrid( posw, gridPoint );
// Check that the grid point is valid within the terrain. This assumes
// that there is no wrap around past the edge of the terrain.
if ( !mTerrainEditor->isPointInTerrain( gridPoint ) )
{
rl = -1;
continue;
}
infos.clear();
mTerrainEditor->getGridInfos( gridPoint, infos );
for ( U32 z = 0; z < infos.size(); z++ )
{
infos[z].mWeight = pressure * mLerp( infos[z].mWeight, filter.getValue( factor ), softness );
push_back(infos[z]);
}
rl = size()-1;
}
}
}
void EllipseBrush::_renderOutline()
{
F32 squareSize = mGridPoint.terrainBlock->getSquareSize();
RayInfo ri;
Point3F start( 0, 0, 5000.0f );
Point3F end( 0, 0, -5000.0f );
bool hit;
Vector<Point3F> pointList;
ColorI col( 255, 0, 255, 255 );
const U32 steps = 64;
const Point3F &mousePos = mTerrainEditor->getMousePos();
for ( S32 i = 0; i < steps; i++ )
{
F32 radians = (F32)i / (F32)(steps-1) * M_2PI_F;
VectorF vec(0,1,0);
MathUtils::vectorRotateZAxis( vec, radians );
start.x = end.x = mousePos.x + vec.x * squareSize * (F32)mSize.x * 0.5f;
start.y = end.y = mousePos.y + vec.y * squareSize * (F32)mSize.y * 0.5f;
hit = gServerContainer.castRay( start, end, TerrainObjectType, &ri );
if ( hit )
pointList.push_back( ri.point );
}
mTerrainEditor->drawLineList( pointList, col, 1.0f );
}
SelectionBrush::SelectionBrush(TerrainEditor * editor) :
Brush(editor)
{
//... grab the current selection
}
void SelectionBrush::rebuild()
{
reset();
//... move the selection
}
void SelectionBrush::render(Vector<GFXVertexPC> & vertexBuffer, S32 & verts, S32 & elems, S32 & prims, const ColorF & inColorFull, const ColorF & inColorNone, const ColorF & outColorFull, const ColorF & outColorNone) const
{
//... render the selection
}
TerrainEditor::TerrainEditor() :
mActiveTerrain(0),
mMousePos(0,0,0),
mMouseBrush(0),
mInAction(false),
mUndoSel(0),
mGridUpdateMin( S32_MAX, S32_MAX ),
mGridUpdateMax( 0, 0 ),
mMaxBrushSize(48,48),
mNeedsGridUpdate( false ),
mNeedsMaterialUpdate( false ),
mMouseDown( false )
{
VECTOR_SET_ASSOCIATION(mActions);
//
resetCurrentSel();
//
mBrushPressure = 1.0f;
mBrushSize.set(1,1);
mBrushSoftness = 1.0f;
mBrushChanged = true;
mMouseBrush = new BoxBrush(this);
mMouseDownSeq = 0;
mIsDirty = false;
mIsMissionDirty = false;
mPaintIndex = -1;
// add in all the actions here..
mActions.push_back(new SelectAction(this));
mActions.push_back(new DeselectAction(this));
mActions.push_back(new ClearAction(this));
mActions.push_back(new SoftSelectAction(this));
mActions.push_back(new OutlineSelectAction(this));
mActions.push_back(new PaintMaterialAction(this));
mActions.push_back(new ClearMaterialsAction(this));
mActions.push_back(new RaiseHeightAction(this));
mActions.push_back(new LowerHeightAction(this));
mActions.push_back(new SetHeightAction(this));
mActions.push_back(new SetEmptyAction(this));
mActions.push_back(new ClearEmptyAction(this));
mActions.push_back(new ScaleHeightAction(this));
mActions.push_back(new BrushAdjustHeightAction(this));
mActions.push_back(new AdjustHeightAction(this));
mActions.push_back(new FlattenHeightAction(this));
mActions.push_back(new SmoothHeightAction(this));
mActions.push_back(new SmoothSlopeAction(this));
mActions.push_back(new PaintNoiseAction(this));
//mActions.push_back(new ThermalErosionAction(this));
// set the default action
mCurrentAction = mActions[0];
mRenderBrush = mCurrentAction->useMouseBrush();
// persist data defaults
mRenderBorder = true;
mBorderHeight = 10;
mBorderFillColor.set(0,255,0,20);
mBorderFrameColor.set(0,255,0,128);
mBorderLineMode = false;
mSelectionHidden = false;
mRenderVertexSelection = false;
mRenderSolidBrush = false;
mProcessUsesBrush = false;
//
mAdjustHeightVal = 10;
mSetHeightVal = 100;
mScaleVal = 1;
mSmoothFactor = 0.1f;
mNoiseFactor = 1.0f;
mMaterialGroup = 0;
mSoftSelectRadius = 50.f;
mAdjustHeightMouseScale = 0.1f;
mSoftSelectDefaultFilter = StringTable->insert("1.000000 0.833333 0.666667 0.500000 0.333333 0.166667 0.000000");
mSoftSelectFilter = mSoftSelectDefaultFilter;
mSlopeMinAngle = 0.0f;
mSlopeMaxAngle = 90.0f;
}
TerrainEditor::~TerrainEditor()
{
// mouse
delete mMouseBrush;
// terrain actions
U32 i;
for(i = 0; i < mActions.size(); i++)
delete mActions[i];
// undo stuff
delete mUndoSel;
}
TerrainAction * TerrainEditor::lookupAction(const char * name)
{
for(U32 i = 0; i < mActions.size(); i++)
if(!dStricmp(mActions[i]->getName(), name))
return(mActions[i]);
return(0);
}
bool TerrainEditor::onAdd()
{
if ( !Parent::onAdd() )
return false;
GFXStateBlockDesc desc;
desc.setZReadWrite( false );
desc.zWriteEnable = false;
desc.setCullMode( GFXCullNone );
desc.setBlend( true, GFXBlendSrcAlpha, GFXBlendDestAlpha );
mStateBlock = GFX->createStateBlock( desc );
return true;
}
bool TerrainEditor::onWake()
{
if ( !Parent::onWake() )
return false;
// Push our default cursor on here once.
GuiCanvas *root = getRoot();
if ( root )
{
S32 currCursor = PlatformCursorController::curArrow;
PlatformWindow *window = root->getPlatformWindow();
PlatformCursorController *controller = window->getCursorController();
controller->pushCursor( currCursor );
}
return true;
}
void TerrainEditor::onSleep()
{
// Pop our default cursor off.
GuiCanvas *root = getRoot();
if ( root )
{
PlatformWindow *window = root->getPlatformWindow();
PlatformCursorController *controller = window->getCursorController();
controller->popCursor();
}
Parent::onSleep();
}
void TerrainEditor::get3DCursor( GuiCursor *&cursor,
bool &visible,
const Gui3DMouseEvent &event_ )
{
cursor = NULL;
visible = false;
GuiCanvas *root = getRoot();
if ( !root )
return;
S32 currCursor = PlatformCursorController::curArrow;
if ( root->mCursorChanged == currCursor )
return;
PlatformWindow *window = root->getPlatformWindow();
PlatformCursorController *controller = window->getCursorController();
// We've already changed the cursor,
// so set it back before we change it again.
if( root->mCursorChanged != -1)
controller->popCursor();
// Now change the cursor shape
controller->pushCursor(currCursor);
root->mCursorChanged = currCursor;
}
void TerrainEditor::onDeleteNotify(SimObject * object)
{
Parent::onDeleteNotify(object);
if (dynamic_cast<TerrainBlock*>(object) == mActiveTerrain)
mActiveTerrain = NULL;
}
TerrainBlock* TerrainEditor::getClientTerrain( TerrainBlock *serverTerrain ) const
{
if ( !serverTerrain )
serverTerrain = mActiveTerrain;
return serverTerrain ? dynamic_cast<TerrainBlock*>( serverTerrain->getClientObject() ) : NULL;
}
bool TerrainEditor::isMainTile(const GridPoint & gPoint) const
{
const S32 blockSize = (S32)gPoint.terrainBlock->getBlockSize();
Point2I testPos = gPoint.gridPos;
if (!dStrcmp(getCurrentAction(),"paintMaterial"))
{
if (testPos.x == blockSize)
testPos.x--;
if (testPos.y == blockSize)
testPos.y--;
}
return (testPos.x >= 0 && testPos.x < blockSize && testPos.y >= 0 && testPos.y < blockSize);
}
TerrainBlock* TerrainEditor::getTerrainUnderWorldPoint(const Point3F & wPos)
{
PROFILE_SCOPE( TerrainEditor_GetTerrainUnderWorldPoint );
// Cast a ray straight down from the world position and see which
// Terrain is the closest to our starting point
Point3F startPnt = wPos;
Point3F endPnt = wPos + Point3F(0.0f, 0.0f, -1000.0f);
S32 blockIndex = -1;
F32 nearT = 1.0f;
for (U32 i = 0; i < mTerrainBlocks.size(); i++)
{
Point3F tStartPnt, tEndPnt;
mTerrainBlocks[i]->getWorldTransform().mulP(startPnt, &tStartPnt);
mTerrainBlocks[i]->getWorldTransform().mulP(endPnt, &tEndPnt);
RayInfo ri;
if (mTerrainBlocks[i]->castRayI(tStartPnt, tEndPnt, &ri, true))
{
if (ri.t < nearT)
{
blockIndex = i;
nearT = ri.t;
}
}
}
if (blockIndex > -1)
return mTerrainBlocks[blockIndex];
return NULL;
}
bool TerrainEditor::gridToWorld(const GridPoint & gPoint, Point3F & wPos)
{
PROFILE_SCOPE( TerrainEditor_GridToWorld );
const MatrixF & mat = gPoint.terrainBlock->getTransform();
Point3F origin;
mat.getColumn(3, &origin);
wPos.x = gPoint.gridPos.x * gPoint.terrainBlock->getSquareSize() + origin.x;
wPos.y = gPoint.gridPos.y * gPoint.terrainBlock->getSquareSize() + origin.y;
wPos.z = getGridHeight(gPoint) + origin.z;
return isMainTile(gPoint);
}
bool TerrainEditor::gridToWorld(const Point2I & gPos, Point3F & wPos, TerrainBlock* terrain)
{
GridPoint gridPoint;
gridPoint.gridPos = gPos;
gridPoint.terrainBlock = terrain;
return gridToWorld(gridPoint, wPos);
}
bool TerrainEditor::worldToGrid(const Point3F & wPos, GridPoint & gPoint)
{
PROFILE_SCOPE( TerrainEditor_WorldToGrid );
// If the grid point TerrainBlock is NULL then find the closest Terrain underneath that
// point - pad a little upward in case our incoming point already lies exactly on the terrain
if (!gPoint.terrainBlock)
gPoint.terrainBlock = getTerrainUnderWorldPoint(wPos + Point3F(0.0f, 0.0f, 0.05f));
if (gPoint.terrainBlock == NULL)
return false;
gPoint.gridPos = gPoint.terrainBlock->getGridPos(wPos);
return isMainTile(gPoint);
}
bool TerrainEditor::worldToGrid(const Point3F & wPos, Point2I & gPos, TerrainBlock* terrain)
{
GridPoint gridPoint;
gridPoint.terrainBlock = terrain;
bool ret = worldToGrid(wPos, gridPoint);
gPos = gridPoint.gridPos;
return ret;
}
bool TerrainEditor::gridToCenter(const Point2I & gPos, Point2I & cPos) const
{
// TODO: What is this for... megaterrain or tiled terrains?
cPos.x = gPos.x; // & TerrainBlock::BlockMask;
cPos.y = gPos.y;// & TerrainBlock::BlockMask;
//if (gPos.x == TerrainBlock::BlockSize)
// cPos.x = gPos.x;
//if (gPos.y == TerrainBlock::BlockSize)
// cPos.y = gPos.y;
//return isMainTile(gPos);
return true;
}
//------------------------------------------------------------------------------
//bool TerrainEditor::getGridInfo(const Point3F & wPos, GridInfo & info)
//{
// Point2I gPos;
// worldToGrid(wPos, gPos);
// return getGridInfo(gPos, info);
//}
bool TerrainEditor::getGridInfo(const GridPoint & gPoint, GridInfo & info)
{
//
info.mGridPoint = gPoint;
info.mMaterial = getGridMaterial(gPoint);
info.mHeight = getGridHeight(gPoint);
info.mWeight = 1.f;
info.mPrimarySelect = true;
info.mMaterialChanged = false;
Point2I cPos;
gridToCenter(gPoint.gridPos, cPos);
return isMainTile(gPoint);
}
bool TerrainEditor::getGridInfo(const Point2I & gPos, GridInfo & info, TerrainBlock* terrain)
{
GridPoint gridPoint;
gridPoint.gridPos = gPos;
gridPoint.terrainBlock = terrain;
return getGridInfo(gridPoint, info);
}
void TerrainEditor::getGridInfos(const GridPoint & gPoint, Vector<GridInfo>& infos)
{
PROFILE_SCOPE( TerrainEditor_GetGridInfos );
// First we test against the brush terrain so that we can
// favor it (this should be the same as the active terrain)
bool foundBrush = false;
GridInfo baseInfo;
if (getGridInfo(gPoint, baseInfo))
{
infos.push_back(baseInfo);
foundBrush = true;
}
// We are going to need the world position to test against
Point3F wPos;
gridToWorld(gPoint, wPos);
// Now loop through our terrain blocks and decide which ones hit the point
// If we already found a hit against our brush terrain we only add points
// that are relatively close to the found point
for (U32 i = 0; i < mTerrainBlocks.size(); i++)
{
// Skip if we've already found the point on the brush terrain
if (foundBrush && mTerrainBlocks[i] == baseInfo.mGridPoint.terrainBlock)
continue;
// Get our grid position
Point2I gPos;
worldToGrid(wPos, gPos, mTerrainBlocks[i]);
GridInfo info;
if (getGridInfo(gPos, info, mTerrainBlocks[i]))
{
// Skip adding this if we already found a GridInfo from the brush terrain
// and the resultant world point isn't equivalent
if (foundBrush)
{
// Convert back to world (since the height can be different)
// Possibly use getHeight() here?
Point3F testWorldPt;
gridToWorld(gPos, testWorldPt, mTerrainBlocks[i]);
if (mFabs( wPos.z - testWorldPt.z ) > 4.0f )
continue;
}
infos.push_back(info);
}
}
}
void TerrainEditor::setGridInfo(const GridInfo & info, bool checkActive)
{
PROFILE_SCOPE( TerrainEditor_SetGridInfo );
setGridHeight(info.mGridPoint, info.mHeight);
setGridMaterial(info.mGridPoint, info.mMaterial);
}
F32 TerrainEditor::getGridHeight(const GridPoint & gPoint)
{
PROFILE_SCOPE( TerrainEditor_GetGridHeight );
Point2I cPos;
gridToCenter( gPoint.gridPos, cPos );
const TerrainFile *file = gPoint.terrainBlock->getFile();
return fixedToFloat( file->getHeight( cPos.x, cPos.y ) );
}
void TerrainEditor::gridUpdateComplete( bool materialChanged )
{
PROFILE_SCOPE( TerrainEditor_GridUpdateComplete );
// TODO: This updates all terrains and not just the ones
// that were changed. We should keep track of the mGridUpdate
// in world space and transform it into terrain space.
if(mGridUpdateMin.x <= mGridUpdateMax.x)
{
for (U32 i = 0; i < mTerrainBlocks.size(); i++)
{
TerrainBlock *clientTerrain = getClientTerrain( mTerrainBlocks[i] );
if ( materialChanged )
clientTerrain->updateGridMaterials(mGridUpdateMin, mGridUpdateMax);
mTerrainBlocks[i]->updateGrid(mGridUpdateMin, mGridUpdateMax);
clientTerrain->updateGrid(mGridUpdateMin, mGridUpdateMax);
}
}
mGridUpdateMin.set( S32_MAX, S32_MAX );
mGridUpdateMax.set( 0, 0 );
mNeedsGridUpdate = false;
}
void TerrainEditor::materialUpdateComplete()
{
PROFILE_SCOPE( TerrainEditor_MaterialUpdateComplete );
if(mActiveTerrain && (mGridUpdateMin.x <= mGridUpdateMax.x))
{
TerrainBlock * clientTerrain = getClientTerrain(mActiveTerrain);
clientTerrain->updateGridMaterials(mGridUpdateMin, mGridUpdateMax);
}
mGridUpdateMin.set( S32_MAX, S32_MAX );
mGridUpdateMax.set( 0, 0 );
mNeedsMaterialUpdate = false;
}
void TerrainEditor::setGridHeight(const GridPoint & gPoint, const F32 height)
{
PROFILE_SCOPE( TerrainEditor_SetGridHeight );
Point2I cPos;
gridToCenter(gPoint.gridPos, cPos);
mGridUpdateMin.setMin( cPos );
mGridUpdateMax.setMax( cPos );
gPoint.terrainBlock->setHeight(cPos, height);
}
U8 TerrainEditor::getGridMaterial( const GridPoint &gPoint ) const
{
PROFILE_SCOPE( TerrainEditor_GetGridMaterial );
Point2I cPos;
gridToCenter( gPoint.gridPos, cPos );
const TerrainFile *file = gPoint.terrainBlock->getFile();
return file->getLayerIndex( cPos.x, cPos.y );
}
void TerrainEditor::setGridMaterial( const GridPoint &gPoint, U8 index )
{
PROFILE_SCOPE( TerrainEditor_SetGridMaterial );
Point2I cPos;
gridToCenter( gPoint.gridPos, cPos );
TerrainFile *file = gPoint.terrainBlock->getFile();
// If we changed the empty state then we need
// to do a grid update as well.
U8 currIndex = file->getLayerIndex( cPos.x, cPos.y );
if ( ( currIndex == (U8)-1 && index != (U8)-1 ) ||
( currIndex != (U8)-1 && index == (U8)-1 ) )
{
mGridUpdateMin.setMin( cPos );
mGridUpdateMax.setMax( cPos );
mNeedsGridUpdate = true;
}
file->setLayerIndex( cPos.x, cPos.y, index );
}
//------------------------------------------------------------------------------
TerrainBlock* TerrainEditor::collide(const Gui3DMouseEvent & evt, Point3F & pos)
{
PROFILE_SCOPE( TerrainEditor_Collide );
if (mTerrainBlocks.size() == 0)
return NULL;
if ( mMouseDown && !dStrcmp(getCurrentAction(),"paintMaterial") )
{
if ( !mActiveTerrain )
return NULL;
Point3F tpos, tvec;
tpos = evt.pos;
tvec = evt.vec;
mMousePlane.intersect( evt.pos, evt.vec, &pos );
return mActiveTerrain;
}
const U32 mask = TerrainObjectType;
Point3F start( evt.pos );
Point3F end( evt.pos + ( evt.vec * 10000.0f ) );
RayInfo rinfo;
bool hit = gServerContainer.castRay( start, end, mask, &rinfo );
if ( !hit )
return NULL;
pos = rinfo.point;
return (TerrainBlock*)(rinfo.object);
//
//// call the terrain block's ray collision routine directly
//Point3F startPnt = event.pos;
//Point3F endPnt = event.pos + event.vec * 1000.0f;
//S32 blockIndex = -1;
//F32 nearT = 1.0f;
//for (U32 i = 0; i < mTerrainBlocks.size(); i++)
//{
// Point3F tStartPnt, tEndPnt;
// mTerrainBlocks[i]->getWorldTransform().mulP(startPnt, &tStartPnt);
// mTerrainBlocks[i]->getWorldTransform().mulP(endPnt, &tEndPnt);
// RayInfo ri;
// if (mTerrainBlocks[i]->castRayI(tStartPnt, tEndPnt, &ri, true))
// {
// if (ri.t < nearT)
// {
// blockIndex = i;
// nearT = ri.t;
// }
// }
//}
//if (blockIndex > -1)
//{
// pos.interpolate(startPnt, endPnt, nearT);
// return mTerrainBlocks[blockIndex];
//}
//return NULL;
}
//------------------------------------------------------------------------------
void TerrainEditor::updateGuiInfo()
{
PROFILE_SCOPE( TerrainEditor_UpdateGuiInfo );
char buf[128];
// mouse num grids
// mouse avg height
// selection num grids
// selection avg height
dSprintf(buf, sizeof(buf), "%d %g %g %g %d %g",
mMouseBrush->size(), mMouseBrush->getMinHeight(),
mMouseBrush->getAvgHeight(), mMouseBrush->getMaxHeight(),
mDefaultSel.size(), mDefaultSel.getAvgHeight());
Con::executef(this, "onGuiUpdate", buf);
// If the brush setup has changed send out
// a notification of that!
if ( mBrushChanged && isMethod( "onBrushChanged" ) )
{
mBrushChanged = false;
Con::executef( this, "onBrushChanged" );
}
}
//------------------------------------------------------------------------------
void TerrainEditor::onPreRender()
{
PROFILE_SCOPE( TerrainEditor_OnPreRender );
if ( mNeedsGridUpdate )
gridUpdateComplete( mNeedsMaterialUpdate );
else if ( mNeedsMaterialUpdate )
materialUpdateComplete();
Parent::onPreRender();
}
void TerrainEditor::renderScene(const RectI &)
{
PROFILE_SCOPE( TerrainEditor_RenderScene );
if(mTerrainBlocks.size() == 0)
return;
if(!mSelectionHidden)
renderSelection(mDefaultSel, ColorF::RED, ColorF::GREEN, ColorF::BLUE, ColorF::BLUE, true, false);
if(mRenderBrush && mMouseBrush->size())
renderBrush(*mMouseBrush, ColorF::GREEN, ColorF::RED, ColorF::BLUE, ColorF::BLUE, false, true);
if(mRenderBorder)
renderBorder();
}
//------------------------------------------------------------------------------
void TerrainEditor::renderGui( Point2I offset, const RectI &updateRect )
{
PROFILE_SCOPE( TerrainEditor_RenderGui );
if ( !mActiveTerrain )
return;
// Just in case...
if ( mMouseBrush->getGridPoint().terrainBlock != mActiveTerrain )
mMouseBrush->setTerrain( mActiveTerrain );
mMouseBrush->render();
}
void TerrainEditor::renderPoints( const Vector<GFXVertexPCT> &pointList )
{
PROFILE_SCOPE( TerrainEditor_RenderPoints );
const U32 pointCount = pointList.size();
const U32 vertCount = pointCount * 6;
GFXStateBlockDesc desc;
desc.setBlend( true );
desc.setZReadWrite( false, false );
GFX->setupGenericShaders();
GFX->setStateBlockByDesc( desc );
U32 vertsLeft = vertCount;
U32 offset = 0;
while ( vertsLeft > 0 )
{
U32 vertsThisDrawCall = getMin( (U32)vertsLeft, (U32)MAX_DYNAMIC_VERTS );
vertsLeft -= vertsThisDrawCall;
GFXVertexBufferHandle<GFXVertexPC> vbuff( GFX, vertsThisDrawCall, GFXBufferTypeVolatile );
GFXVertexPC *vert = vbuff.lock();
const U32 loops = vertsThisDrawCall / 6;
for ( S32 i = 0; i < loops; i++ )
{
const GFXVertexPCT &pointInfo = pointList[i + offset];
vert[0].color = vert[1].color = vert[2].color = vert[3].color = vert[4].color = vert[5].color = pointInfo.color;
const F32 halfSize = pointInfo.texCoord.x * 0.5f;
const Point3F &pos = pointInfo.point;
Point3F p0( pos.x - halfSize, pos.y - halfSize, 0.0f );
Point3F p1( pos.x + halfSize, pos.y - halfSize, 0.0f );
Point3F p2( pos.x + halfSize, pos.y + halfSize, 0.0f );
Point3F p3( pos.x - halfSize, pos.y + halfSize, 0.0f );
vert[0].point = p0;
vert[1].point = p1;
vert[2].point = p2;
vert[3].point = p0;
vert[4].point = p2;
vert[5].point = p3;
vert += 6;
}
vbuff.unlock();
GFX->setVertexBuffer( vbuff );
GFX->drawPrimitive( GFXTriangleList, 0, vertsThisDrawCall / 3 );
offset += loops;
}
}
//------------------------------------------------------------------------------
void TerrainEditor::renderSelection( const Selection & sel, const ColorF & inColorFull, const ColorF & inColorNone, const ColorF & outColorFull, const ColorF & outColorNone, bool renderFill, bool renderFrame )
{
PROFILE_SCOPE( TerrainEditor_RenderSelection );
// Draw nothing if nothing selected.
if(sel.size() == 0)
return;
Vector<GFXVertexPC> vertexBuffer;
ColorF color;
ColorI iColor;
vertexBuffer.setSize(sel.size() * 5);
F32 squareSize = ( mActiveTerrain ) ? mActiveTerrain->getSquareSize() : 1;
// 'RenderVertexSelection' looks really bad so just always use the good one.
if( false && mRenderVertexSelection)
{
for(U32 i = 0; i < sel.size(); i++)
{
Point3F wPos;
bool center = gridToWorld(sel[i].mGridPoint, wPos);
F32 weight = sel[i].mWeight;
if(center)
{
if ( weight < 0.f || weight > 1.f )
color = inColorFull;
else
color.interpolate( inColorNone, inColorFull, weight );
}
else
{
if ( weight < 0.f || weight > 1.f)
color = outColorFull;
else
color.interpolate( outColorFull, outColorNone, weight );
}
//
iColor = color;
GFXVertexPC *verts = &(vertexBuffer[i * 5]);
verts[0].point = wPos + Point3F(-squareSize, -squareSize, 0);
verts[0].color = iColor;
verts[1].point = wPos + Point3F( squareSize, -squareSize, 0);
verts[1].color = iColor;
verts[2].point = wPos + Point3F( squareSize, squareSize, 0);
verts[2].color = iColor;
verts[3].point = wPos + Point3F(-squareSize, squareSize, 0);
verts[3].color = iColor;
verts[4].point = verts[0].point;
verts[4].color = iColor;
}
}
else
{
// walk the points in the selection
for(U32 i = 0; i < sel.size(); i++)
{
Point2I gPos = sel[i].mGridPoint.gridPos;
GFXVertexPC *verts = &(vertexBuffer[i * 5]);
bool center = gridToWorld(sel[i].mGridPoint, verts[0].point);
gridToWorld(Point2I(gPos.x + 1, gPos.y), verts[1].point, sel[i].mGridPoint.terrainBlock);
gridToWorld(Point2I(gPos.x + 1, gPos.y + 1), verts[2].point, sel[i].mGridPoint.terrainBlock);
gridToWorld(Point2I(gPos.x, gPos.y + 1), verts[3].point, sel[i].mGridPoint.terrainBlock);
verts[4].point = verts[0].point;
F32 weight = sel[i].mWeight;
if( !mRenderSolidBrush )
{
if ( center )
{
if ( weight < 0.f || weight > 1.f )
color = inColorFull;
else
color.interpolate(inColorNone, inColorFull, weight );
}
else
{
if( weight < 0.f || weight > 1.f )
color = outColorFull;
else
color.interpolate(outColorFull, outColorNone, weight );
}
iColor = color;
}
else
{
if ( center )
{
iColor = inColorNone;
}
else
{
iColor = outColorFull;
}
}
verts[0].color = iColor;
verts[1].color = iColor;
verts[2].color = iColor;
verts[3].color = iColor;
verts[4].color = iColor;
}
}
// Render this bad boy, by stuffing everything into a volatile buffer
// and rendering...
GFXVertexBufferHandle<GFXVertexPC> selectionVB(GFX, vertexBuffer.size(), GFXBufferTypeStatic);
selectionVB.lock(0, vertexBuffer.size());
// Copy stuff
dMemcpy((void*)&selectionVB[0], (void*)&vertexBuffer[0], sizeof(GFXVertexPC) * vertexBuffer.size());
selectionVB.unlock();
GFX->setupGenericShaders();
GFX->setStateBlock( mStateBlock );
GFX->setVertexBuffer(selectionVB);
if(renderFill)
for(U32 i=0; i < sel.size(); i++)
GFX->drawPrimitive( GFXTriangleFan, i*5, 4);
if(renderFrame)
for(U32 i=0; i < sel.size(); i++)
GFX->drawPrimitive( GFXLineStrip , i*5, 4);
}
void TerrainEditor::renderBrush( const Brush & brush, const ColorF & inColorFull, const ColorF & inColorNone, const ColorF & outColorFull, const ColorF & outColorNone, bool renderFill, bool renderFrame )
{
}
void TerrainEditor::renderBorder()
{
// TODO: Disabled rendering the terrain borders... it was
// very annoying getting a fullscreen green tint on things.
//
// We should consider killing this all together or coming
// up with a new technique.
/*
Point2I pos(0,0);
Point2I dir[4] = {
Point2I(1,0),
Point2I(0,1),
Point2I(-1,0),
Point2I(0,-1)
};
GFX->setStateBlock( mStateBlock );
//
if(mBorderLineMode)
{
PrimBuild::color(mBorderFrameColor);
PrimBuild::begin( GFXLineStrip, TerrainBlock::BlockSize * 4 + 1 );
for(U32 i = 0; i < 4; i++)
{
for(U32 j = 0; j < TerrainBlock::BlockSize; j++)
{
Point3F wPos;
gridToWorld(pos, wPos, mActiveTerrain);
PrimBuild::vertex3fv( wPos );
pos += dir[i];
}
}
Point3F wPos;
gridToWorld(Point2I(0,0), wPos, mActiveTerrain);
PrimBuild::vertex3fv( wPos );
PrimBuild::end();
}
else
{
GridSquare * gs = mActiveTerrain->findSquare(TerrainBlock::BlockShift, Point2I(0,0));
F32 height = F32(gs->maxHeight) * 0.03125f + mBorderHeight;
const MatrixF & mat = mActiveTerrain->getTransform();
Point3F pos;
mat.getColumn(3, &pos);
Point2F min(pos.x, pos.y);
Point2F max(pos.x + TerrainBlock::BlockSize * mActiveTerrain->getSquareSize(),
pos.y + TerrainBlock::BlockSize * mActiveTerrain->getSquareSize());
ColorI & a = mBorderFillColor;
ColorI & b = mBorderFrameColor;
for(U32 i = 0; i < 2; i++)
{
//
if(i){ PrimBuild::color(a); PrimBuild::begin( GFXTriangleFan, 4 ); } else { PrimBuild::color(b); PrimBuild::begin( GFXLineStrip, 5 ); }
PrimBuild::vertex3f(min.x, min.y, 0);
PrimBuild::vertex3f(max.x, min.y, 0);
PrimBuild::vertex3f(max.x, min.y, height);
PrimBuild::vertex3f(min.x, min.y, height);
if(!i) PrimBuild::vertex3f( min.x, min.y, 0.f );
PrimBuild::end();
//
if(i){ PrimBuild::color(a); PrimBuild::begin( GFXTriangleFan, 4 ); } else { PrimBuild::color(b); PrimBuild::begin( GFXLineStrip, 5 ); }
PrimBuild::vertex3f(min.x, max.y, 0);
PrimBuild::vertex3f(max.x, max.y, 0);
PrimBuild::vertex3f(max.x, max.y, height);
PrimBuild::vertex3f(min.x, max.y, height);
if(!i) PrimBuild::vertex3f( min.x, min.y, 0.f );
PrimBuild::end();
//
if(i){ PrimBuild::color(a); PrimBuild::begin( GFXTriangleFan, 4 ); } else { PrimBuild::color(b); PrimBuild::begin( GFXLineStrip, 5 ); }
PrimBuild::vertex3f(min.x, min.y, 0);
PrimBuild::vertex3f(min.x, max.y, 0);
PrimBuild::vertex3f(min.x, max.y, height);
PrimBuild::vertex3f(min.x, min.y, height);
if(!i) PrimBuild::vertex3f( min.x, min.y, 0.f );
PrimBuild::end();
//
if(i){ PrimBuild::color(a); PrimBuild::begin( GFXTriangleFan, 4 ); } else { PrimBuild::color(b); PrimBuild::begin( GFXLineStrip, 5 ); }
PrimBuild::vertex3f(max.x, min.y, 0);
PrimBuild::vertex3f(max.x, max.y, 0);
PrimBuild::vertex3f(max.x, max.y, height);
PrimBuild::vertex3f(max.x, min.y, height);
if(!i) PrimBuild::vertex3f( min.x, min.y, 0.f );
PrimBuild::end();
}
}
*/
}
void TerrainEditor::submitUndo( Selection *sel )
{
// Grab the mission editor undo manager.
UndoManager *undoMan = NULL;
if ( !Sim::findObject( "EUndoManager", undoMan ) )
{
Con::errorf( "TerrainEditor::submitUndo() - EUndoManager not found!" );
return;
}
// Create and submit the action.
TerrainEditorUndoAction *action = new TerrainEditorUndoAction( "Terrain Editor Action" );
action->mSel = sel;
action->mTerrainEditor = this;
undoMan->addAction( action );
// Mark the editor as dirty!
setDirty();
}
void TerrainEditor::TerrainEditorUndoAction::undo()
{
// NOTE: This function also handles TerrainEditorUndoAction::redo().
bool materialChanged = false;
for (U32 i = 0; i < mSel->size(); i++)
{
// Grab the current grid info for this point.
GridInfo info;
mTerrainEditor->getGridInfo( (*mSel)[i].mGridPoint, info );
info.mMaterialChanged = (*mSel)[i].mMaterialChanged;
materialChanged |= info.mMaterialChanged;
// Restore the previous grid info.
mTerrainEditor->setGridInfo( (*mSel)[i] );
// Save the old grid info so we can
// restore it later.
(*mSel)[i] = info;
}
// Mark the editor as dirty!
mTerrainEditor->setDirty();
mTerrainEditor->gridUpdateComplete( materialChanged );
mTerrainEditor->mMouseBrush->update();
}
void TerrainEditor::submitMaterialUndo( String actionName )
{
// Grab the mission editor undo manager.
UndoManager *undoMan = NULL;
if ( !Sim::findObject( "EUndoManager", undoMan ) )
{
Con::errorf( "TerrainEditor::submitMaterialUndo() - EUndoManager not found!" );
return;
}
TerrainBlock *terr = getClientTerrain();
// Create and submit the action.
TerrainMaterialUndoAction *action = new TerrainMaterialUndoAction( actionName );
action->mTerrain = terr;
action->mMaterials = terr->getMaterials();
action->mLayerMap = terr->getLayerMap();
action->mEditor = this;
undoMan->addAction( action );
// Mark the editor as dirty!
setDirty();
}
void TerrainEditor::onMaterialUndo( TerrainBlock *terr )
{
setDirty();
scheduleMaterialUpdate();
setGridUpdateMinMax();
terr->mDetailsDirty = true;
terr->mLayerTexDirty = true;
Con::executef( this, "onMaterialUndo" );
}
void TerrainEditor::TerrainMaterialUndoAction::undo()
{
Vector<TerrainMaterial*> tempMaterials = mTerrain->getMaterials();
Vector<U8> tempLayers = mTerrain->getLayerMap();
mTerrain->setMaterials(mMaterials);
mTerrain->setLayerMap(mLayerMap);
mMaterials = tempMaterials;
mLayerMap = tempLayers;
mEditor->onMaterialUndo( mTerrain );
}
void TerrainEditor::TerrainMaterialUndoAction::redo()
{
undo();
}
class TerrainProcessActionEvent : public SimEvent
{
U32 mSequence;
public:
TerrainProcessActionEvent(U32 seq)
{
mSequence = seq;
}
void process(SimObject *object)
{
((TerrainEditor *) object)->processActionTick(mSequence);
}
};
void TerrainEditor::processActionTick(U32 sequence)
{
if(mMouseDownSeq == sequence)
{
Sim::postEvent(this, new TerrainProcessActionEvent(mMouseDownSeq), Sim::getCurrentTime() + 30);
mCurrentAction->process(mMouseBrush, mLastEvent, false, TerrainAction::Update);
}
}
bool TerrainEditor::onInputEvent(const InputEventInfo & event)
{
/*
if ( mRightMousePassThru &&
event.deviceType == KeyboardDeviceType &&
event.objType == SI_KEY &&
event.objInst == KEY_TAB &&
event.action == SI_MAKE )
{
if ( isMethod( "onToggleToolWindows" ) )
Con::executef( this, "onToggleToolWindows" );
}
*/
return Parent::onInputEvent( event );
}
void TerrainEditor::on3DMouseDown(const Gui3DMouseEvent & event)
{
getRoot()->showCursor( false );
if(mTerrainBlocks.size() == 0)
return;
if (!dStrcmp(getCurrentAction(),"paintMaterial"))
{
Point3F pos;
TerrainBlock* hitTerrain = collide(event, pos);
if(!hitTerrain)
return;
// Set the active terrain
bool changed = mActiveTerrain != hitTerrain;
mActiveTerrain = hitTerrain;
if (changed)
{
Con::executef(this, "onActiveTerrainChange", Con::getIntArg(hitTerrain->getId()));
mMouseBrush->setTerrain(mActiveTerrain);
//if(mRenderBrush)
//mCursorVisible = false;
mMousePos = pos;
mMouseBrush->setPosition(mMousePos);
return;
}
}
else if ((event.modifier & SI_ALT) && !dStrcmp(getCurrentAction(),"setHeight"))
{
// Set value to terrain height at mouse position
GridInfo info;
getGridInfo(mMouseBrush->getGridPoint(), info);
mSetHeightVal = info.mHeight;
mBrushChanged = true;
return;
}
mMousePlane.set( mMousePos, Point3F(0,0,1) );
mMouseDown = true;
mSelectionLocked = false;
mouseLock();
mMouseDownSeq++;
mUndoSel = new Selection;
mCurrentAction->process(mMouseBrush, event, true, TerrainAction::Begin);
// process on ticks - every 30th of a second.
Sim::postEvent(this, new TerrainProcessActionEvent(mMouseDownSeq), Sim::getCurrentTime() + 30);
}
void TerrainEditor::on3DMouseMove(const Gui3DMouseEvent & event)
{
PROFILE_SCOPE( TerrainEditor_On3DMouseMove );
if(mTerrainBlocks.size() == 0)
return;
Point3F pos;
TerrainBlock* hitTerrain = collide(event, pos);
if(!hitTerrain)
{
mMouseBrush->reset();
}
else
{
// We do not change the active terrain as the mouse moves when
// in painting mode. This is because it causes the material
// window to change as you cursor over to it.
if ( dStrcmp(getCurrentAction(),"paintMaterial") != 0 )
{
// Set the active terrain
bool changed = mActiveTerrain != hitTerrain;
mActiveTerrain = hitTerrain;
if (changed)
Con::executef(this, "onActiveTerrainChange", Con::getIntArg(hitTerrain->getId()));
}
mMousePos = pos;
mMouseBrush->setTerrain(mActiveTerrain);
mMouseBrush->setPosition(mMousePos);
}
}
void TerrainEditor::on3DMouseDragged(const Gui3DMouseEvent & event)
{
PROFILE_SCOPE( TerrainEditor_On3DMouseDragged );
if ( mTerrainBlocks.empty() )
return;
if ( !isMouseLocked() )
return;
Point3F pos;
if ( !mSelectionLocked )
{
if ( !collide( event, pos) )
mMouseBrush->reset();
}
// check if the mouse has actually moved in grid space
bool selChanged = false;
if ( !mSelectionLocked )
{
Point2I gMouse;
Point2I gLastMouse;
worldToGrid( pos, gMouse );
worldToGrid( mMousePos, gLastMouse );
mMousePos = pos;
mMouseBrush->setPosition( mMousePos );
selChanged = gMouse != gLastMouse;
}
mCurrentAction->process( mMouseBrush, event, true, TerrainAction::Update );
}
void TerrainEditor::on3DMouseUp(const Gui3DMouseEvent & event)
{
mMouseDown = false;
getRoot()->showCursor( true );
if ( mTerrainBlocks.size() == 0 )
return;
if ( isMouseLocked() )
{
mouseUnlock();
mMouseDownSeq++;
mCurrentAction->process( mMouseBrush, event, false, TerrainAction::End );
if ( mUndoSel->size() )
submitUndo( mUndoSel );
else
delete mUndoSel;
mUndoSel = 0;
mInAction = false;
}
}
bool TerrainEditor::onMouseWheelDown( const GuiEvent & event )
{
if ( event.modifier & SI_PRIMARY_CTRL && event.modifier & SI_SHIFT )
{
setBrushPressure( mBrushPressure - 0.1f );
return true;
}
else if ( event.modifier & SI_SHIFT )
{
setBrushSoftness( mBrushSoftness + 0.05f );
return true;
}
else if ( event.modifier & SI_PRIMARY_CTRL )
{
Point2I newBrush = getBrushSize() - Point2I(1,1);
setBrushSize( newBrush.x, newBrush.y );
return true;
}
return Parent::onMouseWheelDown( event );
}
bool TerrainEditor::onMouseWheelUp( const GuiEvent & event )
{
if ( event.modifier & SI_PRIMARY_CTRL && event.modifier & SI_SHIFT )
{
setBrushPressure( mBrushPressure + 0.1f );
return true;
}
else if ( event.modifier & SI_SHIFT )
{
setBrushSoftness( mBrushSoftness - 0.05f );
return true;
}
else if( event.modifier & SI_PRIMARY_CTRL )
{
Point2I newBrush = getBrushSize() + Point2I(1,1);
setBrushSize( newBrush.x, newBrush.y );
return true;
}
return Parent::onMouseWheelUp( event );
}
//------------------------------------------------------------------------------
// any console function which depends on a terrainBlock attached to the editor
// should call this
bool checkTerrainBlock(TerrainEditor * object, const char * funcName)
{
if(!object->terrainBlockValid())
{
Con::errorf(ConsoleLogEntry::Script, "TerrainEditor::%s: not attached to a terrain block!", funcName);
return(false);
}
return(true);
}
void TerrainEditor::attachTerrain(TerrainBlock *terrBlock)
{
mActiveTerrain = terrBlock;
mTerrainBlocks.push_back_unique(terrBlock);
}
void TerrainEditor::detachTerrain(TerrainBlock *terrBlock)
{
if (mActiveTerrain == terrBlock)
mActiveTerrain = NULL; //do we want to set this to an existing terrain?
if (mMouseBrush->getGridPoint().terrainBlock == terrBlock)
mMouseBrush->setTerrain(NULL);
// reset the brush as its gridinfos may still have references to the old terrain
mMouseBrush->reset();
mTerrainBlocks.remove(terrBlock);
}
TerrainBlock* TerrainEditor::getTerrainBlock(S32 index)
{
if(index < 0 || index >= mTerrainBlocks.size())
return NULL;
return mTerrainBlocks[index];
}
void TerrainEditor::getTerrainBlocksMaterialList(Vector<StringTableEntry>& list)
{
for(S32 i=0; i<mTerrainBlocks.size(); ++i)
{
TerrainBlock* tb = mTerrainBlocks[i];
if(!tb)
continue;
for(S32 m=0; m<tb->getMaterialCount(); ++m)
{
TerrainMaterial* mat = tb->getMaterial(m);
if (mat)
list.push_back_unique(mat->getInternalName());
}
}
}
void TerrainEditor::setBrushType( const char *type )
{
if ( mMouseBrush && dStrcmp( mMouseBrush->getType(), type ) == 0 )
return;
if(!dStricmp(type, "box"))
{
delete mMouseBrush;
mMouseBrush = new BoxBrush(this);
mBrushChanged = true;
}
else if(!dStricmp(type, "ellipse"))
{
delete mMouseBrush;
mMouseBrush = new EllipseBrush(this);
mBrushChanged = true;
}
else if(!dStricmp(type, "selection"))
{
delete mMouseBrush;
mMouseBrush = new SelectionBrush(this);
mBrushChanged = true;
}
else {}
}
const char* TerrainEditor::getBrushType() const
{
if ( mMouseBrush )
return mMouseBrush->getType();
return "";
}
void TerrainEditor::setBrushSize( S32 w, S32 h )
{
w = mClamp( w, 1, mMaxBrushSize.x );
h = mClamp( h, 1, mMaxBrushSize.y );
if ( w == mBrushSize.x && h == mBrushSize.y )
return;
mBrushSize.set( w, h );
mBrushChanged = true;
if ( mMouseBrush )
{
mMouseBrush->setSize( mBrushSize );
if ( mMouseBrush->getGridPoint().terrainBlock )
mMouseBrush->rebuild();
}
}
void TerrainEditor::setBrushPressure( F32 pressure )
{
pressure = mClampF( pressure, 0.01f, 1.0f );
if ( mBrushPressure == pressure )
return;
mBrushPressure = pressure;
mBrushChanged = true;
if ( mMouseBrush && mMouseBrush->getGridPoint().terrainBlock )
mMouseBrush->rebuild();
}
void TerrainEditor::setBrushSoftness( F32 softness )
{
softness = mClampF( softness, 0.01f, 1.0f );
if ( mBrushSoftness == softness )
return;
mBrushSoftness = softness;
mBrushChanged = true;
if ( mMouseBrush && mMouseBrush->getGridPoint().terrainBlock )
mMouseBrush->rebuild();
}
const char* TerrainEditor::getBrushPos()
{
AssertFatal(mMouseBrush!=NULL, "TerrainEditor::getBrushPos: no mouse brush!");
Point2I pos = mMouseBrush->getPosition();
char * ret = Con::getReturnBuffer(32);
dSprintf(ret, 32, "%d %d", pos.x, pos.y);
return(ret);
}
void TerrainEditor::setBrushPos(Point2I pos)
{
AssertFatal(mMouseBrush!=NULL, "TerrainEditor::setBrushPos: no mouse brush!");
mMouseBrush->setPosition(pos);
}
void TerrainEditor::setAction(const char* action)
{
for(U32 i = 0; i < mActions.size(); i++)
{
if(!dStricmp(mActions[i]->getName(), action))
{
mCurrentAction = mActions[i];
//
mRenderBrush = mCurrentAction->useMouseBrush();
return;
}
}
}
const char* TerrainEditor::getActionName(U32 index)
{
if(index >= mActions.size())
return("");
return(mActions[index]->getName());
}
const char* TerrainEditor::getCurrentAction() const
{
return(mCurrentAction->getName());
}
S32 TerrainEditor::getNumActions()
{
return(mActions.size());
}
void TerrainEditor::resetSelWeights(bool clear)
{
//
if(!clear)
{
for(U32 i = 0; i < mDefaultSel.size(); i++)
{
mDefaultSel[i].mPrimarySelect = false;
mDefaultSel[i].mWeight = 1.f;
}
return;
}
Selection sel;
U32 i;
for(i = 0; i < mDefaultSel.size(); i++)
{
if(mDefaultSel[i].mPrimarySelect)
{
mDefaultSel[i].mWeight = 1.f;
sel.add(mDefaultSel[i]);
}
}
mDefaultSel.reset();
for(i = 0; i < sel.size(); i++)
mDefaultSel.add(sel[i]);
}
void TerrainEditor::clearSelection()
{
mDefaultSel.reset();
}
void TerrainEditor::processAction(const char* sAction)
{
if(!checkTerrainBlock(this, "processAction"))
return;
TerrainAction * action = mCurrentAction;
if (dStrcmp(sAction, "") != 0)
{
action = lookupAction(sAction);
if(!action)
{
Con::errorf(ConsoleLogEntry::General, "TerrainEditor::cProcessAction: invalid action name '%s'.", sAction);
return;
}
}
if(!getCurrentSel()->size() && !mProcessUsesBrush)
return;
mUndoSel = new Selection;
Gui3DMouseEvent event;
if(mProcessUsesBrush)
action->process(mMouseBrush, event, true, TerrainAction::Process);
else
action->process(getCurrentSel(), event, true, TerrainAction::Process);
// check if should delete the undo
if(mUndoSel->size())
submitUndo( mUndoSel );
else
delete mUndoSel;
mUndoSel = 0;
}
S32 TerrainEditor::getNumTextures()
{
if(!checkTerrainBlock(this, "getNumTextures"))
return(0);
// walk all the possible material lists and count them..
U32 count = 0;
for (U32 t = 0; t < mTerrainBlocks.size(); t++)
count += mTerrainBlocks[t]->getMaterialCount();
return count;
}
void TerrainEditor::markEmptySquares()
{
if(!checkTerrainBlock(this, "markEmptySquares"))
return;
}
void TerrainEditor::mirrorTerrain(S32 mirrorIndex)
{
if(!checkTerrainBlock(this, "mirrorTerrain"))
return;
// TODO!
/*
TerrainBlock * terrain = mActiveTerrain;
setDirty();
//
enum {
top = BIT(0),
bottom = BIT(1),
left = BIT(2),
right = BIT(3)
};
U32 sides[8] =
{
bottom,
bottom | left,
left,
left | top,
top,
top | right,
right,
bottom | right
};
U32 n = TerrainBlock::BlockSize;
U32 side = sides[mirrorIndex % 8];
bool diag = mirrorIndex & 0x01;
Point2I src((side & right) ? (n - 1) : 0, (side & bottom) ? (n - 1) : 0);
Point2I dest((side & left) ? (n - 1) : 0, (side & top) ? (n - 1) : 0);
Point2I origSrc(src);
Point2I origDest(dest);
// determine the run length
U32 minStride = ((side & top) || (side & bottom)) ? n : n / 2;
U32 majStride = ((side & left) || (side & right)) ? n : n / 2;
Point2I srcStep((side & right) ? -1 : 1, (side & bottom) ? -1 : 1);
Point2I destStep((side & left) ? -1 : 1, (side & top) ? -1 : 1);
//
U16 * heights = terrain->getHeightAddress(0,0);
U8 * baseMaterials = terrain->getBaseMaterialAddress(0,0);
TerrainBlock::Material * materials = terrain->getMaterial(0,0);
// create an undo selection
Selection * undo = new Selection;
// walk through all the positions
for(U32 i = 0; i < majStride; i++)
{
for(U32 j = 0; j < minStride; j++)
{
// skip the same position
if(src != dest)
{
U32 si = src.x + (src.y << TerrainBlock::BlockShift);
U32 di = dest.x + (dest.y << TerrainBlock::BlockShift);
// add to undo selection
GridInfo info;
getGridInfo(dest, info, terrain);
undo->add(info);
//... copy info... (height, basematerial, material)
heights[di] = heights[si];
baseMaterials[di] = baseMaterials[si];
materials[di] = materials[si];
}
// get to the new position
src.x += srcStep.x;
diag ? (dest.y += destStep.y) : (dest.x += destStep.x);
}
// get the next position for a run
src.y += srcStep.y;
diag ? (dest.x += destStep.x) : (dest.y += destStep.y);
// reset the minor run
src.x = origSrc.x;
diag ? (dest.y = origDest.y) : (dest.x = origDest.x);
// shorten the run length for diag runs
if(diag)
minStride--;
}
// rebuild stuff..
terrain->buildGridMap();
terrain->rebuildEmptyFlags();
terrain->packEmptySquares();
// add undo selection
submitUndo( undo );
*/
}
bool TerrainEditor::isPointInTerrain( const GridPoint & gPoint)
{
PROFILE_SCOPE( TerrainEditor_IsPointInTerrain );
Point2I cPos;
gridToCenter( gPoint.gridPos, cPos );
const TerrainFile *file = gPoint.terrainBlock->getFile();
return file->isPointInTerrain( cPos.x, cPos.y );
}
void TerrainEditor::reorderMaterial( S32 index, S32 orderPos )
{
TerrainBlock *terr = getClientTerrain();
Vector<U8> layerMap = terr->getLayerMap();
Vector<TerrainMaterial*> materials = terr->getMaterials();
TerrainMaterial *pMat = materials[index];
submitMaterialUndo( String::ToString( "Reordered %s Material", terr->getMaterialName(index) ) );
materials.erase( index );
materials.insert( orderPos, pMat );
Vector<U8>::iterator itr = layerMap.begin();
for ( ; itr != layerMap.end(); itr++ )
{
// Was previous material, set to new index.
if ( *itr == index )
*itr = orderPos;
else
{
// We removed a Material prior to this one, bump it down.
if ( *itr > index )
(*itr)--;
// We added a Material prior to this one, bump it up.
if ( *itr >= orderPos )
(*itr)++;
}
}
terr->setMaterials( materials );
terr->setLayerMap( layerMap );
// We didn't really just "undo" but it happens to do everything we
// need to update the materials and gui.
onMaterialUndo( terr );
}
//------------------------------------------------------------------------------
ConsoleMethod( TerrainEditor, attachTerrain, void, 2, 3, "(TerrainBlock terrain)")
{
SimSet * missionGroup = dynamic_cast<SimSet*>(Sim::findObject("MissionGroup"));
if (!missionGroup)
{
Con::errorf(ConsoleLogEntry::Script, "TerrainEditor::attach: no mission group found");
return;
}
VectorPtr<TerrainBlock*> terrains;
// attach to first found terrainBlock
if (argc == 2)
{
for(SimSetIterator itr(missionGroup); *itr; ++itr)
{
TerrainBlock* terrBlock = dynamic_cast<TerrainBlock*>(*itr);
if (terrBlock)
terrains.push_back(terrBlock);
}
//if (terrains.size() == 0)
// Con::errorf(ConsoleLogEntry::Script, "TerrainEditor::attach: no TerrainBlock objects found!");
}
else // attach to named object
{
TerrainBlock* terrBlock = dynamic_cast<TerrainBlock*>(Sim::findObject(argv[2]));
if (terrBlock)
terrains.push_back(terrBlock);
if(terrains.size() == 0)
Con::errorf(ConsoleLogEntry::Script, "TerrainEditor::attach: failed to attach to object '%s'", argv[2]);
}
if (terrains.size() > 0)
{
for (U32 i = 0; i < terrains.size(); i++)
{
if (!terrains[i]->isServerObject())
{
terrains[i] = NULL;
Con::errorf(ConsoleLogEntry::Script, "TerrainEditor::attach: cannot attach to client TerrainBlock");
}
}
}
for (U32 i = 0; i < terrains.size(); i++)
{
if (terrains[i])
object->attachTerrain(terrains[i]);
}
}
ConsoleMethod( TerrainEditor, getTerrainBlockCount, S32, 2, 2, "()")
{
return object->getTerrainBlockCount();
}
ConsoleMethod( TerrainEditor, getTerrainBlock, S32, 3, 3, "(S32 index)")
{
TerrainBlock* tb = object->getTerrainBlock(dAtoi(argv[2]));
if(!tb)
return 0;
else
return tb->getId();
}
ConsoleMethod(TerrainEditor, getTerrainBlocksMaterialList, const char *, 2, 2, "() gets the list of current terrain materials for all terrain blocks.")
{
Vector<StringTableEntry> list;
object->getTerrainBlocksMaterialList(list);
if(list.size() == 0)
return "";
// Calculate the size of the return buffer
S32 size = 0;
for(U32 i = 0; i < list.size(); ++i)
{
size += dStrlen(list[i]);
++size;
}
++size;
// Copy the material names
char *ret = Con::getReturnBuffer(size);
ret[0] = 0;
for(U32 i = 0; i < list.size(); ++i)
{
dStrcat( ret, list[i] );
dStrcat( ret, "\n" );
}
return ret;
}
ConsoleMethod( TerrainEditor, setBrushType, void, 3, 3, "(string type)"
"One of box, ellipse, selection.")
{
object->setBrushType(argv[2]);
}
ConsoleMethod( TerrainEditor, getBrushType, const char*, 2, 2, "()")
{
return object->getBrushType();
}
ConsoleMethod( TerrainEditor, setBrushSize, void, 3, 4, "(int w [, int h])")
{
S32 w = dAtoi(argv[2]);
S32 h = argc > 3 ? dAtoi(argv[3]) : w;
object->setBrushSize( w, h );
}
ConsoleMethod( TerrainEditor, getBrushSize, const char*, 2, 2, "()")
{
Point2I size = object->getBrushSize();
char * ret = Con::getReturnBuffer(32);
dSprintf(ret, 32, "%d %d", size.x, size.y);
return ret;
}
ConsoleMethod( TerrainEditor, setBrushPressure, void, 3, 3, "(float pressure)")
{
object->setBrushPressure( dAtof( argv[2] ) );
}
ConsoleMethod( TerrainEditor, getBrushPressure, F32, 2, 2, "()")
{
return object->getBrushPressure();
}
ConsoleMethod( TerrainEditor, setBrushSoftness, void, 3, 3, "(float softness)")
{
object->setBrushSoftness( dAtof( argv[2] ) );
}
ConsoleMethod( TerrainEditor, getBrushSoftness, F32, 2, 2, "()")
{
return object->getBrushSoftness();
}
ConsoleMethod( TerrainEditor, getBrushPos, const char*, 2, 2, "Returns a Point2I.")
{
return object->getBrushPos();
}
ConsoleMethod( TerrainEditor, setBrushPos, void, 3, 4, "(int x, int y)")
{
//
Point2I pos;
if(argc == 3)
dSscanf(argv[2], "%d %d", &pos.x, &pos.y);
else
{
pos.x = dAtoi(argv[2]);
pos.y = dAtoi(argv[3]);
}
object->setBrushPos(pos);
}
ConsoleMethod( TerrainEditor, setAction, void, 3, 3, "(string action_name)")
{
object->setAction(argv[2]);
}
ConsoleMethod( TerrainEditor, getActionName, const char*, 3, 3, "(int num)")
{
return (object->getActionName(dAtoi(argv[2])));
}
ConsoleMethod( TerrainEditor, getNumActions, S32, 2, 2, "")
{
return(object->getNumActions());
}
ConsoleMethod( TerrainEditor, getCurrentAction, const char*, 2, 2, "")
{
return object->getCurrentAction();
}
ConsoleMethod( TerrainEditor, resetSelWeights, void, 3, 3, "(bool clear)")
{
object->resetSelWeights(dAtob(argv[2]));
}
ConsoleMethod( TerrainEditor, clearSelection, void, 2, 2, "")
{
object->clearSelection();
}
ConsoleMethod( TerrainEditor, processAction, void, 2, 3, "(string action=NULL)")
{
if(argc == 3)
object->processAction(argv[2]);
else object->processAction("");
}
ConsoleMethod( TerrainEditor, getActiveTerrain, S32, 2, 2, "")
{
S32 ret = 0;
TerrainBlock* terrain = object->getActiveTerrain();
if (terrain)
ret = terrain->getId();
return ret;
}
ConsoleMethod( TerrainEditor, getNumTextures, S32, 2, 2, "")
{
return object->getNumTextures();
}
ConsoleMethod( TerrainEditor, markEmptySquares, void, 2, 2, "")
{
object->markEmptySquares();
}
ConsoleMethod( TerrainEditor, mirrorTerrain, void, 3, 3, "")
{
object->mirrorTerrain(dAtoi(argv[2]));
}
ConsoleMethod(TerrainEditor, setTerraformOverlay, void, 3, 3, "(bool overlayEnable) - sets the terraformer current heightmap to draw as an overlay over the current terrain.")
{
// XA: This one needs to be implemented :)
}
ConsoleMethod(TerrainEditor, updateMaterial, bool, 4, 4,
"( int index, string matName )\n"
"Changes the material name at the index." )
{
TerrainBlock *terr = object->getClientTerrain();
if ( !terr )
return false;
U32 index = dAtoi( argv[2] );
if ( index >= terr->getMaterialCount() )
return false;
terr->updateMaterial( index, argv[3] );
object->setDirty();
return true;
}
ConsoleMethod(TerrainEditor, addMaterial, S32, 3, 3,
"( string matName )\n"
"Adds a new material." )
{
TerrainBlock *terr = object->getClientTerrain();
if ( !terr )
return false;
terr->addMaterial( argv[2] );
object->setDirty();
return true;
}
ConsoleMethod( TerrainEditor, removeMaterial, void, 3, 3, "( int index ) - Remove the material at the given index." )
{
TerrainBlock *terr = object->getClientTerrain();
if ( !terr )
return;
S32 index = dAtoi( argv[ 2 ] );
if ( index < 0 || index >= terr->getMaterialCount() )
{
Con::errorf( "TerrainEditor::removeMaterial - index out of range!" );
return;
}
if ( terr->getMaterialCount() == 1 )
{
Con::errorf( "TerrainEditor::removeMaterial - cannot remove material, there is only one!" );
return;
}
const char *matName = terr->getMaterialName( index );
object->submitMaterialUndo( String::ToString( "Remove TerrainMaterial %s", matName ) );
terr->removeMaterial( index );
object->setDirty();
object->scheduleMaterialUpdate();
object->setGridUpdateMinMax();
}
ConsoleMethod(TerrainEditor, getMaterialCount, S32, 2, 2,
"Returns the current material count." )
{
TerrainBlock *terr = object->getClientTerrain();
if ( terr )
return terr->getMaterialCount();
return 0;
}
ConsoleMethod(TerrainEditor, getMaterials, const char *, 2, 2, "() gets the list of current terrain materials.")
{
TerrainBlock *terr = object->getClientTerrain();
if ( !terr )
return "";
char *ret = Con::getReturnBuffer(4096);
ret[0] = 0;
for(U32 i = 0; i < terr->getMaterialCount(); i++)
{
dStrcat( ret, terr->getMaterialName(i) );
dStrcat( ret, "\n" );
}
return ret;
}
ConsoleMethod( TerrainEditor, getMaterialName, const char*, 3, 3, "( int index ) - Returns the name of the material at the given index." )
{
TerrainBlock *terr = object->getClientTerrain();
if ( !terr )
return "";
S32 index = dAtoi( argv[ 2 ] );
if( index < 0 || index >= terr->getMaterialCount() )
{
Con::errorf( "TerrainEditor::getMaterialName - index out of range!" );
return "";
}
const char* name = terr->getMaterialName( index );
return Con::getReturnBuffer( name );
}
ConsoleMethod( TerrainEditor, getMaterialIndex, S32, 3, 3, "( string name ) - Returns the index of the material with the given name or -1." )
{
TerrainBlock *terr = object->getClientTerrain();
if ( !terr )
return -1;
const char* name = argv[ 2 ];
const U32 count = terr->getMaterialCount();
for( U32 i = 0; i < count; ++ i )
if( dStricmp( name, terr->getMaterialName( i ) ) == 0 )
return i;
return -1;
}
ConsoleMethod( TerrainEditor, reorderMaterial, void, 4, 4, "( int index, int order ) "
"- Reorder material at the given index to the new position, changing the order in which it is rendered / blended." )
{
object->reorderMaterial( dAtoi( argv[2] ), dAtoi( argv[3] ) );
}
ConsoleMethod(TerrainEditor, getTerrainUnderWorldPoint, S32, 3, 5, "(x/y/z) Gets the terrain block that is located under the given world point.\n"
"@param x/y/z The world coordinates (floating point values) you wish to query at. "
"These can be formatted as either a string (\"x y z\") or separately as (x, y, z)\n"
"@return Returns the ID of the requested terrain block (0 if not found).\n\n")
{
TerrainEditor *tEditor = (TerrainEditor *) object;
if(tEditor == NULL)
return 0;
Point3F pos;
if(argc == 3)
dSscanf(argv[2], "%f %f %f", &pos.x, &pos.y, &pos.z);
else if(argc == 5)
{
pos.x = dAtof(argv[2]);
pos.y = dAtof(argv[3]);
pos.z = dAtof(argv[4]);
}
else
{
Con::errorf("TerrainEditor.getTerrainUnderWorldPoint(): Invalid argument count! Valid arguments are either \"x y z\" or x,y,z\n");
return 0;
}
TerrainBlock* terrain = tEditor->getTerrainUnderWorldPoint(pos);
if(terrain != NULL)
{
return terrain->getId();
}
return 0;
}
//------------------------------------------------------------------------------
void TerrainEditor::initPersistFields()
{
addGroup("Misc");
addField("isDirty", TypeBool, Offset(mIsDirty, TerrainEditor));
addField("isMissionDirty", TypeBool, Offset(mIsMissionDirty, TerrainEditor));
addField("renderBorder", TypeBool, Offset(mRenderBorder, TerrainEditor)); ///< Not currently used
addField("borderHeight", TypeF32, Offset(mBorderHeight, TerrainEditor)); ///< Not currently used
addField("borderFillColor", TypeColorI, Offset(mBorderFillColor, TerrainEditor)); ///< Not currently used
addField("borderFrameColor", TypeColorI, Offset(mBorderFrameColor, TerrainEditor)); ///< Not currently used
addField("borderLineMode", TypeBool, Offset(mBorderLineMode, TerrainEditor)); ///< Not currently used
addField("selectionHidden", TypeBool, Offset(mSelectionHidden, TerrainEditor));
addField("renderVertexSelection", TypeBool, Offset(mRenderVertexSelection, TerrainEditor)); ///< Not currently used
addField("renderSolidBrush", TypeBool, Offset(mRenderSolidBrush, TerrainEditor));
addField("processUsesBrush", TypeBool, Offset(mProcessUsesBrush, TerrainEditor));
addField("maxBrushSize", TypePoint2I, Offset(mMaxBrushSize, TerrainEditor));
// action values...
addField("adjustHeightVal", TypeF32, Offset(mAdjustHeightVal, TerrainEditor)); ///< RaiseHeightAction and LowerHeightAction
addField("setHeightVal", TypeF32, Offset(mSetHeightVal, TerrainEditor)); ///< SetHeightAction
addField("scaleVal", TypeF32, Offset(mScaleVal, TerrainEditor)); ///< ScaleHeightAction
addField("smoothFactor", TypeF32, Offset(mSmoothFactor, TerrainEditor)); ///< SmoothHeightAction
addField("noiseFactor", TypeF32, Offset(mNoiseFactor, TerrainEditor)); ///< PaintNoiseAction
addField("materialGroup", TypeS32, Offset(mMaterialGroup, TerrainEditor)); ///< Not currently used
addField("softSelectRadius", TypeF32, Offset(mSoftSelectRadius, TerrainEditor)); ///< SoftSelectAction
addField("softSelectFilter", TypeString, Offset(mSoftSelectFilter, TerrainEditor)); ///< SoftSelectAction brush filtering
addField("softSelectDefaultFilter", TypeString, Offset(mSoftSelectDefaultFilter, TerrainEditor)); ///< SoftSelectAction brush filtering
addField("adjustHeightMouseScale", TypeF32, Offset(mAdjustHeightMouseScale, TerrainEditor)); ///< Not currently used
addField("paintIndex", TypeS32, Offset(mPaintIndex, TerrainEditor)); ///< PaintMaterialAction
endGroup("Misc");
Parent::initPersistFields();
}
ConsoleMethod( TerrainEditor, getSlopeLimitMinAngle, F32, 2, 2, 0)
{
return object->mSlopeMinAngle;
}
ConsoleMethod( TerrainEditor, setSlopeLimitMinAngle, F32, 3, 3, 0)
{
F32 angle = dAtof( argv[2] );
if ( angle < 0.0f )
angle = 0.0f;
if ( angle > object->mSlopeMaxAngle )
angle = object->mSlopeMaxAngle;
object->mSlopeMinAngle = angle;
return angle;
}
ConsoleMethod( TerrainEditor, getSlopeLimitMaxAngle, F32, 2, 2, 0)
{
return object->mSlopeMaxAngle;
}
ConsoleMethod( TerrainEditor, setSlopeLimitMaxAngle, F32, 3, 3, 0)
{
F32 angle = dAtof( argv[2] );
if ( angle > 90.0f )
angle = 90.0f;
if ( angle < object->mSlopeMinAngle )
angle = object->mSlopeMinAngle;
object->mSlopeMaxAngle = angle;
return angle;
}
//------------------------------------------------------------------------------
void TerrainEditor::autoMaterialLayer( F32 mMinHeight, F32 mMaxHeight, F32 mMinSlope, F32 mMaxSlope )
{
if (!mActiveTerrain)
return;
S32 mat = getPaintMaterialIndex();
if (mat == -1)
return;
mUndoSel = new Selection;
U32 terrBlocks = mActiveTerrain->getBlockSize();
for (U32 y = 0; y < terrBlocks; y++)
{
for (U32 x = 0; x < terrBlocks; x++)
{
// get info
GridPoint gp;
gp.terrainBlock = mActiveTerrain;
gp.gridPos.set(x, y);
GridInfo gi;
getGridInfo(gp, gi);
if (gi.mMaterial == mat)
continue;
Point3F wp;
gridToWorld(gp, wp);
if (!(wp.z >= mMinHeight && wp.z <= mMaxHeight))
continue;
// transform wp to object space
Point3F op;
mActiveTerrain->getWorldTransform().mulP(wp, &op);
Point3F norm;
mActiveTerrain->getNormal(Point2F(op.x, op.y), &norm, true);
if (mMinSlope > 0)
if (norm.z > mSin(mDegToRad(90.0f - mMinSlope)))
continue;
if (mMaxSlope < 90)
if (norm.z < mSin(mDegToRad(90.0f - mMaxSlope)))
continue;
gi.mMaterialChanged = true;
mUndoSel->add(gi);
gi.mMaterial = mat;
setGridInfo(gi);
}
}
if(mUndoSel->size())
submitUndo( mUndoSel );
else
delete mUndoSel;
mUndoSel = 0;
scheduleMaterialUpdate();
}
ConsoleMethod( TerrainEditor, autoMaterialLayer, void, 6, 6, "(float minHeight, float maxHeight, float minSlope, float maxSlope)")
{
object->autoMaterialLayer( dAtof(argv[2]), dAtof(argv[3]), dAtof(argv[4]), dAtof(argv[5]) );
}
|
#include "stdwx.h"
#include "FijiInterfacePlugin.h"
#include "FijiInterfacePluginWindow.h"
#include "VRenderFrame.h"
#include "wx/process.h"
#include "wx/mstream.h"
#include "compatibility.h"
IMPLEMENT_DYNAMIC_CLASS(SampleGuiPlugin1, wxObject)
FijiServer::~FijiServer(void)
{
}
void FijiServer::DeleteConnection()
{
if (m_connection)
{
if (m_connection->GetConnected()) m_connection->Disconnect();
delete m_connection;
m_connection = NULL;
}
}
wxConnectionBase* FijiServer::OnAcceptConnection(const wxString &topic)
{
if (topic == _("FijiVVDPlugin"))
{
m_connection = new FijiServerConnection;
m_connection->SetFrame(m_vframe);
notifyAll(FI_CONNECT);
return m_connection;
}
else
return NULL;
}
void FijiServerConnection::SetTimeout(long seconds)
{
if (m_sock)
m_sock->SetTimeout(seconds);
}
long FijiServerConnection::GetTimeout()
{
if (m_sock)
return m_sock->GetTimeout();
else
return -1L;
}
void FijiServerConnection::SetSndBufSize(size_t size)
{
if (m_sock)
m_sock->SetOption(SOL_SOCKET, SO_SNDBUF, &size, sizeof(size));
}
bool FijiServerConnection::OnAdvise(const wxString& topic, const wxString& item, char *data,
int size, wxIPCFormat format)
{
wxMessageBox(topic, data);
return true;
}
bool FijiServerConnection::OnStartAdvise(const wxString& topic, const wxString& item)
{
wxMessageBox(wxString::Format("OnStartAdvise(\"%s\",\"%s\")", topic.c_str(), item.c_str()));
return true;
}
bool FijiServerConnection::OnStopAdvise(const wxString& topic, const wxString& item)
{
wxMessageBox(wxString::Format("OnStopAdvise(\"%s\",\"%s\")", topic.c_str(), item.c_str()));
return true;
}
bool FijiServerConnection::OnPoke(const wxString& topic, const wxString& item, const void *data, size_t size, wxIPCFormat format)
{
char ret[1] = {10};
switch (format)
{
case wxIPC_TEXT:
//wxMessageBox(wxString::Format("OnPoke(\"%s\",\"%s\",\"%s\")", topic.c_str(), item.c_str(), (const char*)data));
if (item == "version")
{
notifyAll(FI_VERSION_CHECK, data, size);
int newbuffersize = 300*1024*1024;
m_sock->SetOption(SOL_SOCKET, SO_RCVBUF, &newbuffersize, sizeof(newbuffersize));
m_sock->SetOption(SOL_SOCKET, SO_SNDBUF, &newbuffersize, sizeof(newbuffersize));
m_sock->SetFlags(wxSOCKET_BLOCK|wxSOCKET_WAITALL);
//m_sock->Write(ret, 1);
}
if (item == "confirm")
{
Poke(item, data, size, wxIPC_TEXT);
notifyAll(FI_CONFIRM, data, size);
}
if (item == "pid")
{
notifyAll(FI_PID, data, size);
}
if (item == "com_finish")
notifyAll(FI_COMMAND_FINISHED, data, size);
break;
case wxIPC_PRIVATE:
if (item == "settimeout" && size == 4)
{
int sec = *((const int32_t *)data);
if (sec > 0)
SetTimeout(sec);
}
if (item == "setrcvbufsize")
{
int newbuffersize = *((const int32_t *)data);
if (newbuffersize > 0)
{
m_sock->SetOption(SOL_SOCKET, SO_RCVBUF, &newbuffersize, sizeof(newbuffersize));
wxMilliSleep(300);
}
}
if (item == "setsndbufsize")
{
int newbuffersize = *((const int32_t *)data);
if (newbuffersize > 0)
{
m_sock->SetOption(SOL_SOCKET, SO_SNDBUF, &newbuffersize, sizeof(newbuffersize));
wxMilliSleep(300);
}
}
if (item == "volume")
{
notifyAll(FI_VOLUMEDATA, data, size);
// Poke("volume_received", "recv", 4, wxIPC_TEXT);
}
}
return true;
}
bool FijiServerConnection::OnExec(const wxString &topic, const wxString &data)
{
return true;
}
SampleGuiPlugin1::SampleGuiPlugin1()
: wxGuiPluginBase(NULL, NULL), m_server(NULL), m_initialized(false), m_booting(false), m_fijiprocess(NULL), m_sendmask(false), m_launch_fiji_startup(false), m_tmp_ovvox(TMP_OVOX_NONE)
{
}
SampleGuiPlugin1::SampleGuiPlugin1(wxEvtHandler * handler, wxWindow * vvd)
: wxGuiPluginBase(handler, vvd), m_server(NULL), m_initialized(false), m_booting(false), m_fijiprocess(NULL), m_sendmask(false), m_launch_fiji_startup(false), m_tmp_ovvox(TMP_OVOX_NONE)
{
}
SampleGuiPlugin1::~SampleGuiPlugin1()
{
wxDELETE(m_server);
}
void SampleGuiPlugin1::doAction(ActionInfo *info)
{
if (!info)
return;
int evid = info->id;
switch (evid)
{
case FI_CONNECT:
if (m_server && m_server->GetConnection())
m_server->GetConnection()->addObserver(this);
m_booting = false;
break;
case FI_VERSION_CHECK:
//wxMessageBox(wxString::Format("VVD plugin ver. %s Fiji plugin ver. %s", FI_PLUGIN_VERSION, wxString((char *)info->data)));
m_fiji_plugin_ver = wxString((char *)info->data);
if (wxString((char *)info->data) != FI_PLUGIN_VERSION)
{
//do something
}
notifyAll(FI_VERSION_CHECK, info->data, info->size);
break;
case FI_PID:
//m_pid = wxString((char *)info->data);
notifyAll(FI_PID, info->data, info->size);
break;
case FI_CONFIRM:
m_initialized = true;
m_timer.Stop();
m_watch.Pause();
break;
case FI_VOLUMEDATA:
if (m_vvd)
{
int idx = 0;
const char *ptr = (const char *)info->data;
size_t chk = info->size;
VRenderFrame *vframe = (VRenderFrame *)m_vvd;
int name_len = *((const int32_t *)ptr);
ptr += 4;
chk -= 4;
char *name = new char[name_len];
memcpy(name, ptr, name_len);
ptr += name_len;
chk -= name_len;
int nx = *((const int32_t *)ptr);
ptr += 4;
chk -= 4;
int ny = *((const int32_t *)ptr);
ptr += 4;
chk -= 4;
int nz = *((const int32_t *)ptr);
ptr += 4;
chk -= 4;
int bd = *((const int32_t *)ptr);
ptr += 4;
chk -= 4;
int r = *((const int32_t *)ptr);
ptr += 4;
chk -= 4;
int g = *((const int32_t *)ptr);
ptr += 4;
chk -= 4;
int b = *((const int32_t *)ptr);
ptr += 4;
chk -= 4;
double spcx = *((const double *)ptr);
ptr += 8;
chk -= 8;
double spcy = *((const double *)ptr);
ptr += 8;
chk -= 8;
double spcz = *((const double *)ptr);
ptr += 8;
chk -= 8;
if (chk == nx*ny*nz*(bd/8))
{
bool set_as_mask = false;
DataManager *dm = vframe->GetDataManager();
if (dm && !m_sent_mask.IsEmpty() && m_sent_mask == name && bd == 8)
{
VolumeData *src = dm->GetVolumeData(name);
if (src)
{
int resx, resy, resz;
src->GetResolution(resx, resy, resz);
if (resx == nx && resy == ny && resz == nz)
set_as_mask = true;
}
m_sent_mask = "";
}
if (set_as_mask)
{
VolumeData *vd = VolumeData::DeepCopy(*dm->GetVolumeData(name), false, dm);
if (!vd->GetMask(false)) vd->AddEmptyMask();
auto vlnrrd = vd->GetMask(false);
memcpy(vlnrrd->getNrrd()->data, ptr, nx*ny*nz*(bd/8));
vframe->AddVolume(vd, NULL);
}
else
{
VolumeData *vd = new VolumeData();
vd->AddEmptyData(bd, nx, ny, nz, spcx, spcy, spcz);
FLIVR::Color col((double)r/255.0, (double)g/255.0, (double)b/255.0);
vd->SetName(wxString(name));
vd->SetColor(col);
vd->SetBaseSpacings(spcx, spcy, spcz);
vd->SetSpcFromFile(true);
if (dm) dm->SetVolumeDefault(vd);
auto vlnrrd = vd->GetVolume(false);
memcpy(vlnrrd->getNrrd()->data, ptr, nx*ny*nz*(bd/8));
if (bd == 16)
{
const char *p = ptr;
int maxval = 0;
for (int i = 0; i < chk; i+=2)
{
int ival = *((unsigned short *)p);
if (maxval < ival)
maxval = ival;
p += 2;
}
vd->SetMaxValue((double)maxval);
}
vframe->AddVolume(vd, NULL);
}
}
delete [] name;
}
break;
case FI_COMMAND_FINISHED:
{
VRenderFrame *vframe = (VRenderFrame *)m_vvd;
DataManager *dm = vframe ? vframe->GetDataManager() : NULL;
if (dm && vframe->GetView(0))
{
dm->SetOverrideVox(m_ovvox);
DataGroup* group = vframe->GetView(0)->GetCurrentVolGroup();
if (group)
{
group->SetVolumeSyncSpc(m_gpsyncspc);
group->SetVolumeSyncProp(m_gpsync);
}
}
m_tmp_ovvox = TMP_OVOX_NONE;
}
notifyAll(FI_COMMAND_FINISHED, info->data, info->size);
break;
}
delete info;
}
bool SampleGuiPlugin1::SendCommand(wxString command, bool send_mask)
{
if (!m_server || !m_server->GetConnection())
return false;
SendCurrentVolume(send_mask);
VRenderFrame *vframe = (VRenderFrame *)m_vvd;
DataManager *dm = vframe ? vframe->GetDataManager() : NULL;
if (dm && vframe->GetView(0))
{
m_ovvox = dm->GetOverrideVox();
DataGroup* group = vframe->GetView(0)->GetCurrentVolGroup();
if (group)
{
m_gpsync = group->GetVolumeSyncProp();
m_gpsyncspc = group->GetVolumeSyncSpc();
if (m_tmp_ovvox == TMP_OVOX_TRUE)
{
dm->SetOverrideVox(true);
group->SetVolumeSyncSpc(true);
}
else if (m_tmp_ovvox == TMP_OVOX_FALSE)
{
dm->SetOverrideVox(false);
group->SetVolumeSyncSpc(false);
group->SetVolumeSyncProp(false);
}
}
}
return m_server->GetConnection()->Poke(_("com"), command);
}
bool SampleGuiPlugin1::SendCurrentVolume(bool send_mask)
{
VRenderFrame *vframe = (VRenderFrame *)m_vvd;
if (!vframe || !m_server || !m_server->GetConnection() || !m_server->GetConnection()) return false;
VolumeData *vd = vframe->GetCurSelVol();
if (!vd) return false;
shared_ptr<VL_Nrrd> vol;
if (send_mask)
{
vol = vd->GetMask(true);
if (!vol)
vol = vd->GetVolume(true);
}
else
vol = vd->GetVolume(true);
if (!vol || !vol->getNrrd() || !vol->getNrrd()->data) return false;
const wxString name = vd->GetName();
size_t basesize = 4+name.Len()+4+4+4+4+4+4+4+8+8+8;
int resx, resy, resz;
vd->GetResolution(resx, resy, resz);
double spcx, spcy, spcz;
vd->GetSpacings(spcx, spcy, spcz);
int bd;
if (vol->getNrrd()->type == nrrdTypeChar || vol->getNrrd()->type == nrrdTypeUChar)
bd = 8;
else
bd = 16;
size_t imagesize = (size_t)resx*(size_t)resy*(size_t)resz*(size_t)(bd/8);
char *buf = new char[basesize+imagesize];
FLIVR::Color col = vd->GetColor();
int32_t tmp32;
wxMemoryOutputStream mos(buf, basesize+imagesize);
tmp32 = (int32_t)name.Len();
mos.Write(&tmp32, sizeof(int32_t));
mos.Write(name.ToStdString().c_str(), tmp32);
tmp32 = (int32_t)resx;
mos.Write(&tmp32, sizeof(int32_t));
tmp32 = (int32_t)resy;
mos.Write(&tmp32, sizeof(int32_t));
tmp32 = (int32_t)resz;
mos.Write(&tmp32, sizeof(int32_t));
tmp32 = (int32_t)bd;
mos.Write(&tmp32, sizeof(int32_t));
tmp32 = (int32_t)(col.r()*255);
mos.Write(&tmp32, sizeof(int32_t));
tmp32 = (int32_t)(col.g()*255);
mos.Write(&tmp32, sizeof(int32_t));
tmp32 = (int32_t)(col.b()*255);
mos.Write(&tmp32, sizeof(int32_t));
mos.Write(&spcx, sizeof(double));
mos.Write(&spcy, sizeof(double));
mos.Write(&spcz, sizeof(double));
mos.Write(vol->getNrrd()->data, imagesize);
tmp32 = basesize+imagesize;
if (tmp32 > 0)
{
m_server->GetConnection()->SetSndBufSize(basesize+imagesize);
m_server->GetConnection()->Poke("setrcvbufsize", &tmp32, sizeof(int32_t), wxIPC_PRIVATE);
wxMilliSleep(500);
m_server->GetConnection()->Poke("volume", buf, tmp32, wxIPC_PRIVATE);
if (send_mask) m_sent_mask = name;
}
delete[] buf;
return true;
}
wxString SampleGuiPlugin1::GetName() const
{
return _("Fiji Interface");
}
wxString SampleGuiPlugin1::GetDisplayName() const
{
return _("Fiji Interface");
}
wxString SampleGuiPlugin1::GetId() const
{
return wxT("{4E97DF66-5FBB-4719-AF17-76C1C82D3FE1}");
}
wxWindow * SampleGuiPlugin1::CreatePanel(wxWindow * parent)
{
return new SampleGuiPluginWindow1(this, parent);
}
bool SampleGuiPlugin1::StartFiji()
{
if (m_initialized || m_booting)
return true;
wxString fjpath = m_fiji_path;
#ifdef _DARWIN
fjpath += _("/Contents/MacOS/ImageJ-macosx");
#endif
if (fjpath.IsEmpty() || !wxFileExists(fjpath))
{
wxMessageBox("Error: Could not found Fiji", "Fiji Interface");
VRenderFrame *vframe = (VRenderFrame *)m_vvd;
if (vframe)
{
if (!vframe->IsCreatedPluginWindow(GetName()))
vframe->CreatePluginWindow(GetName());
vframe->ToggleVisibilityPluginWindow(GetName(), true);
}
return false;
}
wxString expath = wxStandardPaths::Get().GetExecutablePath();
expath = expath.BeforeLast(wxFILE_SEP_PATH, NULL);
#ifdef _WIN32
wxString rootdir = m_fiji_path.BeforeLast(wxFILE_SEP_PATH, NULL);
wxString rdir = expath + wxFILE_SEP_PATH;
#else
wxString rootdir = m_fiji_path;
wxString rdir = expath + _("/../Resources") + wxFILE_SEP_PATH;
#endif
wxString macrodir = rootdir + wxFILE_SEP_PATH + _("macros") + wxFILE_SEP_PATH;
wxString plugindir = rootdir + wxFILE_SEP_PATH + _("plugins") + wxFILE_SEP_PATH;
if (wxDirExists(macrodir) && wxFileExists(rdir+"vvd_listener.txt"))
wxCopyFile(rdir+"vvd_listener.txt", macrodir+"vvd_listener.txt");
if (wxDirExists(macrodir) && wxFileExists(rdir+"vvd_run.txt"))
wxCopyFile(rdir+"vvd_run.txt", macrodir+"vvd_run.txt");
if (wxDirExists(macrodir) && wxFileExists(rdir+"vvd_quit.txt"))
wxCopyFile(rdir+"vvd_quit.txt", macrodir+"vvd_quit.txt");
if (wxDirExists(plugindir) && wxFileExists(rdir+"vvd_listener.jar"))
wxCopyFile(rdir+"vvd_listener.jar", plugindir+"vvd_listener.jar");
if (wxDirExists(plugindir) && wxFileExists(rdir+"NBLAST_Skeletonize.jar"))
wxCopyFile(rdir+"NBLAST_Skeletonize.jar", plugindir+"NBLAST_Skeletonize.jar");
m_initialized = false;
#ifdef _WIN32
wxString command = fjpath + " -macro vvd_listener.txt";
#else
wxString hcom = "defaults write " + m_fiji_path + "/Contents/Info LSUIElement 1";
wxExecute(hcom, wxEXEC_HIDE_CONSOLE|wxEXEC_SYNC);
wxString command = fjpath + " -macro vvd_listener.txt";
#endif
m_booting = true;
m_fijiprocess = new wxProcess();
wxExecute(command, wxEXEC_HIDE_CONSOLE|wxEXEC_ASYNC, m_fijiprocess);
if (m_fijiprocess) m_pid = wxString::Format("%ld", m_fijiprocess->GetPid());
return true;
}
void SampleGuiPlugin1::CloseFiji()
{
if (m_fiji_path.IsEmpty())
return;
if (m_fijiprocess) m_fijiprocess->Detach();
#ifdef _WIN32
//wxString command = m_fiji_path + " -port3 -macro vvd_quit.ijm";
//wxExecute(command);
if (!m_pid.IsEmpty()) wxExecute("taskkill /pid "+m_pid+" /f", wxEXEC_HIDE_CONSOLE|wxEXEC_SYNC);
#else
if (!m_pid.IsEmpty())
{
wxString hcom = "defaults write " + m_fiji_path + "/Contents/Info LSUIElement 0";
if (!m_fiji_path.IsEmpty())
wxExecute(hcom, wxEXEC_HIDE_CONSOLE|wxEXEC_SYNC);
wxExecute("kill "+m_pid, wxEXEC_HIDE_CONSOLE|wxEXEC_SYNC);
}
#endif
wxString expath = wxStandardPaths::Get().GetExecutablePath();
expath = expath.BeforeLast(wxFILE_SEP_PATH, NULL);
#ifdef _WIN32
wxString rootdir = m_fiji_path.BeforeLast(wxFILE_SEP_PATH, NULL);
wxString rdir = expath + wxFILE_SEP_PATH;
#else
wxString rootdir = m_fiji_path;
wxString rdir = expath + _("/../Resources") + wxFILE_SEP_PATH;
#endif
wxString macrodir = rootdir + wxFILE_SEP_PATH + _("macros") + wxFILE_SEP_PATH;
wxString plugindir = rootdir + wxFILE_SEP_PATH + _("plugins") + wxFILE_SEP_PATH;
if (wxFileExists(macrodir+"vvd_listener.txt"))
wxRemoveFile(macrodir+"vvd_listener.txt");
if (wxFileExists(macrodir+"vvd_run.txt"))
wxRemoveFile(macrodir+"vvd_run.txt");
if (wxFileExists(macrodir+"vvd_quit.txt"))
wxRemoveFile(macrodir+"vvd_quit.txt");
// if (wxFileExists(plugindir+"vvd_listener.jar"))
// wxRemoveFile(plugindir+"vvd_listener.jar");
// if (wxFileExists(plugindir+"NBLAST_Skeletonize.jar"))
// wxRemoveFile(plugindir+"NBLAST_Skeletonize.jar");
m_initialized = false;
m_booting = false;
}
bool SampleGuiPlugin1::isReady()
{
if (!m_server || !m_server->GetConnection() || !m_server->GetConnection()->GetConnected())
return false;
return m_initialized;
}
void SampleGuiPlugin1::OnInit()
{
LoadConfigFile();
m_server = new FijiServer;
m_server->Create("8002");
m_server->addObserver(this);
if (m_launch_fiji_startup)
StartFiji();
}
void SampleGuiPlugin1::OnDestroy()
{
CloseFiji();
}
bool SampleGuiPlugin1::OnRun(wxString options)
{
notifyAll(FI_RUN, options.ToStdString().c_str(), options.Len()+1);
return true;
}
void SampleGuiPlugin1::OnTimer(wxTimerEvent& event)
{
if (m_watch.Time() >= 15000)
{
CloseFiji();
m_timer.Stop();
m_watch.Pause();
}
}
void SampleGuiPlugin1::LoadConfigFile()
{
wxString expath = wxStandardPaths::Get().GetExecutablePath();
expath = expath.BeforeLast(GETSLASH(), NULL);
#ifdef _WIN32
wxString dft = expath + "\\fiji_interface_settings.dft";
if (!wxFileExists(dft))
dft = wxStandardPaths::Get().GetUserConfigDir() + "\\fiji_interface_settings.dft";
#else
wxString dft = expath + "/../Resources/fiji_interface_settings.dft";
#endif
if (wxFileExists(dft))
{
wxFileInputStream is(dft);
if (is.IsOk())
{
wxFileConfig fconfig(is);
wxString str;
bool bVal;
if (fconfig.Read("fiji_path", &str))
m_fiji_path = str;
if (fconfig.Read("launch_fiji", &bVal))
m_launch_fiji_startup = bVal;
if (fconfig.Read("send_mask", &bVal))
m_sendmask = bVal;
}
}
}
void SampleGuiPlugin1::SaveConfigFile()
{
wxFileConfig fconfig("Fiji interface default settings");
fconfig.Write("fiji_path", m_fiji_path);
fconfig.Write("launch_fiji", m_launch_fiji_startup);
fconfig.Write("send_mask", m_sendmask);
wxString expath = wxStandardPaths::Get().GetExecutablePath();
expath = expath.BeforeLast(GETSLASH(),NULL);
#ifdef _WIN32
wxString dft = expath + "\\fiji_interface_settings.dft";
wxString dft2 = wxStandardPaths::Get().GetUserConfigDir() + "\\fiji_interface_settings.dft";
if (!wxFileExists(dft) && wxFileExists(dft2))
dft = dft2;
#else
wxString dft = expath + "/../Resources/fiji_interface_settings.dft";
#endif
wxFileOutputStream os(dft);
fconfig.Save(os);
}
|
/******************************************************************************
* $Id: ogrelasticdatasource.cpp 23848 2012-01-31 20:49:42Z rouault $
*
* Project: ElasticSearch Translator
* Purpose:
* Author:
*
******************************************************************************
* Copyright (c) 2011, Adam Estrada
*
* 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 warning( disable : 4251 )
#include "ogr_elastic.h"
#include "cpl_conv.h"
#include "cpl_string.h"
#include "cpl_csv.h"
#include "cpl_http.h"
CPL_CVSID("$Id: ogrelasticdatasource.cpp 23848 2012-01-31 20:49:42Z rouault $");
/************************************************************************/
/* OGRElasticDataSource() */
/************************************************************************/
OGRElasticDataSource::OGRElasticDataSource() {
papoLayers = NULL;
nLayers = 0;
pszName = NULL;
pszMapping = NULL;
pszWriteMap = NULL;
}
/************************************************************************/
/* ~OGRElasticDataSource() */
/************************************************************************/
OGRElasticDataSource::~OGRElasticDataSource() {
for (int i = 0; i < nLayers; i++)
delete papoLayers[i];
CPLFree(papoLayers);
CPLFree(pszName);
CPLFree(pszMapping);
CPLFree(pszWriteMap);
}
/************************************************************************/
/* TestCapability() */
/************************************************************************/
int OGRElasticDataSource::TestCapability(const char * pszCap) {
if (EQUAL(pszCap, ODsCCreateLayer))
return TRUE;
else
return FALSE;
}
/************************************************************************/
/* GetLayer() */
/************************************************************************/
OGRLayer *OGRElasticDataSource::GetLayer(int iLayer) {
if (iLayer < 0 || iLayer >= nLayers)
return NULL;
else
return papoLayers[iLayer];
}
/************************************************************************/
/* CreateLayer() */
/************************************************************************/
OGRLayer * OGRElasticDataSource::CreateLayer(const char * pszLayerName,
OGRSpatialReference *poSRS,
OGRwkbGeometryType eType,
char ** papszOptions) {
nLayers++;
papoLayers = (OGRElasticLayer **) CPLRealloc(papoLayers, nLayers * sizeof (OGRElasticLayer*));
papoLayers[nLayers - 1] = new OGRElasticLayer(pszName, pszLayerName, this, poSRS, TRUE);
return papoLayers[nLayers - 1];
}
/************************************************************************/
/* Open() */
/************************************************************************/
int OGRElasticDataSource::Open(const char * pszFilename, int bUpdateIn) {
CPLError(CE_Failure, CPLE_NotSupported,
"OGR/Elastic driver does not support opening a file");
return FALSE;
}
/************************************************************************/
/* DeleteIndex() */
/************************************************************************/
void OGRElasticDataSource::DeleteIndex(const CPLString &url) {
char** papszOptions = NULL;
papszOptions = CSLAddNameValue(papszOptions, "CUSTOMREQUEST", "DELETE");
CPLHTTPResult* psResult = CPLHTTPFetch(url, papszOptions);
CSLDestroy(papszOptions);
if (psResult) {
CPLHTTPDestroyResult(psResult);
}
}
/************************************************************************/
/* UploadFile() */
/************************************************************************/
void OGRElasticDataSource::UploadFile(const CPLString &url, const CPLString &data) {
char** papszOptions = NULL;
papszOptions = CSLAddNameValue(papszOptions, "POSTFIELDS", data.c_str());
papszOptions = CSLAddNameValue(papszOptions, "HEADERS",
"Content-Type: application/x-javascript; charset=UTF-8");
CPLHTTPResult* psResult = CPLHTTPFetch(url, papszOptions);
CSLDestroy(papszOptions);
if (psResult) {
CPLHTTPDestroyResult(psResult);
}
}
/************************************************************************/
/* Create() */
/************************************************************************/
int OGRElasticDataSource::Create(const char *pszFilename,
char **papszOptions) {
this->pszName = CPLStrdup(pszFilename);
const char* pszMetaFile = CPLGetConfigOption("ES_META", NULL);
const char* pszWriteMap = CPLGetConfigOption("ES_WRITEMAP", NULL);;
this->bOverwrite = CSLTestBoolean(CPLGetConfigOption("ES_OVERWRITE", "0"));
this->nBulkUpload = (int) CPLAtof(CPLGetConfigOption("ES_BULK", "0"));
if (pszWriteMap != NULL) {
this->pszWriteMap = CPLStrdup(pszWriteMap);
}
// Read in the meta file from disk
if (pszMetaFile != NULL)
{
int fsize;
char *fdata;
FILE *fp;
fp = fopen(pszMetaFile, "rb");
if (fp != NULL) {
fseek(fp, 0, SEEK_END);
fsize = (int) ftell(fp);
fdata = (char *) malloc(fsize + 1);
fseek(fp, 0, SEEK_SET);
fread(fdata, fsize, 1, fp);
fdata[fsize] = 0;
this->pszMapping = fdata;
fclose(fp);
}
}
// Do a status check to ensure that the server is valid
CPLHTTPResult* psResult = CPLHTTPFetch(CPLSPrintf("%s/_status", pszFilename), NULL);
int bOK = (psResult != NULL && psResult->pszErrBuf == NULL);
if (!bOK)
{
CPLError(CE_Failure, CPLE_NoWriteAccess,
"Could not connect to server");
}
CPLHTTPDestroyResult(psResult);
return bOK;
}
|
// Copyright 2021 Pudovkin Artem
#include <mpi.h>
#include <cstring>
#include "../../..//modules/task_2/pudovkin_a_allreduce/allreduce.h"
int Allreduce(void* sendbuf, void* recvbuf, int count, MPI_Datatype datatype, MPI_Op op, MPI_Comm comm) {
if (recvbuf == nullptr)
return MPI_ERR_BUFFER;
if (count <= 0)
return MPI_ERR_COUNT;
if ((datatype != MPI_INT) && (datatype != MPI_FLOAT) && (datatype != MPI_DOUBLE))
return MPI_ERR_TYPE;
if ((op != MPI_MAX) && (op != MPI_MIN) && (op != MPI_SUM))
return MPI_ERR_OP;
int rank, size;
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
int* bufferInt;
float* bufferFloat;
double* bufferDouble;
if (rank != 0) {
MPI_Send(sendbuf, count, datatype, 0, 0, comm);
}
if (rank == 0) {
if (datatype == MPI_INT) memcpy(recvbuf, sendbuf, count * sizeof(int));
else if (datatype == MPI_FLOAT) memcpy(recvbuf, sendbuf, count * sizeof(float));
else if (datatype == MPI_DOUBLE) memcpy(recvbuf, sendbuf, count * sizeof(double));
if (datatype == MPI_INT) {
bufferInt = new int[count];
} else if (datatype == MPI_FLOAT) {
bufferFloat = new float[count];
} else if (datatype == MPI_DOUBLE) {
bufferDouble = new double[count];
}
for (int proc = 1; proc < size; proc++) {
MPI_Status status;
if (datatype == MPI_INT)
MPI_Recv(bufferInt, count, datatype, proc, 0, comm, &status);
if (datatype == MPI_FLOAT)
MPI_Recv(bufferFloat, count, datatype, proc, 0, comm, &status);
if (datatype == MPI_DOUBLE)
MPI_Recv(bufferDouble, count, datatype, proc, 0, comm, &status);
if (op == MPI_MAX) {
for (int i = 0; i < count; i++) {
if (datatype == MPI_INT)
static_cast<int*>(recvbuf)[i] = std::max(static_cast<int*>(recvbuf)[i], bufferInt[i]);
if (datatype == MPI_FLOAT)
static_cast<float*>(recvbuf)[i] = std::max(static_cast<float*>(recvbuf)[i], bufferFloat[i]);
if (datatype == MPI_DOUBLE)
static_cast<double*>(recvbuf)[i] = std::max(static_cast<double*>(recvbuf)[i], bufferDouble[i]);
}
}
if (op == MPI_MIN) {
for (int i = 0; i < count; i++) {
if (datatype == MPI_INT)
static_cast<int*>(recvbuf)[i] = std::min(static_cast<int*>(recvbuf)[i], bufferInt[i]);
if (datatype == MPI_FLOAT)
static_cast<float*>(recvbuf)[i] = std::min(static_cast<float*>(recvbuf)[i], bufferFloat[i]);
if (datatype == MPI_DOUBLE)
static_cast<double*>(recvbuf)[i] = std::min(static_cast<double*>(recvbuf)[i], bufferDouble[i]);
}
}
if (op == MPI_SUM) {
for (int i = 0; i < count; i++) {
if (datatype == MPI_INT) static_cast<int*>(recvbuf)[i] += bufferInt[i];
if (datatype == MPI_FLOAT) static_cast<float*>(recvbuf)[i] += bufferFloat[i];
if (datatype == MPI_DOUBLE) static_cast<double*>(recvbuf)[i] += bufferDouble[i];
}
}
}
for (int proc = 1; proc < size; proc++) {
MPI_Send(recvbuf, count, datatype, proc, 0, comm);
}
}
if (rank != 0) {
MPI_Status status;
MPI_Recv(recvbuf, count, datatype, 0, 0, comm, &status);
}
return MPI_SUCCESS;
}
|
// Copyright 2020 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// 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 tree_node_size_impl.hpp
*
*/
#ifndef SRC_CPP_UTILS_COLLECTIONS_IMPL_STD_TREE_NODE_SIZE_IMPL_HPP_
#define SRC_CPP_UTILS_COLLECTIONS_IMPL_STD_TREE_NODE_SIZE_IMPL_HPP_
#ifdef STD_TREE_NODE_TYPE
template <typename T>
struct tree_node_size : std::integral_constant <size_t, sizeof(STD_TREE_NODE_TYPE <T, void*>)>
{
};
#else
#error "STD_TREE_NODE_TYPE should be defined along with USE_STD_NODE_SIZES"
#endif // STD_TREE_NODE_TYPE
#endif /* SRC_CPP_UTILS_COLLECTIONS_IMPL_STD_TREE_NODE_SIZE_IMPL_HPP_ */
|
/**
* 1.8 Zero Matrix: Write an algorithm such that if an element in an MxN matrix is 0, its entire row and
* column are set to 0
*/
#include <assert.h>
#include <stdint.h>
#include <stddef.h>
#include <string.h>
#include <vector>
#include <iostream>
struct matrix2d {
size_t nrows;
size_t ncols;
uint32_t* data;
};
static uint32_t get(const struct matrix2d* m, size_t r, size_t c)
{
assert(m);
assert(r < m->nrows);
assert(c < m->ncols);
return m->data[r * m->ncols + c];
}
static void set(struct matrix2d* m, size_t r, size_t c, uint32_t v)
{
assert(m);
assert(r < m->nrows);
assert(c < m->ncols);
m->data[r * m->ncols + c] = v;
}
static void dump(const struct matrix2d* m)
{
assert(m);
for (size_t r = 0; r < m->nrows; ++r) {
for (size_t c = 0; c < m->ncols; ++c) {
std::cout << get(m, r, c) << " ";
}
std::cout << std::endl;
}
}
static void zero_row(struct matrix2d* m, size_t r)
{
assert(m);
assert(r < m->nrows);
memset(m->data + r * m->ncols, 0, sizeof(*m->data) * m->ncols);
}
static void zero_col(struct matrix2d* m, size_t c)
{
assert(m);
assert(c < m->ncols);
for (size_t r = 0; r < m->nrows; ++r) {
set(m, r, c, 0);
}
}
void zero_matrix(struct matrix2d* m)
{
if (!m)
return;
std::vector<size_t> zero_rows;
std::vector<size_t> zero_cols;
for (size_t r = 0; r < m->nrows; ++r) {
for (size_t c = 0; c < m->ncols; ++c) {
if (0 == get(m, r, c)) {
zero_rows.push_back(r);
zero_cols.push_back(c);
}
}
}
for (size_t r : zero_rows)
zero_row(m, r);
for (size_t c : zero_cols)
zero_col(m, c);
}
int main()
{
uint32_t data[] = {
1, 2, 3, 4,
9, 0, 8, 0,
5, 6, 7, 0,
};
struct matrix2d m = {
.nrows = 3,
.data = data,
};
dump(&m);
zero_matrix(&m);
dump(&m);
return 0;
}
|
/****************************************************************************
* Copyright (C) from 2009 to Present EPAM Systems.
*
* This file is part of Indigo toolkit.
*
* 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 "molecule/molecule_name_parser.h"
using namespace std;
using namespace indigo;
IMPL_ERROR(MoleculeNameParser, "indigo::MoleculeNameParser");
IMPL_ERROR(MoleculeNameParser::DictionaryManager, "MoleculeNameParser::DictionaryManager");
IMPL_ERROR(MoleculeNameParser::Parse, "MoleculeNameParser::Parse");
IMPL_ERROR(MoleculeNameParser::TreeBuilder, "MoleculeNameParser::TreeBuilder");
IMPL_ERROR(MoleculeNameParser::SmilesBuilder, "MoleculeNameParser::SmilesBuilder");
MoleculeNameParser::DictionaryManager::DictionaryManager()
{
_readTokenTypeStrings();
_readTable(alkanes_table, true);
_readTable(multipliers_table, true);
_readTable(separators_table);
_readTable(flags_table, true);
_readTable(trivial_table, true);
_readSkeletalAtomsTable();
_readBasicElementsTable();
}
void MoleculeNameParser::DictionaryManager::_readSkeletalAtomsTable()
{
TiXmlDocument doc;
doc.Parse(skeletal_table);
if (doc.Error())
{
throw Error("Cannot parse table %s", skeletal_table);
}
TiXmlHandle hdoc(&doc);
TiXmlHandle tokenTables = hdoc.FirstChild("tokenTables");
TiXmlElement* tokenTable = tokenTables.FirstChild("tokenTable").ToElement();
for (; tokenTable; tokenTable = tokenTable->NextSiblingElement())
{
const char* name = tokenTable->Attribute("name");
const char* type = tokenTable->Attribute("type");
if (!name || !type)
{
throw Error("Cannot parse table");
}
TokenType tt = _tokenTypeFromString(type);
TiXmlElement* e = tokenTable->FirstChild("token")->ToElement();
for (; e; e = e->NextSiblingElement())
{
const char* lexeme = e->GetText();
const char* bonding = e->Attribute("bonding");
const char* symbol = e->Attribute("symbol");
if (!lexeme || !bonding || !symbol)
{
throw Error("Cannot parse table %s", name);
}
/*
For skeletal atoms, we combine bonding number and symbol into one value
Values are separated by underscore _
*/
string value = bonding;
value += '_';
value += symbol;
_addLexeme(lexeme, {name, value, tt}, true);
}
}
}
void MoleculeNameParser::DictionaryManager::_readBasicElementsTable()
{
TiXmlDocument doc;
doc.Parse(basic_elements_table);
if (doc.Error())
{
throw Error("Cannot parse table %s", basic_elements_table);
}
TiXmlHandle hdoc(&doc);
TiXmlHandle tokenTables = hdoc.FirstChild("tokenTables");
TiXmlElement* tokenTable = tokenTables.FirstChild("tokenTable").ToElement();
for (; tokenTable; tokenTable = tokenTable->NextSiblingElement())
{
const char* name = tokenTable->Attribute("name");
const char* type = tokenTable->Attribute("type");
if (!name || !type)
{
throw Error("Cannot parse table");
}
TokenType tt = _tokenTypeFromString(type);
TiXmlElement* e = tokenTable->FirstChild("token")->ToElement();
for (; e; e = e->NextSiblingElement())
{
const char* lexeme = e->GetText();
const char* number = e->Attribute("number");
const char* symbol = e->Attribute("symbol");
if (!lexeme || !number || !symbol)
{
throw Error("Cannot parse table %s", name);
}
/*
For basic elements, we combine number and symbol into one value
Values are separated by underscore _
*/
string value = number;
value += '_';
value += symbol;
/*
Symbols might have a separator '|', in which case we need to add
several symbols with the same token type into the dictionary
*/
char delim[] = "|";
char* fragment = ::strtok(const_cast<char*>(lexeme), delim);
while (fragment)
{
_addLexeme(fragment, {name, value, tt}, true);
fragment = ::strtok(nullptr, delim);
}
}
}
}
void MoleculeNameParser::DictionaryManager::_readTokenTypeStrings()
{
TiXmlDocument doc;
doc.Parse(token_types_table);
if (doc.Error())
{
throw Error("Cannot parse the token types table");
}
TiXmlHandle hdoc(&doc);
TiXmlHandle tokenTypes = hdoc.FirstChild("tokenTypes");
TiXmlElement* e = tokenTypes.FirstChild("tokenType").ToElement();
for (; e; e = e->NextSiblingElement())
{
_tokenTypeStrings.push_back(e->GetText());
}
}
void MoleculeNameParser::DictionaryManager::_readTable(const char* table, bool useTrie /* = false*/)
{
TiXmlDocument doc;
doc.Parse(table);
if (doc.Error())
{
throw Error("Cannot parse table %s", table);
}
TiXmlHandle hdoc(&doc);
TiXmlHandle tokenTables = hdoc.FirstChild("tokenTables");
TiXmlElement* tokenTable = tokenTables.FirstChild("tokenTable").ToElement();
for (; tokenTable; tokenTable = tokenTable->NextSiblingElement())
{
const char* name = tokenTable->Attribute("name");
const char* type = tokenTable->Attribute("type");
if (!name || !type)
{
throw Error("Cannot parse table");
}
const bool isSeparator = (::strcmp(name, "separator") == 0);
TokenType tt = _tokenTypeFromString(type);
TiXmlElement* e = tokenTable->FirstChild("token")->ToElement();
for (; e; e = e->NextSiblingElement())
{
const char* lexeme = e->GetText();
const char* value = e->Attribute("value");
if (!lexeme || !value)
{
throw Error("Cannot parse table %s", name);
}
// Symbols might have a separator '|', in which case we need to add
// several symbols with the same token type into the dictionary
char delim[] = "|";
char* fragment = ::strtok(const_cast<char*>(lexeme), delim);
while (fragment)
{
_addLexeme(fragment, Token(name, value, tt), useTrie);
fragment = ::strtok(nullptr, delim);
}
// all separators are 1-byte ASCII
if (isSeparator)
{
separators.push_back(lexeme[0]);
}
}
}
}
void MoleculeNameParser::DictionaryManager::_addLexeme(const string& lexeme, const Token& token, bool useTrie)
{
dictionary[lexeme] = token;
if (useTrie)
{
lexemesTrie.addWord(lexeme, token);
}
}
/*
Converts a token type name into token type value
Returns TokenType::UNKNOWN if no matching found
*/
MoleculeNameParser::TokenType MoleculeNameParser::DictionaryManager::_tokenTypeFromString(const string& s)
{
const auto& begin = std::begin(_tokenTypeStrings);
const auto& end = std::end(_tokenTypeStrings);
const auto& it = std::find(begin, end, s);
if (it != end)
{
return static_cast<TokenType>(std::distance(begin, it));
}
return TokenType::UNKNOWN;
}
/*
Performs by-symbol input scan, determines basic tokens
Text fragments require further processing
*/
void MoleculeNameParser::Parse::scan()
{
const DictionaryManager& dm = mnp.dictionaryManager;
const SymbolDictionary& sd = dm.dictionary;
const string& separators = dm.separators;
// Check for trivial names
const string& trivial = input;
const auto& it = sd.find(trivial);
if (it != sd.end())
{
lexemes.push_back(Lexeme(it->first, it->second));
Token terminator("", "", TokenType::END_OF_STREAM);
lexemes.push_back(Lexeme("", terminator));
return;
}
const size_t length = input.length();
// A buffer for locant symbol(s)
string locant;
/*
If a symbol is a separator, convert it into a lexeme
If not, scan until either a next separator, flag, or an end of the string
is reached, then add a lexeme for text fragment
By this time we already know that brackets do match
*/
for (size_t i = 0; i < length; i++)
{
char ch = input[i];
// whitespace is a special case
if (ch == ' ')
{
Token token{"separator", {ch}, TokenType::PUNCTUATION};
lexemes.push_back({ch, token});
}
/*
The input symbol is a separator; add a separator lexeme
*/
size_t pos = separators.find(ch);
if (pos != separators.npos)
{
const auto& it = sd.find({ch});
if (it != sd.end())
{
// For locants, we need additional check if the number is multi-digit
if (std::isdigit(ch))
{
locant += ch;
while (std::isdigit(input[i + 1]))
{
locant += input[i + 1];
++i;
}
lexemes.push_back(Lexeme(locant, Token("separator", locant, TokenType::LOCANT)));
locant.clear();
continue;
}
lexemes.push_back(Lexeme(ch, it->second));
}
continue;
}
/*
The current fragment is a text fragment
Search until a next separator or the end of string, check the dictionary,
process text fragment
*/
size_t next = input.find_first_of(separators, i);
if (next == input.npos)
{
string fragment = input.substr(i, length - i);
_processTextFragment(fragment);
break;
}
else
{
string fragment = input.substr(i, next - i);
_processTextFragment(fragment);
i = next - 1;
continue;
}
}
Token terminator("", "", TokenType::END_OF_STREAM);
lexemes.push_back(Lexeme("", terminator));
}
// Retrieves a next lexeme from the stream, incrementing the stream pointer
const MoleculeNameParser::Lexeme& MoleculeNameParser::Parse::getNextLexeme() const
{
if (currentLexeme < lexemes.size())
{
return lexemes[currentLexeme++];
}
throw Error("Lexemes stream pointer overflow");
}
// Returns true if next lexeme's token type equals to input
bool MoleculeNameParser::Parse::peekNextToken(TokenType peek) const
{
const Lexeme& lexeme = lexemes[currentLexeme];
return (lexeme.token.type == peek);
}
/*
Splits a fragment into smaller lexemes
Sets up the failure flag if unparsable fragment is encountered
*/
void MoleculeNameParser::Parse::_processTextFragment(const string& fragment)
{
const DictionaryManager& dm = mnp.dictionaryManager;
const LexemesTrie& root = dm.lexemesTrie;
const size_t fLength = fragment.length();
// global position inside the input string
size_t total = 0;
string buffer = fragment;
/*
Slow track with elision, see tryElision
*/
while (total < fLength)
{
/*
Fast track if trie already contains the word
*/
if (root.isWord(buffer))
{
const Trie<Token>* wordNode = root.getNode(buffer);
const Token& token = wordNode->getData();
lexemes.push_back(Lexeme(buffer, token));
return;
}
// current position inside a buffer
int current = 0;
const Trie<Token>* match = root.getNode({buffer[0]});
if (!match)
{
failures.push_back(buffer);
hasFailures = true;
return;
}
while (match && !match->isMark())
{
match = match->getNode({buffer[++current]});
total++;
}
// need to increment counters here, as we manupulate characters and
// not buffer positions
current++;
total++;
string lexeme = buffer.substr(0, current);
if (!match)
{
if (_tryElision(lexeme))
{
// decrement counters as we step back 1 char
total--;
buffer = buffer.substr(--current);
continue;
}
failures.push_back(lexeme);
hasFailures = true;
return;
}
const Token& token = match->getData();
lexemes.push_back(Lexeme(lexeme, token));
buffer = buffer.substr(current);
}
}
/*
Tries to apply different elision rules to a lexeme
For instance, 'pentyl' consists of 2 lexemes, 'penta' and 'yl',
with 'a' being elided. Hence, the first lexeme will be 'penty',
and parsing will fail as there's no known word 'penty'
The idea is to try several different word endidngs and see if we actually
know the word in question
*/
bool MoleculeNameParser::Parse::_tryElision(const string& failure)
{
const DictionaryManager& dm = mnp.dictionaryManager;
const LexemesTrie& root = dm.lexemesTrie;
string endings = "aoey";
string tryout = failure;
for (char ch : endings)
{
tryout.replace(tryout.length() - 1, 1, {ch});
if (!root.isWord(tryout))
{
tryout = failure;
tryout.insert(0, 1, ch);
if (!root.isWord(tryout))
{
tryout = failure;
tryout += ch;
if (!root.isWord(tryout))
{
return false;
}
}
}
_processTextFragment(tryout);
return true;
}
return false;
}
MoleculeNameParser::FragmentNode::~FragmentNode()
{
for (FragmentNode* node : nodes)
{
delete node;
}
}
// Inserts a new node before anchor position, returns status
bool MoleculeNameParser::FragmentNode::insertBefore(FragmentNode* node, const FragmentNode* anchor)
{
node->parent = this;
const auto& position = std::find(nodes.begin(), nodes.end(), anchor);
if (position != nodes.end())
{
nodes.insert(position, node);
return true;
}
return false;
}
void MoleculeNameParser::FragmentNode::insert(FragmentNode* node)
{
node->parent = this;
nodes.push_back(node);
}
#ifdef DEBUG
void MoleculeNameParser::FragmentNode::print(ostream& out) const
{
out << "Parent: " << parent << endl;
if (classType == FragmentClassType::INVALID)
{
out << "Type: INVALID" << endl;
}
}
void MoleculeNameParser::FragmentNodeRoot::print(ostream& out) const
{
out << "Type: FragmentNodeRoot" << endl;
FragmentNode::print(out);
}
void MoleculeNameParser::FragmentNodeBase::print(ostream& out) const
{
out << "Type: FragmentNodeBase" << endl;
out << "Multipliers:" << endl;
auto muls = multipliers;
Multipliers muls_rev;
while (!muls.empty())
{
muls_rev.push(muls.top());
muls.pop();
}
while (!muls_rev.empty())
{
out << "\tvalue: " << muls_rev.top().first << endl;
muls_rev.pop();
}
out << "Locants:" << endl;
for (int locant : locants)
{
out << "\tvalue: " << locant << endl;
}
out << "Element: " << endl;
out << "\tnumber: " << element.first << endl;
out << "\tsymbol: " << element.second << endl;
FragmentNode::print(out);
}
void MoleculeNameParser::FragmentNodeSubstituent::print(ostream& out) const
{
out << "Type: FragmentNodeSubstituent" << endl;
out << "Positions:" << endl;
for (int pos : positions)
{
out << "\tvalue: " << pos << endl;
}
out << "Fragment multiplier: " << fragmentMultiplier << endl;
FragmentNodeBase::print(out);
}
#if 0
ostream& operator<<(ostream& out, const MoleculeNameParser::FragmentNode& node) {
node.print(out);
return out;
}
ostream& operator<<(ostream& out, const MoleculeNameParser::FragmentNode* node) {
node->print(out);
return out;
}
#endif
#endif // DEBUG
MoleculeNameParser::FragmentNodeBase::FragmentNodeBase()
{
classType = FragmentClassType::BASE;
element.first = ELEM_MIN;
}
/*
Returns the sum of multipliers stack
This is a destructive operation
*/
int MoleculeNameParser::FragmentNodeBase::combineMultipliers()
{
int result = 0;
while (!multipliers.empty())
{
const Multiplier& mul = multipliers.top();
result += mul.first;
multipliers.pop();
}
assert(multipliers.empty());
return result;
}
MoleculeNameParser::FragmentBuildTree::FragmentBuildTree()
{
addRoot();
}
MoleculeNameParser::FragmentBuildTree::~FragmentBuildTree()
{
for (FragmentNode* root : roots)
{
delete root;
}
}
void MoleculeNameParser::FragmentBuildTree::addRoot()
{
FragmentNode* root = new FragmentNodeRoot;
currentRoot = root;
roots.push_back(root);
}
bool MoleculeNameParser::TreeBuilder::processParse()
{
_initBuildTree();
return _processParse();
}
void MoleculeNameParser::TreeBuilder::_initBuildTree()
{
FragmentNodeBase* node = new FragmentNodeBase;
FragmentNode* root = buildTree.currentRoot;
root->insert(node);
_current = node;
}
/*
Checks if certain options are (un)set
Returns true if condition matches
*/
bool MoleculeNameParser::TreeBuilder::_checkParserOption(ParserOptionsType options)
{
return (_parse->mnp.getOptions() & options) == options;
}
/*
Returns one level up in the tree, setting current node to the new
level's base fragment
Returns false if operation cannot be performed
*/
bool MoleculeNameParser::TreeBuilder::_upOneLevel()
{
if (_parse->peekNextToken(TokenType::END_OF_STREAM))
{
return true;
}
if (_current->classType == FragmentClassType::BASE)
{
if (!_current->parent)
{
return false;
}
}
_startNewNode = true;
_current = _getParentBase();
return (_current != nullptr);
}
/*
The implementation of parse processing
Recursively calls itself until EndOfStream is reached or error occured
*/
bool MoleculeNameParser::TreeBuilder::_processParse()
{
const Lexeme& lexeme = _parse->getNextLexeme();
const TokenType& tt = lexeme.token.type;
if (lexeme.processed)
{
if (tt == TokenType::SUFFIXES && lexeme.lexeme == "yl")
{
_current = _getCurrentBase();
}
return _processParse();
}
if (tt == TokenType::END_OF_STREAM)
{
return true;
}
if ((tt == TokenType::UNKNOWN) || (tt == TokenType::TEXT))
{
return false;
}
const string& tname = lexeme.token.name;
if (tname == "alkanes")
{
if (!_processAlkane(lexeme))
{
return false;
}
}
else if (tname == "multiplier")
{
if (!_processMultiplier(lexeme))
{
return false;
}
}
else if (tname == "separator")
{
if (!_processSeparator(lexeme))
{
return false;
}
}
else if (tname == "basicElement")
{
if (!_processBasicElement(lexeme))
{
return false;
}
}
else if (tname == "flags")
{
if (!_processFlags(lexeme))
{
return false;
}
}
else if (tname == "skeletal")
{
if (!_processSkeletal(lexeme))
{
return false;
}
}
return _processParse();
}
bool MoleculeNameParser::TreeBuilder::_processSkeletalPrefix(const Lexeme& lexeme)
{
if (_current->classType != FragmentClassType::SUBSTITUENT)
{
FragmentNodeSubstituent* subst = new FragmentNodeSubstituent;
if (!_current->parent->insertBefore(subst, _getCurrentBase()))
{
return false;
}
subst->positions.push_back(1);
FragmentNodeBase* levelBase = _getCurrentBase();
if (levelBase->locants.empty())
{
levelBase->locants.push_back(1);
}
_current = subst;
}
const Token& token = lexeme.token;
const string& value = token.value;
const size_t pos = value.find('_');
if (pos == string::npos)
{
return false;
}
const string bonding = value.substr(0, pos);
const string symbol = value.substr(pos + 1);
FragmentNodeBase* base = dynamic_cast<FragmentNodeBase*>(_current);
base->element.first = indigo::Element::fromString(symbol.c_str());
base->element.second = symbol;
base->nodeType = NodeType::SKELETAL;
base->bondType = BOND_SINGLE;
base->bonding = _strToInt(bonding);
base->multipliers.push({1, TokenType::BASIC});
/*
We erase skeletal positions from base's locants list, as skeletals are not
substituents, and move it into skeletals
*/
FragmentNodeBase* levelBase = _getCurrentBase();
Locants& locants = levelBase->locants;
Skeletals& skeletals = levelBase->skeletals;
FragmentNodeSubstituent* subst = dynamic_cast<FragmentNodeSubstituent*>(_current);
for (int n : subst->positions)
{
const auto& it = std::find(locants.begin(), locants.end(), n);
if (it != locants.end())
{
int val = *it;
locants.erase(it);
skeletals.push_back(val);
}
}
_current = _getCurrentBase();
_startNewNode = true;
lexeme.processed = true;
return true;
}
bool MoleculeNameParser::TreeBuilder::_processSkeletal(const Lexeme& lexeme)
{
bool result = true;
switch (lexeme.token.type)
{
case TokenType::SKELETAL_PREFIX: {
result = _processSkeletalPrefix(lexeme);
}
break;
default:
break;
}
return result;
}
bool MoleculeNameParser::TreeBuilder::_processFlags(const Lexeme& lexeme)
{
const string& name = lexeme.lexeme;
if (name == "cyclo")
{
FragmentNodeBase* base = _getCurrentBase();
if (base == nullptr)
{
return false;
}
if (base->cycle == true)
{
return false;
}
base->cycle = true;
lexeme.processed = true;
return true;
}
if (name == "cis" || name == "trans")
{
if ((_current->classType == FragmentClassType::SUBSTITUENT) || (_current->classType == FragmentClassType::BASE))
{
FragmentNodeBase* base = dynamic_cast<FragmentNodeBase*>(_current);
if (name == "cis")
{
base->isomerism = Isomerism::CIS;
}
else
{
base->isomerism = Isomerism::TRANS;
}
lexeme.processed = true;
return true;
}
}
return false;
}
bool MoleculeNameParser::TreeBuilder::_processBasicElement(const Lexeme& lexeme)
{
if (_current->classType != FragmentClassType::BASE)
{
return false;
}
const string& value = lexeme.token.value;
const size_t pos = value.find('_');
if (pos == string::npos)
{
return false;
}
const string number = value.substr(0, pos);
const string symbol = value.substr(pos + 1);
const int element = _strToInt(number);
FragmentNodeBase* base = dynamic_cast<FragmentNodeBase*>(_current);
base->element.first = element;
base->element.second = symbol;
base->nodeType = NodeType::ELEMENT;
base->multipliers.push({1, TokenType::BASIC});
lexeme.processed = true;
return true;
}
/*
Processes suffixes
Suffixes are -ane, -ene, -yne|-yn, -yl
-ane means that all bonds are single, e.g. hexane CCCCCC
-ene means that at least the first bond is double
locants signify multiple atoms with double bonds, e.g. 2,4-hexadiene CC=CC=CC
-yne|-yn means that at least the first bond is triple
locants signify multiple atoms with triple bonds, e.g. 2,4-hexadiyne CC#CC#CC
*/
void MoleculeNameParser::TreeBuilder::_processSuffix(const Lexeme& lexeme)
{
FragmentNodeBase* base = dynamic_cast<FragmentNodeBase*>(_current);
if (base->nodeType == NodeType::INVALID)
{
base->nodeType = NodeType::SUFFIX;
}
base->element.first = ELEM_C;
base->element.second = "C";
if (base->multipliers.empty())
{
base->multipliers.push({1, TokenType::BASIC});
}
// A stardard carbon bonding
const int carbonBonding = 4;
if (lexeme.lexeme == "ane")
{
base->bondType = BOND_SINGLE;
base->bonding = carbonBonding - BOND_SINGLE;
base->freeAtoms = 0;
}
else if (lexeme.lexeme == "yl")
{
base->bondType = BOND_SINGLE;
base->bonding = carbonBonding - BOND_SINGLE - 1;
base->freeAtoms = 1;
}
else if (lexeme.lexeme == "ene")
{
base->bondType = BOND_DOUBLE;
base->bonding = carbonBonding - BOND_DOUBLE;
base->freeAtoms = 0;
}
else if (lexeme.lexeme == "yne" || lexeme.lexeme == "yn")
{
base->bondType = BOND_TRIPLE;
base->bonding = carbonBonding - BOND_TRIPLE;
base->freeAtoms = 0;
}
if (_current->classType == FragmentClassType::SUBSTITUENT)
{
FragmentNodeBase* currentBase = _getCurrentBase();
if (!currentBase)
{
throw Error("Can't get current level base node");
}
currentBase->element.first = ELEM_C;
currentBase->element.second = "C";
_startNewNode = true;
}
}
bool MoleculeNameParser::TreeBuilder::_processAlkaneBase(const Lexeme& lexeme)
{
FragmentNodeBase* base = dynamic_cast<FragmentNodeBase*>(_current);
base->nodeType = NodeType::BASE;
int value = _strToInt(lexeme.token.value);
base->multipliers.push({value, TokenType::BASIC});
return true;
}
bool MoleculeNameParser::TreeBuilder::_processAlkaneSuffix(const Lexeme& lexeme)
{
_processSuffix(lexeme);
if (_parse->peekNextToken(TokenType::CLOSING_BRACKET))
{
lexeme.processed = true;
return true;
}
if (_current->classType == FragmentClassType::SUBSTITUENT)
{
_current = _getCurrentBase();
if (!_current)
{
return false;
}
}
else if (_current->classType == FragmentClassType::BASE)
{
if (!_upOneLevel())
{
return false;
}
}
lexeme.processed = true;
return true;
}
// Processes alkane lexemes
bool MoleculeNameParser::TreeBuilder::_processAlkane(const Lexeme& lexeme)
{
bool result = true;
switch (lexeme.token.type)
{
case TokenType::BASES: {
result = _processAlkaneBase(lexeme);
}
break;
case TokenType::SUFFIXES: {
result = _processAlkaneSuffix(lexeme);
}
break;
default:
break;
}
return result;
}
bool MoleculeNameParser::TreeBuilder::_processBasicMultiplier(const Lexeme& lexeme)
{
const int value = _strToInt(lexeme.token.value);
if (_current->classType == FragmentClassType::SUBSTITUENT)
{
FragmentNodeSubstituent* node = dynamic_cast<FragmentNodeSubstituent*>(_current);
if (node->expectFragMultiplier)
{
if (value != (int)node->positions.size())
{
throw Error("Locants and fragment multiplier don't match");
}
node->fragmentMultiplier = value;
bool flag = _parse->peekNextToken(TokenType::FACTOR);
node->expectFragMultiplier = flag;
lexeme.processed = true;
return true;
}
}
FragmentNodeBase* base = dynamic_cast<FragmentNodeBase*>(_current);
base->multipliers.push({value, lexeme.token.type});
base->nodeType = NodeType::BASE;
lexeme.processed = true;
return true;
}
bool MoleculeNameParser::TreeBuilder::_processFactorMultiplier(const Lexeme& lexeme)
{
const int value = _strToInt(lexeme.token.value);
if (_current->classType == FragmentClassType::SUBSTITUENT)
{
FragmentNodeSubstituent* node = dynamic_cast<FragmentNodeSubstituent*>(_current);
if (node->expectFragMultiplier)
{
if (node->fragmentMultiplier != 1)
{
node->fragmentMultiplier *= value;
}
node->expectFragMultiplier = false;
lexeme.processed = true;
return true;
}
}
FragmentNodeBase* base = dynamic_cast<FragmentNodeBase*>(_current);
Multipliers& multipliers = base->multipliers;
if (multipliers.empty())
{
multipliers.push({value, TokenType::BASIC});
}
else
{
const Multiplier& prev = multipliers.top();
int value = _strToInt(lexeme.token.value);
value *= prev.first;
multipliers.pop();
multipliers.push({value, TokenType::BASIC});
}
base->nodeType = NodeType::BASE;
lexeme.processed = true;
return true;
}
// Processes multiplier lexemes
bool MoleculeNameParser::TreeBuilder::_processMultiplier(const Lexeme& lexeme)
{
bool result = true;
switch (lexeme.token.type)
{
case TokenType::BASIC: {
result = _processBasicMultiplier(lexeme);
}
break;
case TokenType::FACTOR: {
result = _processFactorMultiplier(lexeme);
}
break;
default:
break;
}
return result;
}
bool MoleculeNameParser::TreeBuilder::_processLocant(const Lexeme& lexeme)
{
int value = _strToInt(lexeme.token.value);
if (value == 0)
{
return false;
}
if (_startNewNode)
{
FragmentNodeSubstituent* subst = new FragmentNodeSubstituent;
if (!_current->parent->insertBefore(subst, _getCurrentBase()))
{
return false;
}
_current = subst;
_startNewNode = false;
}
FragmentNodeSubstituent* subst = dynamic_cast<FragmentNodeSubstituent*>(_current);
subst->positions.push_back(value);
FragmentNodeBase* base = _getCurrentBase();
base->locants.push_back(value);
if (!_checkParserOption(IUPAC_STRICT))
{
auto it = _parse->lexemes.begin();
std::advance(it, _parse->currentLexeme);
if ((it->token.type == TokenType::PUNCTUATION) && (it->lexeme == ","))
{
lexeme.processed = true;
return true;
}
/*
Look for nearest suffix
Then, check previous multiplier. If it's not equal to expected multiplier,
continue to parse lexemes in order
*/
while (!(it->token.type == TokenType::LOCANT || it->token.type == TokenType::SUFFIXES || it->token.type == TokenType::SKELETAL_PREFIX ||
it->token.type == TokenType::END_OF_STREAM))
{
++it;
}
switch (it->token.type)
{
// shouldn't be here
case TokenType::END_OF_STREAM: {
return false;
}
break;
// mark lexeme as processed, continue with processing
case TokenType::SKELETAL_PREFIX:
case TokenType::LOCANT: {
lexeme.processed = true;
return true;
}
break;
case TokenType::SUFFIXES: {
if (it->lexeme == "yl")
{
lexeme.processed = true;
return true;
}
if (subst->positions.size() == 1)
{
return _processAlkaneSuffix(*it);
}
auto prev = std::prev(it);
if (prev->token.type == TokenType::BASIC)
{
if (!_processMultiplier(*prev))
{
lexeme.processed = false;
return true;
}
return _processAlkaneSuffix(*it);
}
}
break;
default:
return false;
}
}
lexeme.processed = true;
return true;
}
bool MoleculeNameParser::TreeBuilder::_processPunctuation(const Lexeme& lexeme)
{
if (lexeme.lexeme == ",")
{
if (_current->classType != FragmentClassType::SUBSTITUENT)
{
return false;
}
dynamic_cast<FragmentNodeSubstituent*>(_current)->expectFragMultiplier = true;
lexeme.processed = true;
return true;
}
/*
Whitespace is a special case when we actually add a new build tree
for a new structure
*/
// FIXME - process acids (acid names have whitespace)
if (lexeme.lexeme == " ")
{
buildTree.addRoot();
_initBuildTree();
lexeme.processed = true;
return true;
}
lexeme.processed = true;
return true;
}
// Processes separator lexemes
bool MoleculeNameParser::TreeBuilder::_processSeparator(const Lexeme& lexeme)
{
switch (lexeme.token.type)
{
case TokenType::OPENING_BRACKET: {
// empty brackets aren't allowed
if (_parse->peekNextToken(TokenType::CLOSING_BRACKET))
{
return false;
}
FragmentNodeBase* base = new FragmentNodeBase;
base->nodeType = NodeType::BASE;
_current->insert(base);
_current = base;
_startNewNode = true;
}
break;
case TokenType::CLOSING_BRACKET: {
if (!_upOneLevel())
{
return false;
}
}
break;
case TokenType::LOCANT: {
return _processLocant(lexeme);
}
break;
// currently no-op
case TokenType::PRIME:
break;
case TokenType::PUNCTUATION: {
return _processPunctuation(lexeme);
}
break;
default:
break;
}
lexeme.processed = true;
return true;
}
// Converts std::string to int
int MoleculeNameParser::TreeBuilder::_strToInt(const string& str)
{
char* ch = nullptr;
return std::strtol(str.c_str(), &ch, 10);
}
// Retrieves current level's base; each level has only one base
MoleculeNameParser::FragmentNodeBase* MoleculeNameParser::TreeBuilder::_getCurrentBase()
{
if (_current->classType == FragmentClassType::BASE)
{
return dynamic_cast<FragmentNodeBase*>(_current);
}
FragmentNode* parent = _current->parent;
if (!parent)
{
return nullptr;
}
// Base is always the rightmost node
return dynamic_cast<FragmentNodeBase*>(parent->nodes.back());
}
// Retrieves upper level's base, if any; each level has only one base
MoleculeNameParser::FragmentNodeBase* MoleculeNameParser::TreeBuilder::_getParentBase()
{
const FragmentNode* parent = _current->parent;
if (!parent)
{
return nullptr;
}
const FragmentNode* grand = parent->parent;
if (!grand)
{
return nullptr;
}
// Base is always the rightmost node
return dynamic_cast<FragmentNodeBase*>(grand->nodes.back());
}
void MoleculeNameParser::SmilesBuilder::_initOrganicElements()
{
_organicElements[ELEM_B] = "B";
_organicElements[ELEM_C] = "C";
_organicElements[ELEM_N] = "N";
_organicElements[ELEM_O] = "O";
_organicElements[ELEM_P] = "P";
_organicElements[ELEM_S] = "S";
_organicElements[ELEM_F] = "F";
_organicElements[ELEM_Cl] = "Cl";
_organicElements[ELEM_Br] = "Br";
}
void MoleculeNameParser::SmilesBuilder::_buildSmiles(SmilesRoot& root)
{
for (SmilesNode& node : root.nodes)
{
_SMILES += node.str;
if (node.bondType == BOND_DOUBLE)
{
_SMILES += "=";
}
if (node.bondType == BOND_TRIPLE)
{
_SMILES += "#";
}
if (!node.roots.empty())
{
for (SmilesRoot& r : node.roots)
{
_SMILES += "(";
_buildSmiles(r);
_SMILES += ")";
}
}
}
}
/*
Traverses the build tree in post-order depth-first order, creates
SMILES representation and loads the SMILES into the resulting Molecule
*/
bool MoleculeNameParser::SmilesBuilder::buildResult(Molecule& molecule)
{
molecule.clear();
const FragmentBuildTree& buildTree = _treeBuilder.buildTree;
const Nodes& roots = buildTree.roots;
if (roots.empty())
{
return false;
}
// most time we'll have a sigle root
for (FragmentNode* root : roots)
{
const Nodes& nodes = root->nodes;
if (!_processNodes(nodes, _smilesTree))
{
return false;
}
}
_buildSmiles(_smilesTree);
BufferScanner scanner(_SMILES.c_str());
SmilesLoader loader(scanner);
loader.loadMolecule(molecule);
return true;
}
bool MoleculeNameParser::SmilesBuilder::_processNodes(const Nodes& nodes, SmilesRoot& root)
{
auto node = nodes.rbegin();
if (!_processBaseNode(dynamic_cast<FragmentNodeBase*>(*node), root))
{
return false;
}
++node;
while (node != nodes.rend())
{
if (!_processSubstNode(dynamic_cast<FragmentNodeSubstituent*>(*node), root))
{
return false;
}
++node;
}
return true;
}
/*
Processes a base node. A base node contains information about structure or
substituent base: number of locants, chemical element info, bonds, etc.
*/
bool MoleculeNameParser::SmilesBuilder::_processBaseNode(FragmentNodeBase* base, SmilesRoot& root)
{
const NodeType& nt = base->nodeType;
const Element& element = base->element;
const int number = element.first;
const int multipliers = base->combineMultipliers();
if (multipliers >= 1)
{
bool organicElement = (_organicElements.find(number) != _organicElements.end());
if (nt == NodeType::ELEMENT)
{
organicElement = false;
}
const string& symbol = organicElement ? _organicElements[number] : "[" + element.second + "]";
SmilesNode node(symbol, BOND_SINGLE, &root);
root.nodes.push_back(std::move(node));
for (int i = 1; i < multipliers; i++)
{
SmilesNode node(symbol, BOND_SINGLE, &root);
root.nodes.push_back(std::move(node));
}
}
if (base->cycle)
{
SmilesNode& first = root.nodes.front();
first.str += "1";
SmilesNode& last = root.nodes.back();
last.str += "1";
}
if (base->bondType != BOND_SINGLE)
{
SmilesNode& sn = root.nodes.front();
sn.bondType = base->bondType;
}
return true;
}
void MoleculeNameParser::SmilesBuilder::_calcHydrogens(const Element& element, int pos, SmilesRoot& root)
{
int number = indigo::Element::fromString(element.second.c_str());
if (number == ELEM_C)
{
return;
}
bool organicElement = (_organicElements.find(number) != _organicElements.end());
int connections = indigo::Element::getMaximumConnectivity(number, 0, 0, false);
int valence = indigo::Element::calcValenceMinusHyd(number, 0, 0, connections);
SmilesNode& sn = root.nodes.at(pos - 1);
string buffer;
if (!organicElement)
{
int hydrogens = 0;
if (root.nodes.size() == 1)
{
hydrogens = valence;
}
else
{
if (pos > 1)
{
const SmilesNode& prev = root.nodes.at(pos - 2);
int prevBond = prev.bondType;
hydrogens = valence - prevBond - sn.bondType;
}
else
{
hydrogens = valence - sn.bondType;
}
}
if (hydrogens > 0)
{
char buff[3];
::sprintf(buff, "%d", hydrogens);
buffer += "[" + element.second + "H" + buff + "]";
}
else
{
buffer += "[" + element.second + "]";
}
}
else
{
buffer = _organicElements[number];
}
sn.str = buffer;
}
/*
Processes a substituent node. Any substituent might also be a base
*/
bool MoleculeNameParser::SmilesBuilder::_processSubstNode(FragmentNodeSubstituent* subst, SmilesRoot& root)
{
const Nodes& nodes = subst->nodes;
const Positions& positions = subst->positions;
if (!nodes.empty())
{
for (int pos : positions)
{
SmilesNode& sn = root.nodes.at(pos - 1);
sn.roots.push_back(SmilesRoot{&sn});
if (!_processNodes(nodes, sn.roots.back()))
{
return false;
}
}
return true;
}
FragmentNodeBase* as_base = subst;
const Element& element = as_base->element;
const int number = element.first;
bool organicElement = (_organicElements.find(number) != _organicElements.end());
switch (subst->nodeType)
{
case NodeType::SUFFIX: {
for (int pos : positions)
{
SmilesNode& sn = root.nodes.at(pos - 1);
sn.bondType = as_base->bondType;
_calcHydrogens(element, pos, root);
}
}
break;
case NodeType::SKELETAL: {
for (int pos : positions)
{
_calcHydrogens(element, pos, root);
}
}
break;
case NodeType::BASE: {
int multiplier = as_base->combineMultipliers();
for (int pos : positions)
{
SmilesNode& sn = root.nodes.at(pos - 1);
SmilesRoot r(&sn);
string symbol = organicElement ? _organicElements[number] : "[" + element.second + "]";
for (int i = 0; i < multiplier; i++)
{
r.nodes.push_back({symbol, BOND_SINGLE, &r});
}
sn.roots.push_back(std::move(r));
}
}
break;
default:
break;
}
return true;
}
bool MoleculeNameParser::SmilesBuilder::checkTrivial()
{
bool good = true;
for (const Lexeme& l : _parse->lexemes)
{
if (!(l.token.type == TokenType::TRIVIAL || l.token.type == TokenType::END_OF_STREAM))
{
good = false;
break;
}
}
return good;
}
void MoleculeNameParser::SmilesBuilder::buildTrivial(Molecule& molecule)
{
molecule.clear();
// currently, build the first trivial name
const Lexeme& l = _parse->getNextLexeme();
BufferScanner scanner(l.token.value.c_str());
SmilesLoader loader(scanner);
loader.loadMolecule(molecule);
}
/*
Main method for convertion from a chemical name into a Molecule object
A given name undergoes several transformations:
phase 1: lexical analysis
phase 2: tokenization
phase 3: grammatical rules check
phase 4: construction of a SMILES representation from parsed fragments
No param check - did that on caller side
*/
void MoleculeNameParser::parseMolecule(const char* name, Molecule& molecule)
{
string input(name);
std::transform(input.begin(), input.end(), input.begin(), [](unsigned long c) { return std::tolower(c); });
_checkBrackets(input);
Parse parse(input, *this);
parse.scan();
if (parse.hasFailures)
{
string message;
for (const string& f : parse.failures)
{
message += f + " ";
}
throw Error("Cannot parse input %s due to errors: %s", name, message.c_str());
}
SmilesBuilder builder(parse);
if (builder.checkTrivial())
{
builder.buildTrivial(molecule);
return;
}
if (!builder.buildTree())
{
molecule.clear();
throw Error("Cannot construct the build tree for name %s", name);
}
if (!builder.buildResult(molecule))
{
molecule.clear();
throw Error("Cannot build a resulting structure for name %s", name);
}
}
/*
Checks if allowed opening and closing brackets match
Doesn't check brackets type matching (e.g. ((]] is valid)
*/
void MoleculeNameParser::_checkBrackets(const string& s)
{
int level = 0;
for (char ch : s)
{
if (ch == '(' || ch == '[' || ch == '{')
{
level++;
continue;
}
if (ch == ')' || ch == ']' || ch == '}')
{
level--;
continue;
}
}
if (level != 0)
{
throw Error("Opening and closing brackets don't match: %d", level);
}
}
/*
Sets parsing options
Changes the 'options' parameter (via strtok())
*/
void MoleculeNameParser::setOptions(char* options)
{
// null check is on caller side
if (::strlen(options) == 0)
{
return;
}
char delim[] = " ";
char* option = ::strtok(options, delim);
while (option)
{
_setOption(option);
option = ::strtok(nullptr, delim);
}
}
// Turns a certain option on or off depending on input flag
void MoleculeNameParser::_setOption(const char* option)
{
string buffer = option;
if ((buffer[0] != '+') && (buffer[0] != '-'))
{
throw Error("Invalid option notation: %s", option);
}
bool on = (buffer[0] == '+') ? true : false;
if (std::move(buffer.substr(1)) == "IUPAC_STRICT")
{
on ? _options |= ParserOptions::IUPAC_STRICT : _options &= ~ParserOptions::IUPAC_STRICT;
}
}
|
// 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 "net/websockets/websocket_job.h"
#include <algorithm>
#include "base/bind.h"
#include "base/lazy_instance.h"
#include "base/string_tokenizer.h"
#include "googleurl/src/gurl.h"
#include "net/base/net_errors.h"
#include "net/base/net_log.h"
#include "net/cookies/cookie_store.h"
#include "net/base/io_buffer.h"
#include "net/http/http_network_session.h"
#include "net/http/http_transaction_factory.h"
#include "net/http/http_util.h"
#include "net/spdy/spdy_session.h"
#include "net/spdy/spdy_session_pool.h"
#include "net/url_request/url_request_context.h"
#include "net/websockets/websocket_handshake_handler.h"
#include "net/websockets/websocket_net_log_params.h"
#include "net/websockets/websocket_throttle.h"
static const int kMaxPendingSendAllowed = 32768; // 32 kilobytes.
namespace {
// lower-case header names.
const char* const kCookieHeaders[] = {
"cookie", "cookie2"
};
const char* const kSetCookieHeaders[] = {
"set-cookie", "set-cookie2"
};
net::SocketStreamJob* WebSocketJobFactory(
const GURL& url, net::SocketStream::Delegate* delegate) {
net::WebSocketJob* job = new net::WebSocketJob(delegate);
job->InitSocketStream(new net::SocketStream(url, job));
return job;
}
class WebSocketJobInitSingleton {
private:
friend struct base::DefaultLazyInstanceTraits<WebSocketJobInitSingleton>;
WebSocketJobInitSingleton() {
net::SocketStreamJob::RegisterProtocolFactory("ws", WebSocketJobFactory);
net::SocketStreamJob::RegisterProtocolFactory("wss", WebSocketJobFactory);
}
};
static base::LazyInstance<WebSocketJobInitSingleton> g_websocket_job_init =
LAZY_INSTANCE_INITIALIZER;
} // anonymous namespace
namespace net {
bool WebSocketJob::websocket_over_spdy_enabled_ = false;
// static
void WebSocketJob::EnsureInit() {
g_websocket_job_init.Get();
}
// static
void WebSocketJob::set_websocket_over_spdy_enabled(bool enabled) {
websocket_over_spdy_enabled_ = enabled;
}
WebSocketJob::WebSocketJob(SocketStream::Delegate* delegate)
: delegate_(delegate),
state_(INITIALIZED),
waiting_(false),
handshake_request_(new WebSocketHandshakeRequestHandler),
handshake_response_(new WebSocketHandshakeResponseHandler),
started_to_send_handshake_request_(false),
handshake_request_sent_(0),
response_cookies_save_index_(0),
spdy_protocol_version_(0),
ALLOW_THIS_IN_INITIALIZER_LIST(weak_ptr_factory_(this)),
ALLOW_THIS_IN_INITIALIZER_LIST(weak_ptr_factory_for_send_pending_(this)) {
}
WebSocketJob::~WebSocketJob() {
DCHECK_EQ(CLOSED, state_);
DCHECK(!delegate_);
DCHECK(!socket_.get());
}
void WebSocketJob::Connect() {
DCHECK(socket_.get());
DCHECK_EQ(state_, INITIALIZED);
state_ = CONNECTING;
socket_->Connect();
}
bool WebSocketJob::SendData(const char* data, int len) {
switch (state_) {
case INITIALIZED:
return false;
case CONNECTING:
return SendHandshakeRequest(data, len);
case OPEN:
{
scoped_refptr<IOBufferWithSize> buffer = new IOBufferWithSize(len);
memcpy(buffer->data(), data, len);
if (current_send_buffer_ || !send_buffer_queue_.empty()) {
send_buffer_queue_.push_back(buffer);
return true;
}
current_send_buffer_ = new DrainableIOBuffer(buffer.get(), len);
return SendDataInternal(current_send_buffer_->data(),
current_send_buffer_->BytesRemaining());
}
case CLOSING:
case CLOSED:
return false;
}
return false;
}
void WebSocketJob::Close() {
if (state_ == CLOSED)
return;
state_ = CLOSING;
if (current_send_buffer_) {
// Will close in SendPending.
return;
}
state_ = CLOSED;
CloseInternal();
}
void WebSocketJob::RestartWithAuth(const AuthCredentials& credentials) {
state_ = CONNECTING;
socket_->RestartWithAuth(credentials);
}
void WebSocketJob::DetachDelegate() {
state_ = CLOSED;
WebSocketThrottle::GetInstance()->RemoveFromQueue(this);
WebSocketThrottle::GetInstance()->WakeupSocketIfNecessary();
scoped_refptr<WebSocketJob> protect(this);
weak_ptr_factory_.InvalidateWeakPtrs();
weak_ptr_factory_for_send_pending_.InvalidateWeakPtrs();
delegate_ = NULL;
if (socket_)
socket_->DetachDelegate();
socket_ = NULL;
if (!callback_.is_null()) {
waiting_ = false;
callback_.Reset();
Release(); // Balanced with OnStartOpenConnection().
}
}
int WebSocketJob::OnStartOpenConnection(
SocketStream* socket, const CompletionCallback& callback) {
DCHECK(callback_.is_null());
state_ = CONNECTING;
addresses_ = socket->address_list();
WebSocketThrottle::GetInstance()->PutInQueue(this);
if (delegate_) {
int result = delegate_->OnStartOpenConnection(socket, callback);
DCHECK_EQ(OK, result);
}
if (waiting_) {
// PutInQueue() may set |waiting_| true for throttling. In this case,
// Wakeup() will be called later.
callback_ = callback;
AddRef(); // Balanced when callback_ is cleared.
return ERR_IO_PENDING;
}
return TrySpdyStream();
}
void WebSocketJob::OnConnected(
SocketStream* socket, int max_pending_send_allowed) {
if (state_ == CLOSED)
return;
DCHECK_EQ(CONNECTING, state_);
if (delegate_)
delegate_->OnConnected(socket, max_pending_send_allowed);
}
void WebSocketJob::OnSentData(SocketStream* socket, int amount_sent) {
DCHECK_NE(INITIALIZED, state_);
DCHECK_GT(amount_sent, 0);
if (state_ == CLOSED)
return;
if (state_ == CONNECTING) {
OnSentHandshakeRequest(socket, amount_sent);
return;
}
if (delegate_) {
DCHECK(state_ == OPEN || state_ == CLOSING);
if (!current_send_buffer_) {
VLOG(1) << "OnSentData current_send_buffer=NULL amount_sent="
<< amount_sent;
return;
}
current_send_buffer_->DidConsume(amount_sent);
if (current_send_buffer_->BytesRemaining() > 0)
return;
// We need to report amount_sent of original buffer size, instead of
// amount sent to |socket|.
amount_sent = current_send_buffer_->size();
DCHECK_GT(amount_sent, 0);
current_send_buffer_ = NULL;
if (!weak_ptr_factory_for_send_pending_.HasWeakPtrs()) {
MessageLoopForIO::current()->PostTask(
FROM_HERE,
base::Bind(&WebSocketJob::SendPending,
weak_ptr_factory_for_send_pending_.GetWeakPtr()));
}
delegate_->OnSentData(socket, amount_sent);
}
}
void WebSocketJob::OnReceivedData(
SocketStream* socket, const char* data, int len) {
DCHECK_NE(INITIALIZED, state_);
if (state_ == CLOSED)
return;
if (state_ == CONNECTING) {
OnReceivedHandshakeResponse(socket, data, len);
return;
}
DCHECK(state_ == OPEN || state_ == CLOSING);
if (delegate_ && len > 0)
delegate_->OnReceivedData(socket, data, len);
}
void WebSocketJob::OnClose(SocketStream* socket) {
state_ = CLOSED;
WebSocketThrottle::GetInstance()->RemoveFromQueue(this);
WebSocketThrottle::GetInstance()->WakeupSocketIfNecessary();
scoped_refptr<WebSocketJob> protect(this);
weak_ptr_factory_.InvalidateWeakPtrs();
SocketStream::Delegate* delegate = delegate_;
delegate_ = NULL;
socket_ = NULL;
if (!callback_.is_null()) {
waiting_ = false;
callback_.Reset();
Release(); // Balanced with OnStartOpenConnection().
}
if (delegate)
delegate->OnClose(socket);
}
void WebSocketJob::OnAuthRequired(
SocketStream* socket, AuthChallengeInfo* auth_info) {
if (delegate_)
delegate_->OnAuthRequired(socket, auth_info);
}
void WebSocketJob::OnSSLCertificateError(
SocketStream* socket, const SSLInfo& ssl_info, bool fatal) {
if (delegate_)
delegate_->OnSSLCertificateError(socket, ssl_info, fatal);
}
void WebSocketJob::OnError(const SocketStream* socket, int error) {
if (delegate_ && error != ERR_PROTOCOL_SWITCHED)
delegate_->OnError(socket, error);
}
void WebSocketJob::OnCreatedSpdyStream(int result) {
DCHECK(spdy_websocket_stream_.get());
DCHECK(socket_.get());
DCHECK_NE(ERR_IO_PENDING, result);
if (state_ == CLOSED) {
result = ERR_ABORTED;
} else if (result == OK) {
state_ = CONNECTING;
result = ERR_PROTOCOL_SWITCHED;
} else {
spdy_websocket_stream_.reset();
}
CompleteIO(result);
}
void WebSocketJob::OnSentSpdyHeaders(int result) {
DCHECK_NE(INITIALIZED, state_);
if (state_ != CONNECTING)
return;
if (delegate_)
delegate_->OnSentData(socket_, handshake_request_->original_length());
handshake_request_.reset();
}
int WebSocketJob::OnReceivedSpdyResponseHeader(
const SpdyHeaderBlock& headers, int status) {
DCHECK_NE(INITIALIZED, state_);
if (state_ != CONNECTING)
return status;
if (status != OK)
return status;
// TODO(toyoshim): Fallback to non-spdy connection?
handshake_response_->ParseResponseHeaderBlock(headers,
challenge_,
spdy_protocol_version_);
SaveCookiesAndNotifyHeaderComplete();
return OK;
}
void WebSocketJob::OnSentSpdyData(int amount_sent) {
DCHECK_NE(INITIALIZED, state_);
DCHECK_NE(CONNECTING, state_);
if (state_ == CLOSED)
return;
if (!spdy_websocket_stream_.get())
return;
OnSentData(socket_, amount_sent);
}
void WebSocketJob::OnReceivedSpdyData(const char* data, int length) {
DCHECK_NE(INITIALIZED, state_);
DCHECK_NE(CONNECTING, state_);
if (state_ == CLOSED)
return;
if (!spdy_websocket_stream_.get())
return;
OnReceivedData(socket_, data, length);
}
void WebSocketJob::OnCloseSpdyStream() {
spdy_websocket_stream_.reset();
OnClose(socket_);
}
bool WebSocketJob::SendHandshakeRequest(const char* data, int len) {
DCHECK_EQ(state_, CONNECTING);
if (started_to_send_handshake_request_)
return false;
if (!handshake_request_->ParseRequest(data, len))
return false;
// handshake message is completed.
handshake_response_->set_protocol_version(
handshake_request_->protocol_version());
AddCookieHeaderAndSend();
return true;
}
void WebSocketJob::AddCookieHeaderAndSend() {
bool allow = true;
if (delegate_ && !delegate_->CanGetCookies(socket_, GetURLForCookies()))
allow = false;
if (socket_ && delegate_ && state_ == CONNECTING) {
handshake_request_->RemoveHeaders(
kCookieHeaders, arraysize(kCookieHeaders));
if (allow && socket_->context()->cookie_store()) {
// Add cookies, including HttpOnly cookies.
CookieOptions cookie_options;
cookie_options.set_include_httponly();
socket_->context()->cookie_store()->GetCookiesWithOptionsAsync(
GetURLForCookies(), cookie_options,
base::Bind(&WebSocketJob::LoadCookieCallback,
weak_ptr_factory_.GetWeakPtr()));
} else {
DoSendData();
}
}
}
void WebSocketJob::LoadCookieCallback(const std::string& cookie) {
if (!cookie.empty())
handshake_request_->AppendHeaderIfMissing("Cookie", cookie);
DoSendData();
}
void WebSocketJob::DoSendData() {
if (spdy_websocket_stream_.get()) {
scoped_ptr<SpdyHeaderBlock> headers(new SpdyHeaderBlock);
handshake_request_->GetRequestHeaderBlock(
socket_->url(), headers.get(), &challenge_, spdy_protocol_version_);
spdy_websocket_stream_->SendRequest(headers.Pass());
} else {
const std::string& handshake_request =
handshake_request_->GetRawRequest();
handshake_request_sent_ = 0;
socket_->net_log()->AddEvent(
NetLog::TYPE_WEB_SOCKET_SEND_REQUEST_HEADERS,
base::Bind(&NetLogWebSocketHandshakeCallback, &handshake_request));
socket_->SendData(handshake_request.data(),
handshake_request.size());
}
// Just buffered in |handshake_request_|.
started_to_send_handshake_request_ = true;
}
void WebSocketJob::OnSentHandshakeRequest(
SocketStream* socket, int amount_sent) {
DCHECK_EQ(state_, CONNECTING);
handshake_request_sent_ += amount_sent;
DCHECK_LE(handshake_request_sent_, handshake_request_->raw_length());
if (handshake_request_sent_ >= handshake_request_->raw_length()) {
// handshake request has been sent.
// notify original size of handshake request to delegate.
if (delegate_)
delegate_->OnSentData(
socket,
handshake_request_->original_length());
handshake_request_.reset();
}
}
void WebSocketJob::OnReceivedHandshakeResponse(
SocketStream* socket, const char* data, int len) {
DCHECK_EQ(state_, CONNECTING);
if (handshake_response_->HasResponse()) {
// If we already has handshake response, received data should be frame
// data, not handshake message.
received_data_after_handshake_.insert(
received_data_after_handshake_.end(), data, data + len);
return;
}
size_t response_length = handshake_response_->ParseRawResponse(data, len);
if (!handshake_response_->HasResponse()) {
// not yet. we need more data.
return;
}
// handshake message is completed.
std::string raw_response = handshake_response_->GetRawResponse();
socket_->net_log()->AddEvent(
NetLog::TYPE_WEB_SOCKET_READ_RESPONSE_HEADERS,
base::Bind(&NetLogWebSocketHandshakeCallback, &raw_response));
if (len - response_length > 0) {
// If we received extra data, it should be frame data.
DCHECK(received_data_after_handshake_.empty());
received_data_after_handshake_.assign(data + response_length, data + len);
}
SaveCookiesAndNotifyHeaderComplete();
}
void WebSocketJob::SaveCookiesAndNotifyHeaderComplete() {
// handshake message is completed.
DCHECK(handshake_response_->HasResponse());
response_cookies_.clear();
response_cookies_save_index_ = 0;
handshake_response_->GetHeaders(
kSetCookieHeaders, arraysize(kSetCookieHeaders), &response_cookies_);
// Now, loop over the response cookies, and attempt to persist each.
SaveNextCookie();
}
void WebSocketJob::SaveNextCookie() {
if (response_cookies_save_index_ == response_cookies_.size()) {
response_cookies_.clear();
response_cookies_save_index_ = 0;
// Remove cookie headers, with malformed headers preserved.
// Actual handshake should be done in WebKit.
handshake_response_->RemoveHeaders(
kSetCookieHeaders, arraysize(kSetCookieHeaders));
std::string handshake_response = handshake_response_->GetResponse();
std::vector<char> received_data(handshake_response.begin(),
handshake_response.end());
received_data.insert(received_data.end(),
received_data_after_handshake_.begin(),
received_data_after_handshake_.end());
received_data_after_handshake_.clear();
state_ = OPEN;
DCHECK(!received_data.empty());
if (delegate_)
delegate_->OnReceivedData(
socket_, &received_data.front(), received_data.size());
handshake_response_.reset();
WebSocketThrottle::GetInstance()->RemoveFromQueue(this);
WebSocketThrottle::GetInstance()->WakeupSocketIfNecessary();
return;
}
bool allow = true;
CookieOptions options;
GURL url = GetURLForCookies();
std::string cookie = response_cookies_[response_cookies_save_index_];
if (delegate_ && !delegate_->CanSetCookie(socket_, url, cookie, &options))
allow = false;
if (socket_ && delegate_ && state_ == CONNECTING) {
response_cookies_save_index_++;
if (allow && socket_->context()->cookie_store()) {
options.set_include_httponly();
socket_->context()->cookie_store()->SetCookieWithOptionsAsync(
url, cookie, options,
base::Bind(&WebSocketJob::SaveCookieCallback,
weak_ptr_factory_.GetWeakPtr()));
} else {
SaveNextCookie();
}
}
}
void WebSocketJob::SaveCookieCallback(bool cookie_status) {
SaveNextCookie();
}
GURL WebSocketJob::GetURLForCookies() const {
GURL url = socket_->url();
std::string scheme = socket_->is_secure() ? "https" : "http";
url_canon::Replacements<char> replacements;
replacements.SetScheme(scheme.c_str(),
url_parse::Component(0, scheme.length()));
return url.ReplaceComponents(replacements);
}
const AddressList& WebSocketJob::address_list() const {
return addresses_;
}
int WebSocketJob::TrySpdyStream() {
if (!socket_.get())
return ERR_FAILED;
if (!websocket_over_spdy_enabled_)
return OK;
// Check if we have a SPDY session available.
HttpTransactionFactory* factory =
socket_->context()->http_transaction_factory();
if (!factory)
return OK;
scoped_refptr<HttpNetworkSession> session = factory->GetSession();
if (!session.get())
return OK;
SpdySessionPool* spdy_pool = session->spdy_session_pool();
const HostPortProxyPair pair(HostPortPair::FromURL(socket_->url()),
socket_->proxy_server());
if (!spdy_pool->HasSession(pair))
return OK;
// Forbid wss downgrade to SPDY without SSL.
// TODO(toyoshim): Does it realize the same policy with HTTP?
scoped_refptr<SpdySession> spdy_session =
spdy_pool->Get(pair, *socket_->net_log());
SSLInfo ssl_info;
bool was_npn_negotiated;
NextProto protocol_negotiated = kProtoUnknown;
bool use_ssl = spdy_session->GetSSLInfo(
&ssl_info, &was_npn_negotiated, &protocol_negotiated);
if (socket_->is_secure() && !use_ssl)
return OK;
// Create SpdyWebSocketStream.
spdy_protocol_version_ = spdy_session->GetProtocolVersion();
spdy_websocket_stream_.reset(new SpdyWebSocketStream(spdy_session, this));
int result = spdy_websocket_stream_->InitializeStream(
socket_->url(), MEDIUM, *socket_->net_log());
if (result == OK) {
OnConnected(socket_, kMaxPendingSendAllowed);
return ERR_PROTOCOL_SWITCHED;
}
if (result != ERR_IO_PENDING) {
spdy_websocket_stream_.reset();
return OK;
}
return ERR_IO_PENDING;
}
void WebSocketJob::SetWaiting() {
waiting_ = true;
}
bool WebSocketJob::IsWaiting() const {
return waiting_;
}
void WebSocketJob::Wakeup() {
if (!waiting_)
return;
waiting_ = false;
DCHECK(!callback_.is_null());
MessageLoopForIO::current()->PostTask(
FROM_HERE,
base::Bind(&WebSocketJob::RetryPendingIO,
weak_ptr_factory_.GetWeakPtr()));
}
void WebSocketJob::RetryPendingIO() {
int result = TrySpdyStream();
// In the case of ERR_IO_PENDING, CompleteIO() will be called from
// OnCreatedSpdyStream().
if (result != ERR_IO_PENDING)
CompleteIO(result);
}
void WebSocketJob::CompleteIO(int result) {
// |callback_| may be null if OnClose() or DetachDelegate() was called.
if (!callback_.is_null()) {
CompletionCallback callback = callback_;
callback_.Reset();
callback.Run(result);
Release(); // Balanced with OnStartOpenConnection().
}
}
bool WebSocketJob::SendDataInternal(const char* data, int length) {
if (spdy_websocket_stream_.get())
return ERR_IO_PENDING == spdy_websocket_stream_->SendData(data, length);
if (socket_.get())
return socket_->SendData(data, length);
return false;
}
void WebSocketJob::CloseInternal() {
if (spdy_websocket_stream_.get())
spdy_websocket_stream_->Close();
if (socket_.get())
socket_->Close();
}
void WebSocketJob::SendPending() {
if (current_send_buffer_)
return;
// Current buffer has been sent. Try next if any.
if (send_buffer_queue_.empty()) {
// No more data to send.
if (state_ == CLOSING)
CloseInternal();
return;
}
scoped_refptr<IOBufferWithSize> next_buffer = send_buffer_queue_.front();
send_buffer_queue_.pop_front();
current_send_buffer_ = new DrainableIOBuffer(next_buffer,
next_buffer->size());
SendDataInternal(current_send_buffer_->data(),
current_send_buffer_->BytesRemaining());
}
} // namespace net
|
/*
* Copyright (C) 2005-2017 by Centre National d'Etudes Spatiales (CNES)
*
* This file is licensed under MIT license:
*
* 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 "erssar/ErsSarPlatformPositionData.h"
namespace ossimplugins
{
ErsSarPlatformPositionData::ErsSarPlatformPositionData() : ErsSarRecord("pos_data_rec")
{
}
ErsSarPlatformPositionData::~ErsSarPlatformPositionData()
{
}
std::ostream& operator<<(std::ostream& os, const ErsSarPlatformPositionData& data)
{
os << "orbit_ele_desg:" << data._orbit_ele_desg << std::endl;
for (int i = 0; i < 6; i++)
{
os << "orbit_ele[" << i << "]:" << data._orbit_ele[i] << std::endl;
}
os << "ndata:" << data._ndata << std::endl;
os << "year:" << data._year << std::endl;
os << "month:" << data._month << std::endl;
os << "day:" << data._day << std::endl;
os << "gmt_day:" << data._gmt_day << std::endl;
os << "gmt_sec:" << data._gmt_sec << std::endl;
os << "data_int:" << data._data_int << std::endl;
os << "ref_coord:" << data._ref_coord << std::endl;
os << "hr_angle:" << data._hr_angle << std::endl;
os << "alt_poserr:" << data._alt_poserr << std::endl;
os << "crt_poserr:" << data._crt_poserr << std::endl;
os << "rad_poserr:" << data._rad_poserr << std::endl;
os << "alt_velerr:" << data._alt_velerr << std::endl;
os << "crt_velerr:" << data._crt_velerr << std::endl;
os << "rad_velerr:" << data._rad_velerr << std::endl;
for (int i = 0; i < 64; i++)
{
os << "pos_vect[" << i << "]:" << data._pos_vect[i] << std::endl;
}
return os;
}
std::istream& operator>>(std::istream& is, ErsSarPlatformPositionData& data)
{
char buf[1207];
buf[1206] = '\0';
is.read(buf, 32);
buf[32] = '\0';
data._orbit_ele_desg = buf;
for (int i = 0; i < 6; i++)
{
is.read(buf, 16);
buf[16] = '\0';
data._orbit_ele[i] = atof(buf);
}
is.read(buf, 4);
buf[4] = '\0';
data._ndata = atoi(buf);
is.read(buf, 4);
buf[4] = '\0';
data._year = atoi(buf);
is.read(buf, 4);
buf[4] = '\0';
data._month = atoi(buf);
is.read(buf, 4);
buf[4] = '\0';
data._day = atoi(buf);
is.read(buf, 4);
buf[4] = '\0';
data._gmt_day = atoi(buf);
is.read(buf, 22);
buf[22] = '\0';
data._gmt_sec = atof(buf);
is.read(buf, 22);
buf[22] = '\0';
data._data_int = atof(buf);
is.read(buf, 64);
buf[64] = '\0';
data._ref_coord = buf;
is.read(buf, 22);
buf[22] = '\0';
data._hr_angle = atof(buf);
is.read(buf, 16);
buf[16] = '\0';
data._alt_poserr = atof(buf);
is.read(buf, 16);
buf[16] = '\0';
data._crt_poserr = atof(buf);
is.read(buf, 16);
buf[16] = '\0';
data._rad_poserr = atof(buf);
is.read(buf, 16);
buf[16] = '\0';
data._alt_velerr = atof(buf);
is.read(buf, 16);
buf[16] = '\0';
data._crt_velerr = atof(buf);
is.read(buf, 16);
buf[16] = '\0';
data._rad_velerr = atof(buf);
for (int i = 0; i < data._ndata; i++)
{
is >> data._pos_vect[i];
}
return is;
}
ErsSarPlatformPositionData::ErsSarPlatformPositionData(const ErsSarPlatformPositionData& rhs):
ErsSarRecord(rhs)
{
_orbit_ele_desg = rhs._orbit_ele_desg;
for (int i = 0; i < 6; i++)
{
_orbit_ele[i] = rhs._orbit_ele[i];
}
_ndata = rhs._ndata;
_year = rhs._year;
_month = rhs._month;
_day = rhs._day;
_gmt_day = rhs._gmt_day;
_gmt_sec = rhs._gmt_sec;
_data_int = rhs._data_int;
_ref_coord = rhs._ref_coord;
_hr_angle = rhs._hr_angle;
_alt_poserr = rhs._alt_poserr;
_crt_poserr = rhs._crt_poserr;
_rad_poserr = rhs._rad_poserr;
_alt_velerr = rhs._alt_velerr;
_crt_velerr = rhs._crt_velerr;
_rad_velerr = rhs._rad_velerr;
for (int i = 0; i < 64; i++)
{
_pos_vect[i] = rhs._pos_vect[i];
}
}
ErsSarPlatformPositionData& ErsSarPlatformPositionData::operator=(const ErsSarPlatformPositionData& rhs)
{
_orbit_ele_desg = rhs._orbit_ele_desg;
for (int i = 0; i < 6; i++)
{
_orbit_ele[i] = rhs._orbit_ele[i];
}
_ndata = rhs._ndata;
_year = rhs._year;
_month = rhs._month;
_day = rhs._day;
_gmt_day = rhs._gmt_day;
_gmt_sec = rhs._gmt_sec;
_data_int = rhs._data_int;
_ref_coord = rhs._ref_coord;
_hr_angle = rhs._hr_angle;
_alt_poserr = rhs._alt_poserr;
_crt_poserr = rhs._crt_poserr;
_rad_poserr = rhs._rad_poserr;
_alt_velerr = rhs._alt_velerr;
_crt_velerr = rhs._crt_velerr;
_rad_velerr = rhs._rad_velerr;
for (int i = 0; i < 64; i++)
{
_pos_vect[i] = rhs._pos_vect[i];
}
return *this;
}
}
|
/****************************************************************************
* apps/graphics/nxwidgets/src/cglyphsliderhorizontal.cxx
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. The
* ASF licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
****************************************************************************
*
* Portions of this package derive from Woopsi (http://woopsi.org/) and
* portions are original efforts. It is difficult to determine at this
* point what parts are original efforts and which parts derive from Woopsi.
* However, in any event, the work of Antony Dzeryn will be acknowledged
* in most NxWidget files. Thanks Antony!
*
* Copyright (c) 2007-2011, Antony Dzeryn
* 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 names "Woopsi", "Simian Zombie" 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 Antony Dzeryn ``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 Antony Dzeryn 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.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#include <cstdint>
#include <cstdbool>
#include "graphics/nxwidgets/ibitmap.hxx"
#include "graphics/nxwidgets/cwidgetcontrol.hxx"
#include "graphics/nxwidgets/cglyphsliderhorizontal.hxx"
#include "graphics/nxwidgets/cglyphsliderhorizontalgrip.hxx"
#include "graphics/nxwidgets/cimage.hxx"
#include "graphics/nxwidgets/cgraphicsport.hxx"
/****************************************************************************
* Pre-Processor Definitions
****************************************************************************/
/****************************************************************************
* Method Implementations
****************************************************************************/
using namespace NXWidgets;
/**
* Constructor.
*
* @param control The widget control instance for the window.
* @param x The x coordinate of the slider, relative to its parent.
* @param y The y coordinate of the slider, relative to its parent.
* @param width The width of the slider.
* @param thickness The thickness of the slider.
* @param gripBitmap The slider grip image
* @param fillColor The color to use when filling the grip
* @param fill True: The grip will be filled with fillColor
*/
CGlyphSliderHorizontal::CGlyphSliderHorizontal(CWidgetControl *control,
nxgl_coord_t x, nxgl_coord_t y, nxgl_coord_t width,
nxgl_coord_t thickness, IBitmap *gripBitmap,
nxwidget_pixel_t fillColor, bool fill)
:CNxWidget(control, x, y, width, thickness, WIDGET_DRAGGABLE)
{
// Initialize state data
m_minimumValue = 0;
m_maximumValue = 0;
m_contentSize = 0;
m_value = 0;
m_minimumGripWidth = 10;
m_pageSize = 1;
m_fillColor = fillColor;
m_fill = fill;
m_barThickness = thickness;
// Correct the height of the widget. The widget height was initially set
// to the thickness of the grip. But the grip image is normally a little
// taller than the slider is thick.
//
// Do use the resize method here; we are not ready for the resize events.
nxgl_coord_t gripHeight = gripBitmap->getHeight() + 4;
if (gripHeight > thickness)
{
// Reset the widget height to the height of the grip image
m_rect.setHeight(gripHeight);
}
// Set widget attributes
m_flags.permeable = false;
m_flags.borderless = false;
m_flags.doubleClickable = false;
// Set the "gutter" width
CRect rect;
getClientRect(rect);
m_gutterWidth = rect.getWidth();
// Create the grip
m_grip = new CGlyphSliderHorizontalGrip(control, x, y,
gripBitmap->getWidth() + 4,
gripHeight, gripBitmap);
m_grip->setBorderless(true);
m_grip->addWidgetEventHandler(this);
addWidget(m_grip);
}
/**
* Set the value of the slider. This will reposition and redraw the grip.
*
* @param value The new value.
*/
void CGlyphSliderHorizontal::setValue(const int value)
{
setValueWithBitshift((int32_t)value << 16);
}
/**
* Set the value that of the slider. This will reposition and redraw
* the grip. The supplied value should be shifted left 16 places.
* This ensures greater accuracy than the standard setValue() method if
* the slider is being used as a scrollbar.
*
* @param value The new value.
*/
void CGlyphSliderHorizontal::setValueWithBitshift(const int32_t value)
{
CRect rect;
getClientRect(rect);
// Can the grip move?
if ((rect.getWidth() > m_grip->getWidth()) &&
(m_maximumValue != m_minimumValue))
{
int32_t newValue = value;
int32_t maxValue = getPhysicalMaximumValueWithBitshift();
// Limit to max/min values
if (newValue > maxValue)
{
newValue = maxValue;
}
if (newValue >> 16 < m_minimumValue)
{
newValue = m_minimumValue << 16;
}
uint32_t scrollRatio = newValue / m_contentSize;
int32_t newGripX = m_gutterWidth * scrollRatio;
newGripX += newGripX & 0x8000;
newGripX >>= 16;
newGripX += rect.getX();
m_grip->moveTo(newGripX, (rect.getHeight() - m_grip->getHeight()) >> 1);
// Update stored value if necessary
if (m_value != newValue)
{
m_value = newValue;
m_widgetEventHandlers->raiseValueChangeEvent();
}
}
}
/**
* Process events fired by the grip.
*
* @param e The event details.
*/
void CGlyphSliderHorizontal::handleDragEvent(const CWidgetEventArgs & e)
{
// Handle grip events
if (e.getSource() == m_grip && e.getSource() != NULL)
{
int32_t newValue = getGripValue() >> 16;
// Grip has moved - compare values and raise event if the
// value has changed. Compare using integer values rather
// than fixed-point.
if (m_value >> 16 != newValue)
{
m_value = newValue << 16;
m_widgetEventHandlers->raiseValueChangeEvent();
}
}
}
/**
* Get the smallest value that the slider can move through when
* dragged.
*
* @return The smallest value that the slider can move through when
* dragged.
*/
nxgl_coord_t CGlyphSliderHorizontal::getMinimumStep(void) const
{
// If the ratio of content to gutter is greater than or equal to one,
// the minimum step that the slider can represent will be that ratio.
uint32_t gutterRatio = m_contentSize << 16 / m_gutterWidth;
gutterRatio += gutterRatio & 0x8000;
gutterRatio >>= 16;
if (gutterRatio > 0)
{
return gutterRatio;
}
return 1;
}
/**
* Get the maximum possible value that the slider can represent. Useful when
* using the slider as a scrollbar, as the height of the grip prevents the full
* range of values being accessed (intentionally).
* The returned value is shifted left 16 places for more accuracy in fixed-point
* calculations.
*
* @return The maximum possible value that the slider can represent.
*/
int32_t CGlyphSliderHorizontal::getPhysicalMaximumValueWithBitshift(void) const
{
uint32_t maxX = m_gutterWidth - m_grip->getWidth();
uint32_t scrollRatio = (maxX << 16) / m_gutterWidth;
int32_t value = (scrollRatio * m_contentSize);
return value;
}
/**
* Get the value represented by the top of the grip.
* return The value represented by the top of the grip.
*/
const int32_t CGlyphSliderHorizontal::getGripValue(void) const
{
// Calculate the current value represented by the top of the grip
CRect rect;
getClientRect(rect);
uint32_t gripPos = ((m_grip->getX() - getX()) - rect.getX());
uint32_t scrollRatio = (gripPos << 16) / m_gutterWidth;
int32_t value = (scrollRatio * m_contentSize);
return value;
}
/**
* Draw the area of this widget that falls within the clipping region.
* Called by the redraw() function to draw all visible regions.
*
* @param port The CGraphicsPort to draw to.
* @see redraw()
*/
void CGlyphSliderHorizontal::drawContents(CGraphicsPort * port)
{
int halfGripWidth = m_grip->getWidth() >> 1;
int halfBar = m_barThickness >> 1;
int halfHeight = getHeight() >> 1;
int width;
nxwidget_pixel_t color;
// Fill in (erase) the region to the left and right of the fuel gauge
width =
m_grip->getX() > halfGripWidth ? halfGripWidth : m_grip->getX() - getX();
port->drawFilledRect(getX(), getY(), width, getHeight(),
getBackgroundColor());
// Fill in (erase) the region above the "fuel gauge"
port->drawFilledRect(getX(), getY(), getWidth(), halfHeight - halfBar,
getBackgroundColor());
// Fill in the bar area to the left of the grip
if (m_fill)
color = m_fillColor;
else
color = getBackgroundColor();
if (m_grip->getX() > halfGripWidth)
port->drawFilledRect(getX() + 1 + halfGripWidth,
getY() + halfHeight - halfBar + 1,
m_grip->getX() - getX() - halfGripWidth, m_barThickness - 2,
color);
// Fill in bar the area to the right of the grip
width = getWidth() - (m_grip->getX() - getX() + m_grip->getWidth()) - 1 -
halfGripWidth;
if (width > 0)
port->drawFilledRect(m_grip->getX() + m_grip->getWidth(),
getY() + halfHeight - halfBar + 1, width,
m_barThickness - 2, getBackgroundColor());
// Fill in (erase) the area to right of the bar
width = m_grip->getX() - getX() + m_grip->getWidth() <
getWidth() - halfGripWidth ? halfGripWidth : getWidth() - (m_grip->getX() -
getX() +
halfGripWidth);
if (width > 0)
port->drawFilledRect(getX() + getWidth() - halfGripWidth, getY(), width,
getHeight(), getBackgroundColor());
// Fill in (erase) the region below the "fuel gauge"
port->drawFilledRect(getX(), getY() + halfHeight + (m_barThickness - halfBar),
getWidth(), halfHeight - (m_barThickness - halfBar),
getBackgroundColor());
// Now redraw the grip
m_grip->enableDrawing();
m_grip->redraw();
}
/**
* Draw the area of this widget that falls within the clipping region.
* Called by the redraw() function to draw all visible regions.
*
* @param port The CGraphicsPort to draw to.
* @see redraw()
*/
void CGlyphSliderHorizontal::drawBorder(CGraphicsPort * port)
{
// Stop drawing if the widget indicates it should not have an outline
if (!isBorderless())
{
int y1, y2;
int x = getX();
int gripWidth = m_grip->getWidth();
int halfGripWidth = gripWidth >> 1;
int gripX = m_grip->getX();
int width;
nxwidget_pixel_t shine;
nxwidget_pixel_t shadow;
y1 = getY() + (getHeight() >> 1) - (m_barThickness >> 1);
y2 = getY() + (getHeight() >> 1) + m_barThickness -
(m_barThickness >> 1) - 1;
// To the Left of the grip. Only draw if the icon isn't covering the
// edge of the bar
width = gripX - x - halfGripWidth;
if (width > 0)
{
// If we aren't filling, then don't draw a "raised" bar
if (m_fill)
{
shine = getShineEdgeColor();
shadow = getShadowEdgeColor();
}
else
{
shadow = getShineEdgeColor();
shine = getShadowEdgeColor();
}
port->drawHorizLine(x + halfGripWidth, y1, width, shine);
port->drawHorizLine(x + halfGripWidth, y2, width, shadow);
}
// To the Right of the grip
// Only draw if the icon isn't covering the edge of the bar
width = getWidth() - (gripX - x + gripWidth) - 1 - halfGripWidth;
if (width > 0)
{
port->drawHorizLine(gripX + gripWidth, y1,
getWidth() - (gripX - x + gripWidth) - 1 -
halfGripWidth, getShadowEdgeColor());
port->drawHorizLine(gripX + gripWidth, y2,
getWidth() - (gripX - x + gripWidth) - 1 -
halfGripWidth, getShineEdgeColor());
}
// Left edge
if (gripX > x + halfGripWidth)
{
port->drawVertLine(x + halfGripWidth, y1, m_barThickness,
getShineEdgeColor());
}
// Right edge
if (gripX + gripWidth < x + getWidth() - 1 - halfGripWidth)
{
port->drawVertLine(x + getWidth() - 1 - halfGripWidth,
y1, m_barThickness, getShadowEdgeColor());
}
}
}
/**
* Resize the slider to the new dimensions.
*
* @param width The new width.
* @param height The new height.
*/
void CGlyphSliderHorizontal::onResize(nxgl_coord_t width, nxgl_coord_t height)
{
// Remember current values
int32_t oldValue = m_value;
bool events = raisesEvents();
// Disable event raising
setRaisesEvents(false);
// resizeGrip();
// Set back to current value
setValue(oldValue);
// Reset event raising
setRaisesEvents(events);
}
/**
* Moves the grip towards the mouse.
*
* @param x The x coordinate of the click.
* @param y The y coordinate of the click.
*/
void CGlyphSliderHorizontal::onClick(nxgl_coord_t x, nxgl_coord_t y)
{
// Which way should the grip move?
if (x > m_grip->getX())
{
// Move grip right
setValueWithBitshift(m_value + (m_pageSize << 16));
}
else
{
// Move grip left
setValueWithBitshift(m_value - (m_pageSize << 16));
}
redraw();
}
|
#include <catch2/catch.hpp>
#include <Engine/RadiumEngine.hpp>
#include <Engine/Scene/Component.hpp>
#include <Engine/Scene/Entity.hpp>
#include <Engine/Scene/EntityManager.hpp>
#include <Engine/Scene/SignalManager.hpp>
using namespace Ra::Engine::Scene;
class Foo
{
public:
Ra::Core::Utils::Index i {0};
void incr( const ItemEntry& /*entity*/ ) { ++i; }
void decr( const ItemEntry& /*entity*/ ) { --i; }
};
class Bar
{
public:
explicit Bar( Foo& f ) : m_f {f} {};
void operator()( const ItemEntry& entity ) { m_f.incr( entity ); }
private:
Foo& m_f;
};
class FooBarComponent : public Component
{
public:
using Component::Component;
void initialize() override {};
};
TEST_CASE( "Engine/Scene/SignalManager/ON", "[Engine][Engine/Scene][SignalManager][ON]" ) {
auto engine = Ra::Engine::RadiumEngine::createInstance();
engine->initialize();
SignalManager signalmanager;
signalmanager.setOn( true );
Foo entitytest;
Foo componenttest;
Foo renderobjecttest;
Foo eoftest;
auto entity = engine->getEntityManager()->createEntity( "test entity" );
SECTION( "Entities signals" ) {
ItemEntry item {entity};
auto& addNotifier = signalmanager.getEntityCreatedNotifier();
auto& delNotifier = signalmanager.getEntityDestroyedNotifier();
Bar bar {entitytest};
int ia = addNotifier.attach( bar );
int id = delNotifier.attachMember( &entitytest, &Foo::decr );
REQUIRE( entitytest.i == 0 );
signalmanager.fireEntityCreated( item );
REQUIRE( entitytest.i == 1 );
REQUIRE( componenttest.i == 0 );
REQUIRE( renderobjecttest.i == 0 );
REQUIRE( eoftest.i == 0 );
signalmanager.fireEntityDestroyed( item );
REQUIRE( entitytest.i == 0 );
REQUIRE( componenttest.i == 0 );
REQUIRE( renderobjecttest.i == 0 );
REQUIRE( eoftest.i == 0 );
addNotifier.detach( ia );
signalmanager.fireEntityCreated( item );
REQUIRE( entitytest.i == 0 );
REQUIRE( componenttest.i == 0 );
REQUIRE( renderobjecttest.i == 0 );
REQUIRE( eoftest.i == 0 );
delNotifier.detach( id );
signalmanager.fireEntityDestroyed( item );
REQUIRE( entitytest.i == 0 );
REQUIRE( componenttest.i == 0 );
REQUIRE( renderobjecttest.i == 0 );
REQUIRE( eoftest.i == 0 );
}
SECTION( "Components signals" ) {
auto component = new FooBarComponent( "test component", entity );
ItemEntry item {entity, component};
auto& addNotifier = signalmanager.getComponentCreatedNotifier();
auto& delNotifier = signalmanager.getComponentDestroyedNotifier();
auto bar = [&componenttest]( const ItemEntry& e ) { componenttest.incr( e ); };
int ia = addNotifier.attach( bar );
int id = delNotifier.attachMember( &componenttest, &Foo::decr );
REQUIRE( componenttest.i == 0 );
signalmanager.fireComponentAdded( item );
REQUIRE( componenttest.i == 1 );
REQUIRE( entitytest.i == 0 );
REQUIRE( renderobjecttest.i == 0 );
REQUIRE( eoftest.i == 0 );
signalmanager.fireComponentRemoved( item );
REQUIRE( componenttest.i == 0 );
REQUIRE( entitytest.i == 0 );
REQUIRE( renderobjecttest.i == 0 );
REQUIRE( eoftest.i == 0 );
addNotifier.detach( ia );
signalmanager.fireComponentAdded( item );
REQUIRE( componenttest.i == 0 );
REQUIRE( entitytest.i == 0 );
REQUIRE( renderobjecttest.i == 0 );
REQUIRE( eoftest.i == 0 );
delNotifier.detach( id );
signalmanager.fireComponentRemoved( item );
REQUIRE( componenttest.i == 0 );
REQUIRE( entitytest.i == 0 );
REQUIRE( renderobjecttest.i == 0 );
REQUIRE( eoftest.i == 0 );
}
SECTION( "RenderObjects signals" ) {
auto component = new FooBarComponent( "test component", entity );
ItemEntry item {entity, component, 1};
auto& addNotifier = signalmanager.getRenderObjectCreatedNotifier();
auto& delNotifier = signalmanager.getRenderObjectDestroyedNotifier();
int ia = addNotifier.attach(
[&renderobjecttest]( const ItemEntry& e ) { renderobjecttest.incr( e ); } );
int id = delNotifier.attachMember( &renderobjecttest, &Foo::decr );
REQUIRE( renderobjecttest.i == 0 );
signalmanager.fireRenderObjectAdded( item );
REQUIRE( renderobjecttest.i == 1 );
REQUIRE( componenttest.i == 0 );
REQUIRE( entitytest.i == 0 );
REQUIRE( eoftest.i == 0 );
signalmanager.fireRenderObjectRemoved( item );
REQUIRE( renderobjecttest.i == 0 );
REQUIRE( componenttest.i == 0 );
REQUIRE( entitytest.i == 0 );
REQUIRE( eoftest.i == 0 );
addNotifier.detach( ia );
signalmanager.fireRenderObjectAdded( item );
REQUIRE( renderobjecttest.i == 0 );
REQUIRE( componenttest.i == 0 );
REQUIRE( entitytest.i == 0 );
REQUIRE( eoftest.i == 0 );
delNotifier.detach( id );
signalmanager.fireRenderObjectRemoved( item );
REQUIRE( renderobjecttest.i == 0 );
REQUIRE( componenttest.i == 0 );
REQUIRE( entitytest.i == 0 );
REQUIRE( eoftest.i == 0 );
}
SECTION( "End of Frame signal" ) {
auto component = new FooBarComponent( "test component", entity );
// this one is just to check it compiles ... we can add some REQUIREs in a near futur.
auto& eofNotifier = signalmanager.getEndFrameNotifier();
ItemEntry item {entity, component, 1};
int ia = eofNotifier.attach( [&eoftest, item]() { eoftest.incr( item ); } );
REQUIRE( eoftest.i == 0 );
signalmanager.fireFrameEnded();
REQUIRE( eoftest.i == 1 );
signalmanager.fireFrameEnded();
REQUIRE( eoftest.i == 2 );
eofNotifier.detach( ia );
signalmanager.fireFrameEnded();
REQUIRE( eoftest.i == 2 );
}
engine->cleanup();
Ra::Engine::RadiumEngine::destroyInstance();
}
TEST_CASE( "Engine/Scene/SignalManager/OFF/", "[Engine][Engine/Scene][SignalManager][OFF]" ) {
auto engine = Ra::Engine::RadiumEngine::createInstance();
engine->initialize();
SignalManager signalmanager;
signalmanager.setOn( false );
auto entity = engine->getEntityManager()->createEntity( "test entity" );
Foo entitytest;
Foo componenttest;
Foo renderobjecttest;
Foo eoftest;
SECTION( "Entities signals" ) {
ItemEntry item {entity};
auto& addNotifier = signalmanager.getEntityCreatedNotifier();
auto& delNotifier = signalmanager.getEntityDestroyedNotifier();
Bar bar {entitytest};
addNotifier.attach( bar );
delNotifier.attachMember( &entitytest, &Foo::decr );
REQUIRE( entitytest.i == 0 );
signalmanager.fireEntityCreated( item );
REQUIRE( entitytest.i == 0 );
REQUIRE( componenttest.i == 0 );
REQUIRE( renderobjecttest.i == 0 );
REQUIRE( eoftest.i == 0 );
signalmanager.fireEntityDestroyed( item );
REQUIRE( entitytest.i == 0 );
REQUIRE( componenttest.i == 0 );
REQUIRE( renderobjecttest.i == 0 );
REQUIRE( eoftest.i == 0 );
}
SECTION( "Components signals" ) {
auto component = new FooBarComponent( "test component", entity );
ItemEntry item {entity, component};
auto& addNotifier = signalmanager.getComponentCreatedNotifier();
auto& delNotifier = signalmanager.getComponentDestroyedNotifier();
auto bar = [&componenttest]( const ItemEntry& e ) { componenttest.incr( e ); };
addNotifier.attach( bar );
delNotifier.attachMember( &componenttest, &Foo::decr );
REQUIRE( componenttest.i == 0 );
signalmanager.fireComponentAdded( item );
REQUIRE( componenttest.i == 0 );
REQUIRE( entitytest.i == 0 );
REQUIRE( renderobjecttest.i == 0 );
REQUIRE( eoftest.i == 0 );
signalmanager.fireComponentRemoved( item );
REQUIRE( componenttest.i == 0 );
REQUIRE( entitytest.i == 0 );
REQUIRE( renderobjecttest.i == 0 );
REQUIRE( eoftest.i == 0 );
}
SECTION( "RenderObjects signals" ) {
auto component = new FooBarComponent( "test component", entity );
ItemEntry item {entity, component, 1};
auto& addNotifier = signalmanager.getRenderObjectCreatedNotifier();
auto& delNotifier = signalmanager.getRenderObjectDestroyedNotifier();
addNotifier.attach(
[&renderobjecttest]( const ItemEntry& e ) { renderobjecttest.incr( e ); } );
delNotifier.attachMember( &renderobjecttest, &Foo::decr );
REQUIRE( renderobjecttest.i == 0 );
signalmanager.fireRenderObjectAdded( item );
REQUIRE( renderobjecttest.i == 0 );
REQUIRE( componenttest.i == 0 );
REQUIRE( entitytest.i == 0 );
REQUIRE( eoftest.i == 0 );
signalmanager.fireRenderObjectRemoved( item );
REQUIRE( renderobjecttest.i == 0 );
REQUIRE( componenttest.i == 0 );
REQUIRE( entitytest.i == 0 );
REQUIRE( eoftest.i == 0 );
}
SECTION( "End of Frame signal" ) {
auto component = new FooBarComponent( "test component", entity );
// this one is just to check it compiles ... we can add some REQUIREs in a near futur.
auto& eofNotifier = signalmanager.getEndFrameNotifier();
ItemEntry item {entity, component, 1};
eofNotifier.attach( [&eoftest, item]() { eoftest.incr( item ); } );
REQUIRE( eoftest.i == 0 );
signalmanager.fireFrameEnded();
REQUIRE( eoftest.i == 0 );
}
engine->cleanup();
Ra::Engine::RadiumEngine::destroyInstance();
}
|
// license:BSD-3-Clause
// copyright-holders:Barry Rodewald
/*
* cpc_rom.cpp
* Amstrad CPC mountable ROM image device
*
*/
#include "emu.h"
#include "cpc_rom.h"
DEFINE_DEVICE_TYPE(CPC_ROM, cpc_rom_device, "cpc_rom", "CPC ROM Box")
void cpc_exp_cards(device_slot_interface &device);
//**************************************************************************
// DEVICE CONFIG INTERFACE
//**************************************************************************
// device machine config
void cpc_rom_device::device_add_mconfig(machine_config &config)
{
CPC_ROMSLOT(config, m_rom[0], 0);
CPC_ROMSLOT(config, m_rom[1], 0);
CPC_ROMSLOT(config, m_rom[2], 0);
CPC_ROMSLOT(config, m_rom[3], 0);
CPC_ROMSLOT(config, m_rom[4], 0);
CPC_ROMSLOT(config, m_rom[5], 0);
CPC_ROMSLOT(config, m_rom[6], 0);
CPC_ROMSLOT(config, m_rom[7], 0);
// pass-through
cpc_expansion_slot_device &exp(CPC_EXPANSION_SLOT(config, "exp", DERIVED_CLOCK(1, 1), cpc_exp_cards, nullptr));
exp.irq_callback().set(DEVICE_SELF_OWNER, FUNC(cpc_expansion_slot_device::irq_w));
exp.nmi_callback().set(DEVICE_SELF_OWNER, FUNC(cpc_expansion_slot_device::nmi_w));
exp.romdis_callback().set(DEVICE_SELF_OWNER, FUNC(cpc_expansion_slot_device::romdis_w)); // ROMDIS
}
//**************************************************************************
// LIVE DEVICE
//**************************************************************************
cpc_rom_device::cpc_rom_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) :
device_t(mconfig, CPC_ROM, tag, owner, clock),
device_cpc_expansion_card_interface(mconfig, *this),
m_rom(*this, "rom%u", 1)
{
}
//-------------------------------------------------
// device_start - device-specific startup
//-------------------------------------------------
void cpc_rom_device::device_start()
{
}
//-------------------------------------------------
// device_reset - device-specific reset
//-------------------------------------------------
void cpc_rom_device::device_reset()
{
}
/*** ROM image device ***/
// device type definition
DEFINE_DEVICE_TYPE(CPC_ROMSLOT, cpc_rom_image_device, "cpc_rom_image", "CPC ROM image")
//-------------------------------------------------
// cpc_rom_image_device - constructor
//-------------------------------------------------
cpc_rom_image_device::cpc_rom_image_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock)
: device_t(mconfig, CPC_ROMSLOT, tag, owner, clock)
, device_image_interface(mconfig, *this)
, m_base(nullptr)
{
}
//-------------------------------------------------
// cpc_rom_image_device - destructor
//-------------------------------------------------
cpc_rom_image_device::~cpc_rom_image_device()
{
}
//-------------------------------------------------
// device_start - device-specific startup
//-------------------------------------------------
void cpc_rom_image_device::device_start()
{
m_base = nullptr;
}
/*-------------------------------------------------
DEVICE_IMAGE_LOAD( rom )
-------------------------------------------------*/
image_init_result cpc_rom_image_device::call_load()
{
device_image_interface* image = this;
uint64_t size = image->length();
m_base = std::make_unique<uint8_t[]>(16384);
if(size <= 16384)
{
image->fread(m_base,size);
}
else
{
image->fseek(size-16384,SEEK_SET);
image->fread(m_base,16384);
}
return image_init_result::PASS;
}
/*-------------------------------------------------
DEVICE_IMAGE_UNLOAD( rom )
-------------------------------------------------*/
void cpc_rom_image_device::call_unload()
{
m_base = nullptr;
}
|
#include "AITools.h"
using namespace SparCraft;
const Unit & AITools::GetClosestEnemyUnit(const GameState & state, const size_t & player, const size_t & unitIndex, bool checkCloaked)
{
const size_t enemyPlayer = state.getEnemy(player);
const Unit & myUnit = state.getUnit(player,unitIndex);
int minDist(1000000);
size_t minUnitInd(0);
size_t minUnitID(0);
Position currentPos = myUnit.currentPosition(state.getTime());
for (size_t u(0); u < state.numUnits(enemyPlayer); ++u)
{
const Unit & enemyUnit = state.getUnit(enemyPlayer, u);
if (checkCloaked&& enemyUnit.type().hasPermanentCloak())
{
bool invisible = true;
for (size_t detectorIndex(0); detectorIndex < state.numUnits(player); ++detectorIndex)
{
// unit reference
const Unit & detector = state.getUnit(player, detectorIndex);
if (detector.type().isDetector() && detector.canSeeTarget(enemyUnit, state.getTime()))
{
invisible = false;
break;
}
}
if (invisible)
{
continue;
}
}
int distSq = myUnit.getDistanceSqToUnit(enemyUnit, state.getTime());
if ((distSq < minDist))// || ((distSq == minDist) && (enemyUnit.getID() < minUnitID)))
{
minDist = distSq;
minUnitInd = u;
minUnitID = enemyUnit.getID();
}
else if ((distSq == minDist) && (enemyUnit.getID() < minUnitID))
{
minDist = distSq;
minUnitInd = u;
minUnitID = enemyUnit.getID();
}
}
return state.getUnit(enemyPlayer, minUnitInd);
}
const Unit & AITools::GetClosestOurUnit(const GameState & state, const size_t & player, const size_t & unitIndex)
{
const Unit & myUnit = state.getUnit(player,unitIndex);
size_t minDist(1000000);
size_t minUnitInd(0);
Position currentPos = myUnit.currentPosition(state.getTime());
for (size_t u(0); u < state.numUnits(player); ++u)
{
if (u == unitIndex)
{
continue;
}
//size_t distSq(myUnit.distSq(getUnit(enemyPlayer,u)));
size_t distSq = currentPos.getDistanceSq(state.getUnit(player, u).currentPosition(state.getTime()));
if (distSq < minDist)
{
minDist = distSq;
minUnitInd = u;
}
}
return state.getUnit(player, minUnitInd);
}
#define TABS(N) for (int i(0); i<N; ++i) { fprintf(stderr, "\t"); }
// print the state in a neat way
void AITools::StatePrint(const GameState & state, int indent)
{
TABS(indent);
fprintf(stderr, "State - Time: %d\n", state.getTime());
for (size_t p(0); p<Players::Num_Players; ++p)
{
for (size_t u(0); u < state.numUnits(p); ++u)
{
const Unit & unit = state.getUnit(p, u);
TABS(indent);
fprintf(stderr, " P%d %5d %5d (%3d, %3d) %s\n", unit.getPlayerID(), unit.currentHP(), (int)unit.firstTimeFree(), unit.x(), unit.y(), unit.name().c_str());
}
}
fprintf(stderr, "\n\n");
}
std::string AITools::StateToString(const GameState & state)
{
std::stringstream ss;
ss << "Time: " << state.getTime() << std::endl;
for (size_t p(0); p<Players::Num_Players; ++p)
{
for (size_t u(0); u < state.numUnits(p); ++u)
{
const Unit & unit = state.getUnit(p, u);
ss << " P" << (int)unit.getPlayerID() << " " << unit.currentHP() << " (" << unit.x() << ", " << unit.y() << ") " << unit.name() << std::endl;
}
}
ss << std::endl;
return ss.str();
}
std::string AITools::StateToStringCompact(const GameState & state)
{
std::stringstream ss;
for (size_t p(0); p<Players::Num_Players; ++p)
{
std::map<BWAPI::UnitType, size_t> typeCount;
for (size_t u(0); u < state.numUnits(p); ++u)
{
const Unit & unit = state.getUnit(p, u);
if (typeCount.find(unit.type()) != std::end(typeCount))
{
typeCount[unit.type()]++;
}
else
{
typeCount[unit.type()] = 1;
}
}
for (auto & kv : typeCount)
{
const BWAPI::UnitType & type = kv.first;
const size_t count = kv.second;
ss << "P" << (int)p << " " << count << " " << type.getName() << "\n";
}
}
return ss.str();
}
Position AITools::CalculatePlayerCenter(const GameState & state, const size_t & player)
{
Position center(0,0);
for (size_t u(0); u < state.numUnits(player); ++u)
{
const Position & pos = state.getUnit(player, u).currentPosition(state.getTime());
center.addPosition(pos);
}
center = Position((int)((double)center.x() / state.numUnits(player)), (int)((double)center.y() / state.numUnits(player)));
return center;
}
|
/* Code generated by IfcQuery EXPRESS generator, www.ifcquery.com */
#include <sstream>
#include <limits>
#include "ifcpp/model/AttributeObject.h"
#include "ifcpp/model/BuildingException.h"
#include "ifcpp/model/BuildingGuid.h"
#include "ifcpp/reader/ReaderUtil.h"
#include "ifcpp/writer/WriterUtil.h"
#include "ifcpp/IFC4/include/IfcAxis2Placement3D.h"
#include "ifcpp/IFC4/include/IfcDirection.h"
#include "ifcpp/IFC4/include/IfcExtrudedAreaSolidTapered.h"
#include "ifcpp/IFC4/include/IfcPositiveLengthMeasure.h"
#include "ifcpp/IFC4/include/IfcPresentationLayerAssignment.h"
#include "ifcpp/IFC4/include/IfcProfileDef.h"
#include "ifcpp/IFC4/include/IfcStyledItem.h"
// ENTITY IfcExtrudedAreaSolidTapered
IfcExtrudedAreaSolidTapered::IfcExtrudedAreaSolidTapered() {}
IfcExtrudedAreaSolidTapered::IfcExtrudedAreaSolidTapered( int id ) { m_entity_id = id; }
IfcExtrudedAreaSolidTapered::~IfcExtrudedAreaSolidTapered() {}
shared_ptr<BuildingObject> IfcExtrudedAreaSolidTapered::getDeepCopy( BuildingCopyOptions& options )
{
shared_ptr<IfcExtrudedAreaSolidTapered> copy_self( new IfcExtrudedAreaSolidTapered() );
if( m_SweptArea )
{
if( options.shallow_copy_IfcProfileDef ) { copy_self->m_SweptArea = m_SweptArea; }
else { copy_self->m_SweptArea = dynamic_pointer_cast<IfcProfileDef>( m_SweptArea->getDeepCopy(options) ); }
}
if( m_Position ) { copy_self->m_Position = dynamic_pointer_cast<IfcAxis2Placement3D>( m_Position->getDeepCopy(options) ); }
if( m_ExtrudedDirection ) { copy_self->m_ExtrudedDirection = dynamic_pointer_cast<IfcDirection>( m_ExtrudedDirection->getDeepCopy(options) ); }
if( m_Depth ) { copy_self->m_Depth = dynamic_pointer_cast<IfcPositiveLengthMeasure>( m_Depth->getDeepCopy(options) ); }
if( m_EndSweptArea )
{
if( options.shallow_copy_IfcProfileDef ) { copy_self->m_EndSweptArea = m_EndSweptArea; }
else { copy_self->m_EndSweptArea = dynamic_pointer_cast<IfcProfileDef>( m_EndSweptArea->getDeepCopy(options) ); }
}
return copy_self;
}
void IfcExtrudedAreaSolidTapered::getStepLine( std::stringstream& stream ) const
{
stream << "#" << m_entity_id << "= IFCEXTRUDEDAREASOLIDTAPERED" << "(";
if( m_SweptArea ) { stream << "#" << m_SweptArea->m_entity_id; } else { stream << "*"; }
stream << ",";
if( m_Position ) { stream << "#" << m_Position->m_entity_id; } else { stream << "*"; }
stream << ",";
if( m_ExtrudedDirection ) { stream << "#" << m_ExtrudedDirection->m_entity_id; } else { stream << "*"; }
stream << ",";
if( m_Depth ) { m_Depth->getStepParameter( stream ); } else { stream << "*"; }
stream << ",";
if( m_EndSweptArea ) { stream << "#" << m_EndSweptArea->m_entity_id; } else { stream << "$"; }
stream << ");";
}
void IfcExtrudedAreaSolidTapered::getStepParameter( std::stringstream& stream, bool ) const { stream << "#" << m_entity_id; }
const std::wstring IfcExtrudedAreaSolidTapered::toString() const { return L"IfcExtrudedAreaSolidTapered"; }
void IfcExtrudedAreaSolidTapered::readStepArguments( const std::vector<std::wstring>& args, const std::map<int,shared_ptr<BuildingEntity> >& map )
{
const size_t num_args = args.size();
if( num_args != 5 ){ std::stringstream err; err << "Wrong parameter count for entity IfcExtrudedAreaSolidTapered, expecting 5, having " << num_args << ". Entity ID: " << m_entity_id << std::endl; throw BuildingException( err.str().c_str() ); }
readEntityReference( args[0], m_SweptArea, map );
readEntityReference( args[1], m_Position, map );
readEntityReference( args[2], m_ExtrudedDirection, map );
m_Depth = IfcPositiveLengthMeasure::createObjectFromSTEP( args[3], map );
readEntityReference( args[4], m_EndSweptArea, map );
}
void IfcExtrudedAreaSolidTapered::getAttributes( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes )
{
IfcExtrudedAreaSolid::getAttributes( vec_attributes );
vec_attributes.push_back( std::make_pair( "EndSweptArea", m_EndSweptArea ) );
}
void IfcExtrudedAreaSolidTapered::getAttributesInverse( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes_inverse )
{
IfcExtrudedAreaSolid::getAttributesInverse( vec_attributes_inverse );
}
void IfcExtrudedAreaSolidTapered::setInverseCounterparts( shared_ptr<BuildingEntity> ptr_self_entity )
{
IfcExtrudedAreaSolid::setInverseCounterparts( ptr_self_entity );
}
void IfcExtrudedAreaSolidTapered::unlinkFromInverseCounterparts()
{
IfcExtrudedAreaSolid::unlinkFromInverseCounterparts();
}
|
/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkAlgorithmHelper.h"
//itk
#include <itkImageDuplicator.h>
// Mitk
#include <mitkImageAccessByItk.h>
#include <mitkPointSetMappingHelper.h>
// MatchPoint
#include <mapImageRegistrationAlgorithmInterface.h>
#include <mapRegistrationAlgorithmInterface.h>
#include <mapPointSetRegistrationAlgorithmInterface.h>
#include <mapDummyImageRegistrationAlgorithm.h>
#include <mapAlgorithmIdentificationInterface.h>
namespace mitk
{
MITKAlgorithmHelper::MITKAlgorithmHelper(map::algorithm::RegistrationAlgorithmBase* algorithm) :
m_AlgorithmBase(algorithm)
{
m_AllowImageCasting = true;
}
map::core::RegistrationBase::Pointer
MITKAlgorithmHelper::
GetRegistration() const
{
map::core::RegistrationBase::Pointer spResult;
unsigned int movingDim = m_AlgorithmBase->getMovingDimensions();
unsigned int targetDim = m_AlgorithmBase->getTargetDimensions();
if (movingDim != targetDim)
{
mapDefaultExceptionStaticMacro( <<
"Error, algorithm instance has unequal dimensionality and is therefore not supported in the current version of MITKAlgorithmHelper.");
}
if (movingDim > 3)
{
mapDefaultExceptionStaticMacro( <<
"Error, algorithm instance has a dimensionality larger than 3 and is therefore not supported in the current version of MITKAlgorithmHelper.");
}
typedef ::map::algorithm::facet::RegistrationAlgorithmInterface<2, 2> RegistrationAlg2D2DInterface;
typedef ::map::algorithm::facet::RegistrationAlgorithmInterface<3, 3> RegistrationAlg3D3DInterface;
RegistrationAlg2D2DInterface* pRegAlgorithm2D2D = dynamic_cast<RegistrationAlg2D2DInterface*>
(m_AlgorithmBase.GetPointer());
RegistrationAlg3D3DInterface* pRegAlgorithm3D3D = dynamic_cast<RegistrationAlg3D3DInterface*>
(m_AlgorithmBase.GetPointer());
if (pRegAlgorithm2D2D)
{
spResult = pRegAlgorithm2D2D->getRegistration();
}
if (pRegAlgorithm3D3D)
{
spResult = pRegAlgorithm3D3D->getRegistration();
}
return spResult;
}
mitk::MAPRegistrationWrapper::Pointer
MITKAlgorithmHelper::
GetMITKRegistrationWrapper() const
{
map::core::RegistrationBase::Pointer spInternalResult = GetRegistration();
mitk::MAPRegistrationWrapper::Pointer spResult = mitk::MAPRegistrationWrapper::New();
spResult->SetRegistration(spInternalResult);
return spResult;
};
static const mitk::Image* GetDataAsImage(const mitk::BaseData* data)
{
return dynamic_cast<const mitk::Image*>(data);
};
static const mitk::PointSet* GetDataAsPointSet(const mitk::BaseData* data)
{
return dynamic_cast<const mitk::PointSet*>(data);
};
bool
MITKAlgorithmHelper::
CheckData(const mitk::BaseData* moving, const mitk::BaseData* target, CheckError::Type& error) const
{
if (! m_AlgorithmBase)
{
mapDefaultExceptionStaticMacro( << "Error, cannot check data. Helper has no algorithm defined.");
}
if (! moving)
{
mapDefaultExceptionStaticMacro( << "Error, cannot check data. Moving data pointer is NULL.");
}
if (! target)
{
mapDefaultExceptionStaticMacro( << "Error, cannot check data. Target data pointer is NULL.");
}
bool result = false;
m_Error = CheckError::unsupportedDataType;
unsigned int movingDim = m_AlgorithmBase->getMovingDimensions();
unsigned int targetDim = m_AlgorithmBase->getTargetDimensions();
if (movingDim != targetDim)
{
m_Error = CheckError::wrongDimension;
}
else
{
//First check if data are point sets or images
if (GetDataAsPointSet(target) && GetDataAsPointSet(moving))
{
typedef ::map::core::continuous::Elements<3>::InternalPointSetType InternalDefaultPointSetType;
typedef ::map::algorithm::facet::PointSetRegistrationAlgorithmInterface<InternalDefaultPointSetType, InternalDefaultPointSetType>
PointSetRegInterface;
PointSetRegInterface* pPointSetInterface = dynamic_cast<PointSetRegInterface*>
(m_AlgorithmBase.GetPointer());
if (!pPointSetInterface)
{
result = false;
m_Error = CheckError::unsupportedDataType;
}
}
else if (GetDataAsImage(moving) && GetDataAsImage(target))
{
if (movingDim == 2)
{
AccessTwoImagesFixedDimensionByItk(GetDataAsImage(moving), GetDataAsImage(target), DoCheckImages,
2);
}
else if (movingDim == 3)
{
AccessTwoImagesFixedDimensionByItk(GetDataAsImage(moving), GetDataAsImage(target), DoCheckImages,
3);
}
else
{
m_Error = CheckError::wrongDimension;
}
if (m_Error == CheckError::none || (m_AllowImageCasting && m_Error == CheckError::onlyByCasting))
{
result = true;
}
}
}
error = m_Error;
return result;
};
void MITKAlgorithmHelper::SetAllowImageCasting(bool allowCasting)
{
this->m_AllowImageCasting = allowCasting;
};
bool MITKAlgorithmHelper::GetAllowImageCasting() const
{
return this->m_AllowImageCasting;
};
void MITKAlgorithmHelper::SetData(const mitk::BaseData* moving, const mitk::BaseData* target)
{
if (! m_AlgorithmBase)
{
mapDefaultExceptionStaticMacro( << "Error, cannot check data. Helper has no algorithm defined.");
}
if (! moving)
{
mapDefaultExceptionStaticMacro( << "Error, cannot check data. Moving data pointer is NULL.");
}
if (! target)
{
mapDefaultExceptionStaticMacro( << "Error, cannot check data. Target data pointer is NULL.");
}
unsigned int movingDim = m_AlgorithmBase->getMovingDimensions();
unsigned int targetDim = m_AlgorithmBase->getTargetDimensions();
if (movingDim != targetDim)
{
mapDefaultExceptionStaticMacro( <<
"Error, cannot set data. Current version of MITKAlgorithmHelper only supports images/point sets with same dimensionality.");
}
if (GetDataAsPointSet(target) && GetDataAsPointSet(moving))
{
typedef ::map::core::continuous::Elements<3>::InternalPointSetType InternalDefaultPointSetType;
typedef ::map::algorithm::facet::PointSetRegistrationAlgorithmInterface<InternalDefaultPointSetType, InternalDefaultPointSetType>
PointSetRegInterface;
PointSetRegInterface* pPointSetInterface = dynamic_cast<PointSetRegInterface*>
(m_AlgorithmBase.GetPointer());
pPointSetInterface->setMovingPointSet(mitk::PointSetMappingHelper::ConvertPointSetMITKtoMAP(
GetDataAsPointSet(moving)->GetPointSet()));
pPointSetInterface->setTargetPointSet(mitk::PointSetMappingHelper::ConvertPointSetMITKtoMAP(
GetDataAsPointSet(target)->GetPointSet()));
}
else if (GetDataAsImage(moving) && GetDataAsImage(target))
{
if (movingDim == 2)
{
AccessTwoImagesFixedDimensionByItk(GetDataAsImage(moving), GetDataAsImage(target), DoSetImages, 2);
}
else if (movingDim == 3)
{
AccessTwoImagesFixedDimensionByItk(GetDataAsImage(moving), GetDataAsImage(target), DoSetImages, 3);
}
}
};
template<typename TInImageType, typename TOutImageType>
typename TOutImageType::Pointer MITKAlgorithmHelper::CastImage(const TInImageType* input) const
{
typedef itk::CastImageFilter< TInImageType, TOutImageType > CastFilterType;
typename CastFilterType::Pointer spImageCaster = CastFilterType::New();
spImageCaster->SetInput(input);
typename TOutImageType::Pointer spImage = spImageCaster->GetOutput();
spImageCaster->Update();
return spImage;
}
template<typename TPixelType1, unsigned int VImageDimension1,
typename TPixelType2, unsigned int VImageDimension2>
void MITKAlgorithmHelper::DoSetImages(const itk::Image<TPixelType1, VImageDimension1>* moving,
const itk::Image<TPixelType2, VImageDimension2>* target)
{
typedef itk::Image<TPixelType1, VImageDimension1> MovingImageType;
typedef itk::Image<TPixelType2, VImageDimension2> TargetImageType;
typedef itk::Image<map::core::discrete::InternalPixelType, VImageDimension1>
InternalDefaultMovingImageType;
typedef itk::Image<map::core::discrete::InternalPixelType, VImageDimension2>
InternalDefaultTargetImageType;
typedef ::map::algorithm::facet::ImageRegistrationAlgorithmInterface<MovingImageType, TargetImageType>
ImageRegInterface;
typedef ::map::algorithm::facet::ImageRegistrationAlgorithmInterface<InternalDefaultMovingImageType, InternalDefaultTargetImageType>
DefaultImageRegInterface;
ImageRegInterface* pImageInterface = dynamic_cast<ImageRegInterface*>(m_AlgorithmBase.GetPointer());
DefaultImageRegInterface* pDefaultImageInterface = dynamic_cast<DefaultImageRegInterface*>
(m_AlgorithmBase.GetPointer());
if (pImageInterface)
{
//just set directly and you are done
/**@todo the duplication work arround is needed due to a insufficuence
in the AccessTwoImagesFixedDimensionByItk macro. The macro always cast
the passed image into non const (even if tha image was passed as const).
This behavior enforces the unnecessary use of an writeaccessor, which as a consequence
will lead to redundant access exceptions as long as the algorithm exists;
e.g. in the typical scenario with the MatchPoint Plugins*/
typedef itk::ImageDuplicator< MovingImageType > MovingDuplicatorType;
typedef itk::ImageDuplicator< TargetImageType > TargetDuplicatorType;
typename MovingDuplicatorType::Pointer mDuplicator = MovingDuplicatorType::New();
mDuplicator->SetInputImage(moving);
mDuplicator->Update();
typename TargetDuplicatorType::Pointer tDuplicator = TargetDuplicatorType::New();
tDuplicator->SetInputImage(target);
tDuplicator->Update();
typename MovingImageType::Pointer clonedMoving = mDuplicator->GetOutput();
typename TargetImageType::Pointer clonedTarget = tDuplicator->GetOutput();
pImageInterface->setTargetImage(clonedTarget);
pImageInterface->setMovingImage(clonedMoving);
}
else if (pDefaultImageInterface)
{
//you may convert it to the default image type and use it then
if (! m_AllowImageCasting)
{
mapDefaultExceptionStaticMacro( <<
"Error, cannot set images. MITKAlgorithmHelper has to convert them into MatchPoint default images, but is not allowed. Please reconfigure helper.");
}
typename InternalDefaultTargetImageType::Pointer spCastedTarget =
CastImage<TargetImageType, InternalDefaultTargetImageType>(target);
typename InternalDefaultMovingImageType::Pointer spCastedMoving =
CastImage<MovingImageType, InternalDefaultMovingImageType>(moving);
pDefaultImageInterface->setTargetImage(spCastedTarget);
pDefaultImageInterface->setMovingImage(spCastedMoving);
}
else
{
mapDefaultExceptionStaticMacro( << "Error, algorithm is not able to use the based images.");
}
}
template<typename TPixelType1, unsigned int VImageDimension1,
typename TPixelType2, unsigned int VImageDimension2>
void MITKAlgorithmHelper::DoCheckImages(const itk::Image<TPixelType1, VImageDimension1>* moving,
const itk::Image<TPixelType2, VImageDimension2>* target) const
{
typedef itk::Image<TPixelType1, VImageDimension1> MovingImageType;
typedef itk::Image<TPixelType2, VImageDimension2> TargetImageType;
typedef itk::Image<map::core::discrete::InternalPixelType, VImageDimension1>
InternalDefaultMovingImageType;
typedef itk::Image<map::core::discrete::InternalPixelType, VImageDimension2>
InternalDefaultTargetImageType;
typedef ::map::algorithm::facet::ImageRegistrationAlgorithmInterface<MovingImageType, TargetImageType>
ImageRegInterface;
typedef ::map::algorithm::facet::ImageRegistrationAlgorithmInterface<InternalDefaultMovingImageType, InternalDefaultTargetImageType>
DefaultImageRegInterface;
ImageRegInterface* pImageInterface = dynamic_cast<ImageRegInterface*>(m_AlgorithmBase.GetPointer());
DefaultImageRegInterface* pDefaultImageInterface = dynamic_cast<DefaultImageRegInterface*>
(m_AlgorithmBase.GetPointer());
if (pImageInterface)
{
//just set directly and you are done
m_Error = CheckError::none;
}
else if (pDefaultImageInterface)
{
//you may convert it to the default image type and use it then
m_Error = CheckError::onlyByCasting;
}
else
{
m_Error = CheckError::unsupportedDataType;
}
}
mapGenerateAlgorithmUIDPolicyMacro(DummyRegIDPolicy, "de.dkfz.dipp", "Identity", "1.0.0", "");
mitk::MAPRegistrationWrapper::Pointer GenerateIdentityRegistration3D()
{
typedef map::algorithm::DummyImageRegistrationAlgorithm<map::core::discrete::Elements<3>::InternalImageType, map::core::discrete::Elements<3>::InternalImageType, DummyRegIDPolicy>
DummyRegType;
DummyRegType::Pointer regAlg = DummyRegType::New();
mitk::MITKAlgorithmHelper helper(regAlg);
map::core::discrete::Elements<3>::InternalImageType::Pointer dummyImg =
map::core::discrete::Elements<3>::InternalImageType::New();
dummyImg->Allocate();
regAlg->setTargetImage(dummyImg);
regAlg->setMovingImage(dummyImg);
mitk::MAPRegistrationWrapper::Pointer dummyReg = mitk::MAPRegistrationWrapper::New();
dummyReg->SetRegistration(regAlg->getRegistration());
return dummyReg;
}
}
|
/**
******************************************************************************
* Xenia : Xbox 360 Emulator Research Project *
******************************************************************************
* Copyright 2013 Ben Vanik. All rights reserved. *
* Released under the BSD license - see LICENSE in the root for more details. *
******************************************************************************
*/
#include <alloy/backend/ivm/ivm_function.h>
#include <alloy/backend/ivm/ivm_stack.h>
#include <alloy/backend/tracing.h>
#include <alloy/runtime/runtime.h>
#include <alloy/runtime/thread_state.h>
using namespace alloy;
using namespace alloy::backend;
using namespace alloy::backend::ivm;
using namespace alloy::runtime;
IVMFunction::IVMFunction(FunctionInfo* symbol_info) :
register_count_(0), intcode_count_(0), intcodes_(0),
source_map_count_(0), source_map_(0),
Function(symbol_info) {
}
IVMFunction::~IVMFunction() {
xe_free(intcodes_);
xe_free(source_map_);
}
void IVMFunction::Setup(TranslationContext& ctx) {
register_count_ = ctx.register_count;
stack_size_ = ctx.stack_size;
intcode_count_ = ctx.intcode_count;
intcodes_ = (IntCode*)ctx.intcode_arena->CloneContents();
source_map_count_ = ctx.source_map_count;
source_map_ = (SourceMapEntry*)ctx.source_map_arena->CloneContents();
}
IntCode* IVMFunction::GetIntCodeAtSourceOffset(uint64_t offset) {
for (size_t n = 0; n < source_map_count_; n++) {
auto entry = &source_map_[n];
if (entry->source_offset == offset) {
return &intcodes_[entry->intcode_index];
}
}
return NULL;
}
int IVMFunction::AddBreakpointImpl(Breakpoint* breakpoint) {
auto i = GetIntCodeAtSourceOffset(breakpoint->address());
if (!i) {
return 1;
}
// TEMP breakpoints always overwrite normal ones.
if (!i->debug_flags ||
breakpoint->type() == Breakpoint::TEMP_TYPE) {
uint64_t breakpoint_ptr = (uint64_t)breakpoint;
i->src2_reg = (uint32_t)breakpoint_ptr;
i->src3_reg = (uint32_t)(breakpoint_ptr >> 32);
}
// Increment breakpoint counter.
++i->debug_flags;
return 0;
}
int IVMFunction::RemoveBreakpointImpl(Breakpoint* breakpoint) {
auto i = GetIntCodeAtSourceOffset(breakpoint->address());
if (!i) {
return 1;
}
// Decrement breakpoint counter.
--i->debug_flags;
i->src2_reg = i->src3_reg = 0;
// If there were other breakpoints, see what they were.
if (i->debug_flags) {
auto old_breakpoint = FindBreakpoint(breakpoint->address());
if (old_breakpoint) {
uint64_t breakpoint_ptr = (uint64_t)old_breakpoint;
i->src2_reg = (uint32_t)breakpoint_ptr;
i->src3_reg = (uint32_t)(breakpoint_ptr >> 32);
}
}
return 0;
}
void IVMFunction::OnBreakpointHit(ThreadState* thread_state, IntCode* i) {
uint64_t breakpoint_ptr = i->src2_reg | (uint64_t(i->src3_reg) << 32);
Breakpoint* breakpoint = (Breakpoint*)breakpoint_ptr;
// Notify debugger.
// The debugger may choose to wait (blocking us).
auto debugger = thread_state->runtime()->debugger();
debugger->OnBreakpointHit(thread_state, breakpoint);
}
#undef TRACE_SOURCE_OFFSET
int IVMFunction::CallImpl(ThreadState* thread_state, uint64_t return_address) {
// Setup register file on stack.
auto stack = (IVMStack*)thread_state->backend_data();
auto register_file = (Register*)stack->Alloc(register_count_);
auto local_stack = (uint8_t*)alloca(stack_size_);
Memory* memory = thread_state->memory();
IntCodeState ics;
ics.rf = register_file;
ics.locals = local_stack;
ics.context = (uint8_t*)thread_state->raw_context();
ics.membase = memory->membase();
ics.did_carry = 0;
ics.did_saturate = 0;
ics.access_callbacks = thread_state->runtime()->access_callbacks();
ics.thread_state = thread_state;
ics.return_address = return_address;
ics.call_return_address = 0;
volatile int* suspend_flag_address = thread_state->suspend_flag_address();
// TODO(benvanik): DID_CARRY -- need HIR to set a OPCODE_FLAG_SET_CARRY
// or something so the fns can set an ics flag.
#ifdef TRACE_SOURCE_OFFSET
size_t source_index = 0;
#endif
uint32_t ia = 0;
while (true) {
// Check suspend. We could do this only on certain instructions, if we
// wanted to speed things up.
if (*suspend_flag_address) {
thread_state->EnterSuspend();
}
#ifdef TRACE_SOURCE_OFFSET
uint64_t source_offset = -1;
if (source_index < this->source_map_count_ &&
this->source_map_[source_index].intcode_index <= ia) {
while (source_index + 1 < this->source_map_count_ &&
this->source_map_[source_index + 1].intcode_index <= ia) {
source_index++;
}
source_offset = this->source_map_[source_index].source_offset;
}
#endif
IntCode* i = &intcodes_[ia];
if (i->debug_flags) {
OnBreakpointHit(thread_state, i);
}
uint32_t new_ia = i->intcode_fn(ics, i);
if (new_ia == IA_NEXT) {
ia++;
} else if (new_ia == IA_RETURN) {
break;
} else {
ia = new_ia;
#ifdef TRACE_SOURCE_OFFSET
source_index = 0;
#endif
}
}
stack->Free(register_count_);
return 0;
}
|
// cmcstl2 - A concept-enabled C++ standard library
//
// Copyright Casey Carter 2015
//
// Use, modification and distribution is subject to 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)
//
// Project home: https://github.com/caseycarter/cmcstl2
//
#ifndef STL2_DETAIL_CONCEPTS_FUNCTION_HPP
#define STL2_DETAIL_CONCEPTS_FUNCTION_HPP
#include <stl2/type_traits.hpp>
#include <stl2/detail/fwd.hpp>
#include <stl2/detail/concepts/compare.hpp>
#include <stl2/detail/concepts/core.hpp>
#include <stl2/detail/concepts/object.hpp>
#include <stl2/detail/functional/invoke.hpp>
///////////////////////////////////////////////////////////////////////////
// invocable Concepts [concepts.lib.callables]
//
STL2_OPEN_NAMESPACE {
///////////////////////////////////////////////////////////////////////////
// invocable [concepts.lib.callables.callable]
//
template<class F, class... Args>
META_CONCEPT invocable =
requires(F&& f, Args&&... args) {
__stl2::invoke((F&&)f, (Args&&)args...);
};
///////////////////////////////////////////////////////////////////////////
// regular_invocable [concepts.lib.callables.regularcallable]
//
template<class F, class... Args>
META_CONCEPT regular_invocable = invocable<F, Args...>;
///////////////////////////////////////////////////////////////////////////
// predicate [concepts.lib.callables.predicate]
//
template<class F, class... Args>
META_CONCEPT predicate =
regular_invocable<F, Args...> && boolean<invoke_result_t<F, Args...>>;
///////////////////////////////////////////////////////////////////////////
// relation [concepts.lib.callables.relation]
//
template<class R, class T, class U>
META_CONCEPT relation =
predicate<R, T, T> &&
predicate<R, U, U> &&
predicate<R, T, U> &&
predicate<R, U, T> &&
common_reference_with<
const std::remove_reference_t<T>&,
const std::remove_reference_t<U>&> &&
predicate<
R,
common_reference_t<
const std::remove_reference_t<T>&,
const std::remove_reference_t<U>&>,
common_reference_t<
const std::remove_reference_t<T>&,
const std::remove_reference_t<U>&>>;
///////////////////////////////////////////////////////////////////////////
// strict_weak_order [concepts.lib.callables.strictweakorder]
//
template<class R, class T, class U>
META_CONCEPT strict_weak_order = relation<R, T, U>;
} STL2_CLOSE_NAMESPACE
#endif
|
// Boost.Units - A C++ library for zero-overhead dimensional analysis and
// unit/quantity manipulation and conversion
//
// Copyright (C) 2003-2008 Matthias Christian Schabel
// Copyright (C) 2008 Steven Watanabe
//
// 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)
/**
\file
\brief fail_scalar_quantity_sub.cpp
\details
Test subtraction of scalar and quantity.
Output:
@verbatim
@endverbatim
**/
#include <boost/units/quantity.hpp>
#include <boost/units/systems/si.hpp>
namespace bu = boost::units;
int main(int argc,char *argv[])
{
2.0 - 2.0 * bu::si::meters;
return 0;
}
|
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <string>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <sstream>
#include <complex>
#include <ctime>
#include <cassert>
#include <functional>
using namespace std;
typedef long long ll;
typedef vector<int> VI;
typedef pair<int,int> PII;
#define REP(i,s,t) for(int i=(s);i<(t);i++)
#define FILL(x,v) memset(x,v,sizeof(x))
const int INF = (int)1E9;
#define MAXN 1005
int N, M, x[MAXN];
int main() {
int T;
cin >> T;
while (T--) {
cin >> N >> M;
map<int,int> pairs;
REP(i,0,N) cin >> x[i];
REP(i,0,N) REP(j,i+1,N) pairs[x[i]+x[j]]++;
REP(i,0,M) {
int q;
cin >> q;
cout << pairs[q] << endl;
}
}
return 0;
}
|
//===--- ModuleDependencyScanner.cpp - Compute module dependencies --------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "swift/Basic/Platform.h"
#include "swift/Serialization/SerializedModuleLoader.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/DiagnosticSuppression.h"
#include "swift/AST/ModuleDependencies.h"
#include "swift/AST/SourceFile.h"
#include "swift/Basic/FileTypes.h"
#include "swift/Subsystems.h"
using namespace swift;
using llvm::ErrorOr;
namespace {
static Optional<StringRef>
computePrebuiltModulePathDefault(ASTContext &ctx,
StringRef interfacePath,
StringRef prebuiltCacheDir,
StringRef moduleName,
StringRef modulePath,
llvm::SmallString<256> &scratch) {
namespace path = llvm::sys::path;
StringRef sdkPath = ctx.SearchPathOpts.SDKPath;
auto &fs = *ctx.SourceMgr.getFileSystem();
// Check if the interface file comes from the SDK
if (sdkPath.empty() || !hasPrefix(path::begin(interfacePath),
path::end(interfacePath),
path::begin(sdkPath),
path::end(sdkPath)))
return None;
// Assemble the expected path: $PREBUILT_CACHE/Foo.swiftmodule or
// $PREBUILT_CACHE/Foo.swiftmodule/arch.swiftmodule. Note that there's no
// cache key here.
scratch = prebuiltCacheDir;
// FIXME: Would it be possible to only have architecture-specific names
// here? Then we could skip this check.
StringRef inParentDirName =
path::filename(path::parent_path(interfacePath));
if (path::extension(inParentDirName) == ".swiftmodule") {
assert(path::stem(inParentDirName) == moduleName);
path::append(scratch, inParentDirName);
}
path::append(scratch, path::filename(modulePath));
// If there isn't a file at this location, skip returning a path.
if (!fs.exists(scratch))
return None;
return scratch.str();
}
/// Hack to deal with build systems (including the Swift standard library, at
/// the time of this comment) that aren't yet using target-specific names for
/// multi-target swiftmodules, in case the prebuilt cache is.
static Optional<StringRef>
computeFallbackPrebuiltModulePath(ASTContext &ctx,
StringRef interfacePath,
StringRef prebuiltCacheDir,
StringRef moduleName,
StringRef modulePath,
llvm::SmallString<256> &scratch) {
namespace path = llvm::sys::path;
StringRef sdkPath = ctx.SearchPathOpts.SDKPath;
auto &fs = *ctx.SourceMgr.getFileSystem();
// Check if the interface file comes from the SDK
if (sdkPath.empty() || !hasPrefix(path::begin(interfacePath),
path::end(interfacePath),
path::begin(sdkPath),
path::end(sdkPath)))
return None;
// If the module isn't target-specific, there's no fallback path.
StringRef inParentDirName =
path::filename(path::parent_path(interfacePath));
if (path::extension(inParentDirName) != ".swiftmodule")
return None;
// If the interface is already using the target-specific name, there's
// nothing else to try.
auto normalizedTarget = getTargetSpecificModuleTriple(ctx.LangOpts.Target);
if (path::stem(modulePath) == normalizedTarget.str())
return None;
// Assemble the expected path:
// $PREBUILT_CACHE/Foo.swiftmodule/target.swiftmodule. Note that there's no
// cache key here.
scratch = prebuiltCacheDir;
path::append(scratch, inParentDirName);
path::append(scratch, normalizedTarget.str());
scratch += ".swiftmodule";
// If there isn't a file at this location, skip returning a path.
if (!fs.exists(scratch))
return None;
return scratch.str();
}
/// A module "loader" that looks for .swiftinterface and .swiftmodule files
/// for the purpose of determining dependencies, but does not attempt to
/// load the module files.
class ModuleDependencyScanner : public SerializedModuleLoaderBase {
/// The module we're scanning dependencies of.
Identifier moduleName;
/// Scan the given interface file to determine dependencies.
ErrorOr<ModuleDependencies> scanInterfaceFile(
Twine moduleInterfacePath);
InterfaceSubContextDelegate &astDelegate;
public:
Optional<ModuleDependencies> dependencies;
ModuleDependencyScanner(ASTContext &ctx, ModuleLoadingMode LoadMode,
Identifier moduleName,
InterfaceSubContextDelegate &astDelegate)
: SerializedModuleLoaderBase(ctx, nullptr, LoadMode,
/*IgnoreSwiftSourceInfoFile=*/true),
moduleName(moduleName), astDelegate(astDelegate) { }
virtual std::error_code findModuleFilesInDirectory(
AccessPathElem ModuleID,
const SerializedModuleBaseName &BaseName,
SmallVectorImpl<char> *ModuleInterfacePath,
std::unique_ptr<llvm::MemoryBuffer> *ModuleBuffer,
std::unique_ptr<llvm::MemoryBuffer> *ModuleDocBuffer,
std::unique_ptr<llvm::MemoryBuffer> *ModuleSourceInfoBuffer) override {
using namespace llvm::sys;
auto &fs = *Ctx.SourceMgr.getFileSystem();
// Compute the full path of the module we're looking for.
auto ModPath = BaseName.getName(file_types::TY_SwiftModuleFile);
if (LoadMode == ModuleLoadingMode::OnlySerialized) {
// If there is no module file, there's nothing we can do.
if (!fs.exists(ModPath))
return std::make_error_code(std::errc::no_such_file_or_directory);
// The module file will be loaded directly.
auto dependencies = scanModuleFile(ModPath);
if (dependencies) {
this->dependencies = std::move(dependencies.get());
return std::error_code();
}
return dependencies.getError();
}
// Check whether the .swiftinterface exists.
auto InPath = BaseName.getName(file_types::TY_SwiftModuleInterfaceFile);
if (!fs.exists(InPath))
return std::make_error_code(std::errc::no_such_file_or_directory);
auto dependencies = scanInterfaceFile(InPath);
if (dependencies) {
this->dependencies = std::move(dependencies.get());
return std::error_code();
}
return dependencies.getError();
}
virtual void collectVisibleTopLevelModuleNames(
SmallVectorImpl<Identifier> &names) const override {
llvm_unreachable("Not used");
}
};
}
Optional<StringRef>
swift::computePrebuiltModulePath(ASTContext &ctx,
StringRef interfacePath,
StringRef prebuiltCacheDir,
StringRef moduleName,
llvm::SmallString<256> &scratch) {
llvm::SmallString<64> modulePath = llvm::sys::path::filename(interfacePath);
llvm::sys::path::replace_extension(modulePath,
file_types::getExtension(file_types::TY_SwiftModuleFile));
auto defaultPath =
computePrebuiltModulePathDefault(ctx, interfacePath, prebuiltCacheDir,
moduleName, modulePath, scratch);
if (defaultPath.hasValue())
return defaultPath;
else
return computeFallbackPrebuiltModulePath(ctx, interfacePath,
prebuiltCacheDir,
moduleName,
modulePath,
scratch);
}
ErrorOr<ModuleDependencies> ModuleDependencyScanner::scanInterfaceFile(
Twine moduleInterfacePath) {
// Create a module filename.
// FIXME: Query the module interface loader to determine an appropriate
// name for the module, which includes an appropriate hash.
auto newExt = file_types::getExtension(file_types::TY_SwiftModuleFile);
llvm::SmallString<32> modulePath = moduleName.str();
llvm::sys::path::replace_extension(modulePath, newExt);
Optional<ModuleDependencies> Result;
std::error_code code;
auto hasError = astDelegate.runInSubContext(moduleName.str(),
moduleInterfacePath.str(),
StringRef(),
SourceLoc(),
[&](ASTContext &Ctx, ArrayRef<StringRef> Args,
ArrayRef<StringRef> PCMArgs, StringRef Hash) {
Result = ModuleDependencies::forSwiftInterface(modulePath.str().str(),
moduleInterfacePath.str(),
Args,
PCMArgs,
Hash);
// Open the interface file.
auto &fs = *Ctx.SourceMgr.getFileSystem();
auto interfaceBuf = fs.getBufferForFile(moduleInterfacePath);
if (!interfaceBuf) {
code = interfaceBuf.getError();
return true;
}
// Create a source file.
unsigned bufferID = Ctx.SourceMgr.addNewSourceBuffer(std::move(interfaceBuf.get()));
auto moduleDecl = ModuleDecl::create(moduleName, Ctx);
auto sourceFile = new (Ctx) SourceFile(
*moduleDecl, SourceFileKind::Interface, bufferID);
// Walk the source file to find the import declarations.
llvm::StringSet<> alreadyAddedModules;
Result->addModuleDependencies(*sourceFile, alreadyAddedModules);
return false;
});
if (hasError) {
return code;
}
return *Result;
}
Optional<ModuleDependencies> SerializedModuleLoaderBase::getModuleDependencies(
StringRef moduleName, ModuleDependenciesCache &cache,
InterfaceSubContextDelegate &delegate) {
// Check whether we've cached this result.
if (auto found = cache.findDependencies(
moduleName, ModuleDependenciesKind::Swift))
return found;
// Check whether there is a module with this name that we can import.
auto moduleId = Ctx.getIdentifier(moduleName);
ModuleDependencyScanner scanner(Ctx, LoadMode, moduleId, delegate);
if (!scanner.canImportModule({moduleId, SourceLoc()}))
return None;
// Record the dependencies.
cache.recordDependencies(moduleName, *scanner.dependencies,
ModuleDependenciesKind::Swift);
return std::move(scanner.dependencies);
}
|
#include "extensions/filters/http/jwt_authn/matcher.h"
#include "envoy/config/route/v3/route_components.pb.h"
#include "envoy/extensions/filters/http/jwt_authn/v3/config.pb.h"
#include "common/common/logger.h"
#include "common/common/matchers.h"
#include "common/common/regex.h"
#include "common/router/config_impl.h"
#include "absl/strings/match.h"
using envoy::config::route::v3::RouteMatch;
using envoy::extensions::filters::http::jwt_authn::v3::RequirementRule;
using Envoy::Router::ConfigUtility;
namespace Envoy {
namespace Extensions {
namespace HttpFilters {
namespace JwtAuthn {
namespace {
/**
* Perform a match against any HTTP header or pseudo-header.
*/
class BaseMatcherImpl : public Matcher, public Logger::Loggable<Logger::Id::jwt> {
public:
BaseMatcherImpl(const RequirementRule& rule)
: case_sensitive_(PROTOBUF_GET_WRAPPED_OR_DEFAULT(rule.match(), case_sensitive, true)),
config_headers_(Http::HeaderUtility::buildHeaderDataVector(rule.match().headers())) {
for (const auto& query_parameter : rule.match().query_parameters()) {
config_query_parameters_.push_back(
std::make_unique<Router::ConfigUtility::QueryParameterMatcher>(query_parameter));
}
}
// Check match for HeaderMatcher and QueryParameterMatcher
bool matchRoute(const Http::RequestHeaderMap& headers) const {
bool matches = true;
// TODO(potatop): matching on RouteMatch runtime is not implemented.
matches &= Http::HeaderUtility::matchHeaders(headers, config_headers_);
if (!config_query_parameters_.empty()) {
Http::Utility::QueryParams query_parameters =
Http::Utility::parseQueryString(headers.getPathValue());
matches &= ConfigUtility::matchQueryParams(query_parameters, config_query_parameters_);
}
return matches;
}
protected:
const bool case_sensitive_;
private:
std::vector<Http::HeaderUtility::HeaderDataPtr> config_headers_;
std::vector<Router::ConfigUtility::QueryParameterMatcherPtr> config_query_parameters_;
};
/**
* Perform a match against any path with prefix rule.
*/
class PrefixMatcherImpl : public BaseMatcherImpl {
public:
PrefixMatcherImpl(const RequirementRule& rule)
: BaseMatcherImpl(rule), prefix_(rule.match().prefix()),
path_matcher_(Matchers::PathMatcher::createPrefix(prefix_, !case_sensitive_)) {}
bool matches(const Http::RequestHeaderMap& headers) const override {
if (BaseMatcherImpl::matchRoute(headers) && path_matcher_->match(headers.getPathValue())) {
ENVOY_LOG(debug, "Prefix requirement '{}' matched.", prefix_);
return true;
}
return false;
}
private:
// prefix string
const std::string prefix_;
const Matchers::PathMatcherConstSharedPtr path_matcher_;
};
/**
* Perform a match against any path with a specific path rule.
*/
class PathMatcherImpl : public BaseMatcherImpl {
public:
PathMatcherImpl(const RequirementRule& rule)
: BaseMatcherImpl(rule), path_(rule.match().path()),
path_matcher_(Matchers::PathMatcher::createExact(path_, !case_sensitive_)) {}
bool matches(const Http::RequestHeaderMap& headers) const override {
if (BaseMatcherImpl::matchRoute(headers) && path_matcher_->match(headers.getPathValue())) {
ENVOY_LOG(debug, "Path requirement '{}' matched.", path_);
return true;
}
return false;
}
private:
// path string.
const std::string path_;
const Matchers::PathMatcherConstSharedPtr path_matcher_;
};
/**
* Perform a match against any path with a regex rule.
* TODO(mattklein123): This code needs dedup with RegexRouteEntryImpl.
*/
class RegexMatcherImpl : public BaseMatcherImpl {
public:
RegexMatcherImpl(const RequirementRule& rule) : BaseMatcherImpl(rule) {
// TODO(yangminzhu): Use PathMatcher once hidden_envoy_deprecated_regex is removed.
if (rule.match().path_specifier_case() ==
envoy::config::route::v3::RouteMatch::PathSpecifierCase::kHiddenEnvoyDeprecatedRegex) {
regex_ = Regex::Utility::parseStdRegexAsCompiledMatcher(
rule.match().hidden_envoy_deprecated_regex());
regex_str_ = rule.match().hidden_envoy_deprecated_regex();
} else {
ASSERT(rule.match().path_specifier_case() ==
envoy::config::route::v3::RouteMatch::PathSpecifierCase::kSafeRegex);
regex_ = Regex::Utility::parseRegex(rule.match().safe_regex());
regex_str_ = rule.match().safe_regex().regex();
}
}
bool matches(const Http::RequestHeaderMap& headers) const override {
if (BaseMatcherImpl::matchRoute(headers)) {
const Http::HeaderString& path = headers.Path()->value();
const absl::string_view query_string = Http::Utility::findQueryStringStart(path);
absl::string_view path_view = path.getStringView();
path_view.remove_suffix(query_string.length());
if (regex_->match(path_view)) {
ENVOY_LOG(debug, "Regex requirement '{}' matched.", regex_str_);
return true;
}
}
return false;
}
private:
Regex::CompiledMatcherPtr regex_;
// raw regex string, for logging.
std::string regex_str_;
};
} // namespace
MatcherConstPtr Matcher::create(const RequirementRule& rule) {
switch (rule.match().path_specifier_case()) {
case RouteMatch::PathSpecifierCase::kPrefix:
return std::make_unique<PrefixMatcherImpl>(rule);
case RouteMatch::PathSpecifierCase::kPath:
return std::make_unique<PathMatcherImpl>(rule);
case RouteMatch::PathSpecifierCase::kHiddenEnvoyDeprecatedRegex:
case RouteMatch::PathSpecifierCase::kSafeRegex:
return std::make_unique<RegexMatcherImpl>(rule);
case RouteMatch::PathSpecifierCase::kConnectMatcher:
// TODO: When CONNECT match support is implemented, remove the manual clean-up of CONNECT
// matching in the filter fuzzer implementation:
// //test/extensions/filters/http/common/fuzz/uber_per_filter.cc
NOT_IMPLEMENTED_GCOVR_EXCL_LINE;
// path specifier is required.
case RouteMatch::PathSpecifierCase::PATH_SPECIFIER_NOT_SET:
default:
NOT_REACHED_GCOVR_EXCL_LINE;
}
}
} // namespace JwtAuthn
} // namespace HttpFilters
} // namespace Extensions
} // namespace Envoy
|
////////////////////////////////////////////////////////////
//
// MIT License
//
// Copyright(c) 2017 Kurt Slagle - kurt_slagle@yahoo.com
//
// 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.
//
// The origin of this software must not be misrepresented; you must not claim
// that you wrote the original software.If you use this software in a product,
// an acknowledgment of the software used is required.
//
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
// Internal Headers
////////////////////////////////////////////////////////////
#include <SFUI/Include/Application/AppWindow.h>
////////////////////////////////////////////////////////////
// Dependency Headers
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
// Standard Library Headers
////////////////////////////////////////////////////////////
namespace sfui
{
AppWindow::AppWindow(Vec2i Size, const std::string &Title, sf::Uint32 style)
{
m_WindowSize = Size;
m_WindowTitle = Title;
m_WindowStyle = style;
}
AppWindow::~AppWindow()
{
}
void AppWindow::Launch()
{
m_Thread = std::thread([this]() { this->MainLoop(); });
return;
}
bool AppWindow::IsOpen()
{
return ( m_Window && m_Window->isOpen() );
}
bool AppWindow::IsModal()
{
return m_IsModal;
}
bool AppWindow::IsDone()
{
return m_MarkForCleanup;
}
void AppWindow::Close()
{
m_MarkForClose = true;
}
void AppWindow::Hide()
{
m_MarkForHide = true;
}
void AppWindow::Show()
{
m_MarkForHide = false;
}
void AppWindow::AddWidget(Widget::shared_ptr widget)
{
m_widgetQueue.push(widget);
}
void AppWindow::PostLaunch()
{
}
void AppWindow::MainLoop()
{
m_Window = std::make_shared<sf::RenderWindow>(sf::VideoMode(m_WindowSize.x, m_WindowSize.y), m_WindowTitle, m_WindowStyle);
m_Window->setVerticalSyncEnabled(true);
m_Widgets = std::make_shared<WidgetWindow>(*m_Window);
sf::Event event;
bool closed = false;
PostLaunch();
while (m_Window && m_Window->isOpen()) {
if (m_MarkForClose) {
closed = true;
break;
}
while (m_Window->pollEvent(event)) {
closed = ( event.type == sf::Event::Closed );
m_Widgets->HandleEvent(event);
}
if (closed) break;
Update();
Render();
QueryQueues();
}
std::cerr << "Popup closed. Marking for cleanup" << std::endl;
// Mark for cleanup and return from the main thread
m_MarkForCleanup = true;
m_Window.reset();
return;
}
void AppWindow::Update()
{
m_Widgets->Update();
}
void AppWindow::Render()
{
m_Window->setActive(true);
m_Window->clear(sf::Color(122, 122, 122));
m_Widgets->Render();
m_Window->display();
m_Window->setActive(false);
}
void AppWindow::QueryQueues()
{
Widget::shared_ptr widgetPtr = nullptr;
while (m_widgetQueue.try_pop(widgetPtr)) {
m_Widgets->Add(widgetPtr);
}
}
AppWindowHandle::AppWindowHandle(AppWindow *win)
: m_Handle(win)
{
}
AppWindowHandle::~AppWindowHandle()
{
/*if (m_Handle) {
m_Handle->Close();
m_Handle = nullptr;
}*/
}
void AppWindowHandle::Open()
{
if (m_Handle) {
m_Handle->Launch();
}
}
void AppWindowHandle::Close()
{
if (m_Handle) {
m_Handle->Close();
}
}
void AppWindowHandle::Hide()
{
if (m_Handle) {
m_Handle->Hide();
}
}
void AppWindowHandle::Show()
{
if (m_Handle) {
m_Handle->Show();
}
}
}
|
// ======================================================================
/*!
* \file NFmiArea.cpp
* \brief Implementation of class NFmiArea
*/
// ======================================================================
/*!
* \class NFmiArea
*
* Undocumented
*/
// ======================================================================
#include "NFmiArea.h"
#include "NFmiAreaFactory.h"
#include <boost/functional/hash.hpp>
// ----------------------------------------------------------------------
/*!
* \bug Turha argumentti konstruktorille
*/
// ----------------------------------------------------------------------
void NFmiArea::Init(bool /* fKeepWorldRect */) { CheckForPacificView(); }
// ----------------------------------------------------------------------
/*!
* \param newArea Undocumented
*/
// ----------------------------------------------------------------------
void NFmiArea::SetXYArea(const NFmiRect &newArea)
{
Place(newArea.TopLeft());
Size(newArea.Size());
Init();
}
static void FixPacificLongitude(NFmiPoint &lonLat)
{
if (lonLat.X() < 0)
{
NFmiLongitude lon(lonLat.X(), true);
lonLat.X(lon.Value());
}
}
#if 0
static void FixAtlanticLongitude(NFmiPoint &lonLat)
{
if(lonLat.X() > 180)
{
NFmiLongitude lon(lonLat.X(), false);
lonLat.X(lon.Value());
}
}
#endif
// ----------------------------------------------------------------------
/*!
* \param theArea Undocumented
*/
// ----------------------------------------------------------------------
const NFmiRect NFmiArea::XYArea(const NFmiArea *theArea) const
{
if (PacificView() && theArea->PacificView() == false)
{
NFmiPoint topLeftLatlon = theArea->ToLatLon(theArea->TopLeft());
::FixPacificLongitude(topLeftLatlon);
NFmiPoint bottomRightLatlon = theArea->ToLatLon(theArea->BottomRight());
::FixPacificLongitude(bottomRightLatlon);
NFmiPoint topLeft(ToXY(topLeftLatlon));
NFmiPoint bottomRight(ToXY(bottomRightLatlon));
NFmiRect rect(topLeft, bottomRight);
return rect;
}
else if (PacificView() == false && theArea->PacificView())
{
std::unique_ptr<NFmiArea> pacificAreaFromThis(DoForcePacificFix());
NFmiPoint topLeft(pacificAreaFromThis->ToXY(theArea->ToLatLon(theArea->TopLeft())));
NFmiPoint bottomRight(pacificAreaFromThis->ToXY(theArea->ToLatLon(theArea->BottomRight())));
NFmiRect rect(topLeft, bottomRight);
return rect;
}
else
{
NFmiPoint topLeft(ToXY(theArea->ToLatLon(theArea->TopLeft())));
NFmiPoint bottomRight(ToXY(theArea->ToLatLon(theArea->BottomRight())));
NFmiRect rect(topLeft, bottomRight);
return rect;
}
}
// ----------------------------------------------------------------------
/*!
* \param file Undocumented
* \return Undocumented
*/
// ----------------------------------------------------------------------
std::ostream &NFmiArea::Write(std::ostream &file) const
{
file << itsXYRectArea;
return file;
}
// ----------------------------------------------------------------------
/*!
* \param file Undocumented
* \return Undocumented
*/
// ----------------------------------------------------------------------
std::istream &NFmiArea::Read(std::istream &file)
{
file >> itsXYRectArea;
return file;
}
// ----------------------------------------------------------------------
/*!
* \return Undocumented
*/
// ----------------------------------------------------------------------
const NFmiPoint NFmiArea::WorldXYSize() const { return WorldRect().Size(); }
// ----------------------------------------------------------------------
/*!
* \return Undocumented
*/
// ----------------------------------------------------------------------
const NFmiPoint NFmiArea::WorldXYPlace() const { return WorldRect().Place(); }
// ----------------------------------------------------------------------
/*!
* \return Undocumented
*/
// ----------------------------------------------------------------------
double NFmiArea::WorldXYWidth() const { return WorldRect().Width(); }
// ----------------------------------------------------------------------
/*!
* \return Undocumented
*/
// ----------------------------------------------------------------------
double NFmiArea::WorldXYHeight() const { return WorldRect().Height(); }
// ----------------------------------------------------------------------
/*!
* \return Undocumented
*/
// ----------------------------------------------------------------------
double NFmiArea::WorldXYAspectRatio() const { return WorldXYWidth() / WorldXYHeight(); }
// ----------------------------------------------------------------------
/*!
* Creates a new area from the current one by altering the corner points only.
* Previously this method required the new area to be inside the original
* one, but I failed to see the point in restricing the functionality - Mika
*
* \param theBottomLeftLatLon Undocumented
* \param theTopRightLatLon Undocumented
* \return Undocumented
*
* \todo Should return an boost::shared_ptr
* \todo Remove the unnecessary cast in the last return statement
*/
// ----------------------------------------------------------------------
NFmiArea *NFmiArea::CreateNewArea(const NFmiPoint &theBottomLeftLatLon,
const NFmiPoint &theTopRightLatLon) const
{
return NewArea(theBottomLeftLatLon, theTopRightLatLon);
}
// ----------------------------------------------------------------------
/*!
*
* Creates a new sub-area inside the current "mother" area.
* The new area is defined by the input local rectangle 'theRect'
*
* \note
* - the input rectangle defines a local XY coordinate area only, NOT the metric
* XY world rectangle
* - the sub-area MUST fit completely inside the current local area
* - the sub-area gets all the projection-specific properties but its dimensions
* from its "mother" area. For example, the orientation stays the same.
*
* \param theRect Undocumented
* \return Undocumented
*/
// ----------------------------------------------------------------------
NFmiArea *NFmiArea::CreateNewArea(const NFmiRect &theRect) const
{
NFmiPoint newBottomLeftXY = theRect.BottomLeft();
NFmiPoint newTopRightXY = theRect.TopRight();
NFmiPoint newBottomLeftLatLon = ToLatLon(newBottomLeftXY);
NFmiPoint newTopRightLatLon = ToLatLon(newTopRightXY);
NFmiArea *newArea = NewArea(newBottomLeftLatLon, newTopRightLatLon);
return newArea;
}
// ----------------------------------------------------------------------
/*!
* Creates a new area with its aspect ratio defined by the input parameters
*
* \note
* - the new area MAY OR MAY NOT completely reside inside the current local area
* - the new area gets all the projection-specific properties but its dimensions
* from its "mother" area. For example, the orientation stays the same.
*
* \param theNewAspectRatioXperY Undocumented
* \param theFixedPoint Undocumented
* \param fShrinkArea Undocumented
* \return Undocumented
*/
// ----------------------------------------------------------------------
NFmiArea *NFmiArea::CreateNewArea(double theNewAspectRatioXperY,
FmiDirection theFixedPoint,
bool fShrinkArea)
{
double originalAspectRatio = WorldXYAspectRatio();
bool keepWidth;
if (fShrinkArea)
{
// The new area will be "shrunk" to completely fit inside the current area
if ((theNewAspectRatioXperY < originalAspectRatio))
keepWidth = false; // Maintain height, compute width
else
keepWidth = true; // Maintain width, compute height
}
else
{
// The new area will in part grow out of the current area
if ((theNewAspectRatioXperY < originalAspectRatio))
keepWidth = true; // Maintain width, compute height
else
keepWidth = false; // Maintain height, compute width
}
// Create copy of the original "world rectangle" to be freely modified
NFmiRect newWorldRect = WorldRect();
// REDIMENSIONING OF THE WORLD RECTANGLE
//----------------------------------------
if (!newWorldRect.AdjustAspectRatio(theNewAspectRatioXperY, keepWidth, theFixedPoint))
return nullptr;
// Create a new area with the new aspect ratio
NFmiArea *newArea =
NewArea(WorldXYToLatLon(newWorldRect.TopLeft()), WorldXYToLatLon(newWorldRect.BottomRight()));
// Return the re-dimensioned copy of the original area
return newArea;
}
// ----------------------------------------------------------------------
/*!
* Creates a new sub-area inside the current "mother" area.
* The new area is defined by the input metric rectangle 'theWorldRect'
*
* \note
* - the input rectangle defines a metric XY world rectangle
* - the sub-area MUST fit completely inside the current local area
* - the sub-area gets all the projection-specific properties but its dimensions
* - from its "mother" area. For example, the orientation stays the same.
*
* \param theWorldRect
* \return Undocumented
*/
// ----------------------------------------------------------------------
NFmiArea *NFmiArea::CreateNewAreaByWorldRect(const NFmiRect &theWorldRect)
{
NFmiPoint newBottomLeftXY = theWorldRect.BottomLeft();
NFmiPoint newTopRightXY = theWorldRect.TopRight();
NFmiPoint newBottomLeftLatLon = WorldXYToLatLon(newBottomLeftXY);
NFmiPoint newTopRightLatLon = WorldXYToLatLon(newTopRightXY);
if (!IsInside(newBottomLeftLatLon) || !IsInside(newTopRightLatLon)) return nullptr;
auto *newArea = static_cast<NFmiArea *>(NewArea(newBottomLeftLatLon, newTopRightLatLon));
if (!IsInside(*newArea)) return nullptr;
return newArea;
}
// ----------------------------------------------------------------------
/*!
* Measured from the input point, returns the azimuth angle between
* the true geodetic north direction and the "up" Y-axis of the map
* area rectangle. Azimuth angle runs 0..360 degrees clockwise, with
* north zero degrees.
*
* \param theLatLonPoint Undocumented
* \param theLatitudeEpsilon Undocumented
* \return Undocumented
*/
// ----------------------------------------------------------------------
const NFmiAngle NFmiArea::TrueNorthAzimuth(const NFmiPoint &theLatLonPoint,
double theLatitudeEpsilon) const
{
using namespace std;
NFmiPoint xyWorldPoint = LatLonToWorldXY(theLatLonPoint);
NFmiPoint latLonIncr =
NFmiPoint(0., theLatitudeEpsilon); // Arbitrary small latitude increment in degrees
// Move up toward geo-north along the meridian of the input point
NFmiPoint xyDistanceAlongMeridian = LatLonToWorldXY(theLatLonPoint + latLonIncr) - xyWorldPoint;
// Get the angle between 'xyDistanceAlongMeridian.X()' and map "up" direction Y-axis
if (xyDistanceAlongMeridian.Y() == 0.)
return xyDistanceAlongMeridian.X() > 0.
? NFmiAngle(90.)
: NFmiAngle(
270.); // Azimuth is exactly east 90 degrees or west 270 degrees, respectively
return NFmiAngle(FmiDeg(atan2(xyDistanceAlongMeridian.X(), xyDistanceAlongMeridian.Y())));
}
// ----------------------------------------------------------------------
/*!
* \brief Return center latlon coordinate
*/
// ----------------------------------------------------------------------
const NFmiPoint NFmiArea::CenterLatLon() const
{
NFmiPoint bl = BottomLeft();
NFmiPoint tr = TopRight();
NFmiPoint center(0.5 * (bl.X() + tr.X()), 0.5 * (bl.Y() + tr.Y()));
return ToLatLon(center);
}
bool NFmiArea::IsPacificLongitude(double theLongitude)
{
if (theLongitude > 180 && theLongitude <= 360)
return true;
else
return false;
}
void NFmiArea::CheckForPacificView()
{
fPacificView = NFmiArea::IsPacificView(BottomLeftLatLon(), TopRightLatLon());
}
// 1. Tarkistaa kattaako annetut pisteet Atlantic vai Pacific alueen
// 2. Jos Pacific, korjaa longitudet pacific:eiksi
// 3. Palauta originaali/korjatut pisteet pair:issa
PacificPointFixerData NFmiArea::PacificPointFixer(const NFmiPoint &theBottomLeftLatlon,
const NFmiPoint &theTopRightLatlon)
{
bool usePacificView = NFmiArea::IsPacificView(theBottomLeftLatlon, theTopRightLatlon);
if (usePacificView)
{
NFmiPoint bottomLeftLatLon = theBottomLeftLatlon;
NFmiPoint topRightLatLon = theTopRightLatlon;
NFmiAreaFactory::DoPossiblePacificFix(bottomLeftLatLon, topRightLatLon, usePacificView);
return PacificPointFixerData(bottomLeftLatLon, topRightLatLon, usePacificView);
}
else
return PacificPointFixerData(theBottomLeftLatlon, theTopRightLatlon, usePacificView);
}
bool NFmiArea::IsPacificView(const NFmiPoint &bottomleftLatlon, const NFmiPoint &toprightLatlon)
{
// Obvious case
if (bottomleftLatlon.X() >= 0 && toprightLatlon.X() < 0) return true;
// 0...360 coordinate system is used
if (IsPacificLongitude(bottomleftLatlon.X()) || IsPacificLongitude(toprightLatlon.X()))
return true;
return false;
}
double NFmiArea::FixLongitude(double theLon) const
{
if (!fPacificView)
{
if (theLon > 180.00000001) // Tämä ei voi olla tasan 180, koska SmartMet maailman rajaviivat
// shapessa (maps\\shapes\\ne_10m_admin_0_countries) ja niiden
// piirto imagine-kirjastolla menee jossain kohdissa sekaisin
// reunoilla, koska siellä on käytetty vähän yli 180-pituuspiirin
// meneviä arvoja Tyynenmeren 180 asteen pituuspiirin reunoilla
return theLon - 360;
else
return theLon;
}
else if (theLon < 0)
return theLon + 360;
else
return theLon;
}
NFmiArea *NFmiArea::DoPossiblePacificFix() const
{
// On olemassa pari erikoistapausta, mitkä halutaan eri areoissa korjata, että alueet toimisivat
// paremmin newbase:ssa.
if (fPacificView)
{
bool usedPacificViewState = fPacificView;
NFmiPoint bottomleft = BottomLeftLatLon();
NFmiPoint topright = TopRightLatLon();
bool createNewArea =
NFmiAreaFactory::DoPossiblePacificFix(bottomleft, topright, usedPacificViewState);
if (createNewArea)
{
NFmiArea *newArea = NewArea(bottomleft, topright);
if (newArea)
{
newArea->PacificView(usedPacificViewState);
return newArea;
}
}
}
return nullptr;
}
NFmiArea *NFmiArea::DoForcePacificFix() const
{
// Joskus on pakko muuttaa atlantic-area pacific tyyppiseksi vaikka väkisin
if (!fPacificView)
{
NFmiPoint bottomleftLatlon = BottomLeftLatLon();
::FixPacificLongitude(bottomleftLatlon);
NFmiPoint toprightLatlon = TopRightLatLon();
::FixPacificLongitude(toprightLatlon);
NFmiArea *newArea = NewArea(bottomleftLatlon, toprightLatlon, false);
if (newArea)
{
newArea->PacificView(true);
return newArea;
}
}
return nullptr;
}
// ----------------------------------------------------------------------
/*!
* \brief Return hash value for the base NFmiArea components
*/
// ----------------------------------------------------------------------
std::size_t NFmiArea::HashValue() const
{
std::size_t hash = itsXYRectArea.HashValue();
boost::hash_combine(hash, boost::hash_value(fPacificView));
boost::hash_combine(hash, boost::hash_value(WKT()));
return hash;
}
|
// ObjectTalk Scripting Language
// Copyright (c) 1993-2022 Johan A. Goossens. All rights reserved.
//
// This work is licensed under the terms of the MIT license.
// For a copy, see <https://opensource.org/licenses/MIT>.
//
// Include files
//
#include <iostream>
#include <argparse/argparse.hpp>
#include "ot.h"
#if defined(INCLUDE_GUI)
#include "guimodule.h"
#include "workspace.h"
#endif
//
// ObjectTalk interpreter main function
//
int main(int argc, char* argv[]) {
// parse all command line parameters
argparse::ArgumentParser program(argv[0], "0.2");
program.add_argument("-e", "--editor")
.help("edit code instead of running it")
.default_value(false)
.implicit_value(true);
program.add_argument("scripts")
.help("scripts to execute")
.remaining();
try {
program.parse_args(argc, argv);
} catch (const std::runtime_error& err) {
std::cerr << err.what() << std::endl;
std::cerr << program;
exit(EXIT_FAILURE);
}
// get all the script file names
std::vector<std::string> scripts;
try {
scripts = program.get<std::vector<std::string>>("scripts");
} catch (std::logic_error& e) {
}
try {
// initialize libuv
OtLibUv::init(argc, argv);
#if defined(INCLUDE_GUI)
// initialize GUI module (if available on this platform)
OtGuiModuleInit();
#endif
// where any script specified?
if (scripts.size() == 0) {
// no, do we start the editor?
#if defined(INCLUDE_GUI)
OtWorkspaceClass::instance()->init();
OtWorkspaceClass::instance()->newFile();
OtWorkspaceClass::instance()->run();
#else
std::cerr << "No scripts specified" << std::endl << std::endl;
std::cerr << program;
exit(EXIT_FAILURE);
#endif
} else {
#if defined(INCLUDE_GUI)
if (program["--editor"] == true) {
OtWorkspaceClass::instance()->init();
for (auto& script : scripts) {
OtWorkspaceClass::instance()->openFile(script);
}
OtWorkspaceClass::instance()->run();
} else {
#endif
// run each script
for (auto& script : scripts) {
OtModuleClass::create(script);
}
#if defined(INCLUDE_GUI)
}
#endif
}
// cleanup
OtLibUv::end();
} catch (const OtException& e) {
// handle all failures
std::wcerr << "Error: " << e.what() << std::endl;
exit(EXIT_FAILURE);
}
return 0;
}
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE758_Undefined_Behavior__long_new_use_13.cpp
Label Definition File: CWE758_Undefined_Behavior.new.label.xml
Template File: point-flaw-13.tmpl.cpp
*/
/*
* @description
* CWE: 758 Undefined Behavior
* Sinks: new_use
* GoodSink: Initialize then use data
* BadSink : Use data
* Flow Variant: 13 Control flow: if(GLOBAL_CONST_FIVE==5) and if(GLOBAL_CONST_FIVE!=5)
*
* */
#include "std_testcase.h"
namespace CWE758_Undefined_Behavior__long_new_use_13
{
#ifndef OMITBAD
void bad()
{
if(GLOBAL_CONST_FIVE==5)
{
{
long * pointer = new long;
long data = *pointer; /* FLAW: the value pointed to by pointer is undefined */
delete pointer;
printLongLine(data);
}
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* good1() uses if(GLOBAL_CONST_FIVE!=5) instead of if(GLOBAL_CONST_FIVE==5) */
static void good1()
{
if(GLOBAL_CONST_FIVE!=5)
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
printLine("Benign, fixed string");
}
else
{
{
long data;
data = 5L;
long * pointer = new long;
*pointer = data; /* FIX: Assign a value to the thing pointed to by pointer */
{
long data = *pointer;
printLongLine(data);
}
delete pointer;
}
}
}
/* good2() reverses the bodies in the if statement */
static void good2()
{
if(GLOBAL_CONST_FIVE==5)
{
{
long data;
data = 5L;
long * pointer = new long;
*pointer = data; /* FIX: Assign a value to the thing pointed to by pointer */
{
long data = *pointer;
printLongLine(data);
}
delete pointer;
}
}
}
void good()
{
good1();
good2();
}
#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 CWE758_Undefined_Behavior__long_new_use_13; /* 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
|
//------------------------------------------------------------------------------
// kheap.cpp
// Kernel heap
//------------------------------------------------------------------------------
// This file is part of the GenOS (Genesis Operating System) project.
// The latest version can be found at http://code.google.com/p/genos
//------------------------------------------------------------------------------
// Copyright (c) 2008-2010 Cedric Rousseau
// All rights reserved.
//
// This source code is released under the new BSD License.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions, and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions, and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// 3. The name of the author may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//------------------------------------------------------------------------------
#include "kheap.h"
#include <kernel.h>
#include <pagemanager.h>
#include <screen.h>
using namespace GenOS;
#define KHEAP_HEAD_USED 'KHHU'
#define KHEAP_FOOT_USED 'KHFU'
#define KHEAP_HEAD_FREE 'KHHF'
#define KHEAP_FOOT_FREE 'KHFF'
//static Kheap* g_heap = NULL;
static intptr __cdecl _new(uint32 size)
{
//return g_heap->Allocate(size, 0);
return Kernel::Kheap()->Allocate(size, 0);
}
static void __cdecl _delete(intptr p)
{
//return g_heap->Free(p);
return Kernel::Kheap()->Free(p);
}
static intptr __cdecl panic_new(uint32)
{
PANIC("Cannot use operator_new because KHeap is not initialized");
}
static void __cdecl panic_delete(intptr)
{
PANIC("Cannot use operator_new because KHeap is not initialized");
}
static intptr (__cdecl *bridge_new)(uint32 size) = panic_new;
static void (__cdecl *bridge_delete)(intptr p) = panic_delete;
intptr __cdecl ::operator new(uint32 size)
{
return bridge_new(size);
}
intptr __cdecl operator new[](uint32 size)
{
return bridge_new(size);
}
void __cdecl ::operator delete(intptr p)
{
return bridge_delete(p);
}
void __cdecl operator delete[](intptr p)
{
return bridge_delete(p);
}
vaddr Kheap::CreateEntryPlacement(vaddr& placement, size_t size, bool free)
{
const uint32 entrySize = sizeof(EntryHead) + size + sizeof(EntryFoot);
EntryHead* head = (EntryHead*)placement;
EntryFoot* foot = (EntryFoot*)((uint32)placement + entrySize - sizeof(EntryHead));
head->Magic = free ? KHEAP_HEAD_FREE : KHEAP_HEAD_USED;
foot->Magic = free ? KHEAP_FOOT_FREE : KHEAP_FOOT_USED;
head->Size = entrySize;
foot->Size = entrySize;
placement = (vaddr)((uint32)placement + entrySize);
return (vaddr)((uint32)head + sizeof(EntryHead));
}
int32 Kheap::CompareEntries(const intptr& a, const intptr& b)
{
EntryHead* aa = (EntryHead*)a;
EntryHead* bb = (EntryHead*)b;
if(aa->Size == bb->Size) return 0;
if(aa->Size < bb->Size) return -1;
return 1;
}
//Kheap::Kheap(vaddr heapStart, size_t heapSize, size_t heapMaxSize, SortedArray<intptr>* freeList)
//: _heapStart(heapStart)
//, _heapSize(heapSize)
//, _heapMaxSize(heapMaxSize)
//, _freeList(freeList)
//{
//}
Kheap::Kheap()
{
}
Kheap::~Kheap()
{
}
void Kheap::Initialize(vaddr heapStart, size_t heapMaxSize)
{
_heapStart = heapStart;
_heapSize = 0x1000;
_heapMaxSize = heapMaxSize;
// Allocate an initial page
if( !Kernel::PageManager()->Map(0, _heapStart, PageManager::Page::Writable))
{
PANIC("Cannot map the first page");
}
vaddr placement = _heapStart;
_freeList = (SortedArray<intptr>*)CreateEntryPlacement(placement, sizeof(SortedArray<intptr>), false);
intptr* freeListBuffer = (intptr*)CreateEntryPlacement(placement, 4*sizeof(intptr), false);
_freeList = new (_freeList) SortedArray<intptr>(freeListBuffer, 4, CompareEntries);
intptr freeEntry = placement;
const size_t initialMemory = 0x1000;
const size_t freeMemory = initialMemory - 4*(sizeof(EntryHead)+sizeof(EntryFoot)) - sizeof(Kheap) - sizeof(SortedArray<intptr>) - 4*sizeof(intptr);
CreateEntryPlacement(placement, freeMemory, true);
_freeList->Insert(freeEntry);
bridge_new = _new;
bridge_delete = _delete;
}
intptr Kheap::Allocate(size_t size, uint32 alignment)
{
// Must be null or a power of two
ASSERT( !alignment || (alignment & (alignment-1))==0 );
//Screen::cout << "initial size: " << size;
//
size_t actualSize = (((size + 3) / 4) * 4);
actualSize += sizeof(EntryHead) + sizeof(EntryFoot);
//Screen::cout << " - actual size: " << actualSize;
// Find the first free zone that fits the request
//Screen::cout << " - freeList size: " << _freeList->Size();
for(size_t index=0; index<_freeList->Size(); index++)
{
EntryHead* head = (EntryHead*)_freeList->At(index);
//Screen::cout << " - currentHead: " << head;
if(alignment)
{
// TODO
}
else if(head->Size >= actualSize)
{
//Screen::cout << " - index: " << index;
_freeList->Remove(index);
// Check that there is enough room after this entry to create another one.
// Else, increase the actualSize.
if (head->Size - actualSize < sizeof(EntryHead) + sizeof(EntryFoot))
{
actualSize = head->Size;
//Screen::cout << " - new actualSize: " << actualSize;
}
else
{
EntryHead* newFreeHead = (EntryHead*)((uint32)head + actualSize);
EntryFoot* newFreeFoot = (EntryFoot*)((uint32)head + head->Size - sizeof(EntryFoot));
newFreeHead->Magic = KHEAP_HEAD_FREE;
newFreeHead->Size = head->Size - actualSize;
newFreeFoot->Magic = KHEAP_FOOT_FREE;
newFreeFoot->Size = head->Size - actualSize;
_freeList->Insert(newFreeHead);
}
EntryHead* newBlockHead = head;
EntryFoot* newBlockFoot = (EntryFoot*)((uint32)head + actualSize - sizeof(EntryFoot));
newBlockHead->Magic = KHEAP_HEAD_USED;
newBlockHead->Size = actualSize;
newBlockFoot->Magic = KHEAP_FOOT_USED;
newBlockFoot->Size = actualSize;
//Screen::cout << Screen::endl;
return (intptr)((uint32)head + sizeof(EntryHead));
}
}
// Not enough memory... Map new pages
//Screen::cout << " - not enough memory." << Screen::endl;
uint32 neededPages = (actualSize + 0x0FFF) / 0x1000;
//Screen::cout << "Adding 0x" << neededPages << " pages" << Screen::endl;
vaddr newStart = (vaddr)((uint32)_heapStart + _heapSize);
vaddr currentAddress = newStart;
for (uint32 i = 0; i< neededPages; i++ )
{
if( !Kernel::PageManager()->Map(0, currentAddress, PageManager::Page::Writable))
{
PANIC("Cannot map the page");
}
currentAddress = (vaddr)((uint32)currentAddress + 0x1000);
}
//Screen::cout << " from 0x" << newStart << " to 0x" << currentAddress << Screen::endl;
_heapSize += neededPages * 0x1000;
// Create a new entry and free it to merge new space with the current one.
EntryHead* newSpaceHead = (EntryHead*)newStart;
newSpaceHead->Magic = KHEAP_HEAD_USED;
newSpaceHead->Size = neededPages * 0x1000;
//Screen::cout << " - Merging ";
Free((intptr)((uint32)newStart + sizeof(EntryHead)));
//Screen::cout << " - Allocating ";
return Allocate(size, alignment);
// TODO
//Screen::cout << "ERROR" << Screen::endl;
//Kernel::Hang();
//return NULL;
}
void Kheap::Free(intptr data)
{
EntryHead* head = (EntryHead*)((uint32)data - sizeof(EntryHead));
EntryFoot* foot = (EntryFoot*)((uint32)head + head->Size - sizeof(EntryFoot));
head->Magic = KHEAP_HEAD_FREE;
foot->Magic = KHEAP_FOOT_FREE;
//Screen::cout << " head " << head << ", foot " << foot << Screen::endl;
// Merge previous entry
EntryHead* previousHead = NULL;
EntryFoot* previousFoot = (EntryFoot*)((uint32)head - sizeof(EntryFoot));
if(previousFoot->Magic == KHEAP_FOOT_FREE)
{
previousHead = (EntryHead*)((uint32)head - previousFoot->Size);
ASSERT(previousHead->Magic == KHEAP_HEAD_FREE);
//Screen::cout << " previousHead " << previousHead << ", previousFoot " << previousFoot << Screen::endl;
// Save index
uint32 index = _freeList->Find(previousHead);
// Change the size in header and footer
previousHead->Size += head->Size;
foot->Size = previousHead->Size;
// Set new header
head = previousHead;
// Update the free list
_freeList->Remove(index);
_freeList->Insert(previousHead);
}
// Merge next entry
EntryHead* nextHead = (EntryHead*)((uint32)head + head->Size);
if(((uint32)nextHead < (uint32)_heapStart + _heapSize) && (nextHead->Magic == KHEAP_HEAD_FREE))
{
EntryFoot* nextFoot = (EntryFoot*)((uint32)nextHead + nextHead->Size - sizeof(EntryFoot));
ASSERT(nextFoot->Magic == KHEAP_FOOT_FREE);
//Screen::cout << " nextHead " << nextHead << ", nextFoot " << nextFoot << Screen::endl;
// Change the size in header and footer
head->Size += nextHead->Size;
nextFoot->Size = head->Size;
// Update the free list
_freeList->Remove(nextHead);
}
if (head != previousHead)
{
_freeList->Insert(head);
}
}
|
// Copyright (c) 2019 PaddlePaddle 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 "lite/kernels/arm/pool_compute.h"
#include <string>
#include <vector>
#include "lite/backends/arm/math/funcs.h"
#include "lite/core/op_registry.h"
#include "lite/core/type_system.h"
namespace paddle {
namespace lite {
namespace kernels {
namespace arm {
void PoolCompute::PrepareForRun() {
auto& ctx = this->ctx_->template As<ARMContext>();
}
void PoolCompute::Run() {
auto& param = Param<operators::PoolParam>();
auto& in_dims = param.x->dims();
auto& out_dims = param.output->dims();
const float* din = param.x->data<float>();
float* dout = param.output->mutable_data<float>();
std::vector<int>& ksize = param.ksize;
std::vector<int>& strides = param.strides;
std::vector<int>& paddings = *param.paddings;
std::string& pooling_type = param.pooling_type;
bool exclusive = param.exclusive;
bool adaptive = param.adaptive;
bool ceil_mode = param.ceil_mode;
bool use_quantizer = param.use_quantizer;
std::string& data_format = param.data_format;
bool pads_less =
(paddings[0] == paddings[2]) && (paddings[1] < 2) && (paddings[3] < 2);
bool pads_equal = (paddings[0] == paddings[2]) &&
(paddings[0] == paddings[1]) &&
(paddings[2] == paddings[3]);
bool kps_equal =
(ksize[0] == ksize[1]) && (strides[0] == strides[1]) && pads_less;
bool global_pooling = (paddings[0] == 0) && (ksize[0] == in_dims[2]) &&
(ksize[1] == in_dims[3]) && kps_equal && pads_equal;
global_pooling = param.global_pooling || global_pooling;
if (global_pooling) {
for (size_t i = 0; i < ksize.size(); ++i) {
paddings[2 * i] = 0;
paddings[2 * i + 1] = 0;
ksize[i] = static_cast<int>(in_dims[i + 2]);
}
if (pooling_type == "max") {
lite::arm::math::pooling_global_max(din,
dout,
out_dims[0],
out_dims[1],
out_dims[2],
out_dims[3],
in_dims[1],
in_dims[2],
in_dims[3]);
return;
} else if (pooling_type == "avg") {
lite::arm::math::pooling_global_avg(din,
dout,
out_dims[0],
out_dims[1],
out_dims[2],
out_dims[3],
in_dims[1],
in_dims[2],
in_dims[3]);
return;
}
} else {
if (ksize[0] == 1 && strides[0] == 2 && paddings[0] == 0 && kps_equal) {
auto& ctx = this->ctx_->template As<ARMContext>();
if (pooling_type == "max") {
lite::arm::math::pooling1x1s2p0_max(din,
dout,
out_dims[0],
out_dims[1],
out_dims[2],
out_dims[3],
in_dims[1],
in_dims[2],
in_dims[3],
paddings[1],
paddings[3]);
return;
}
} else if (ksize[0] == 2 && strides[0] == 2 && paddings[0] == 0 &&
kps_equal) {
if (pooling_type == "max") {
lite::arm::math::pooling2x2s2_max(din,
dout,
out_dims[0],
out_dims[1],
out_dims[2],
out_dims[3],
in_dims[1],
in_dims[2],
in_dims[3],
paddings[1],
paddings[3]);
return;
} else if (pooling_type == "avg") {
lite::arm::math::pooling2x2s2_avg(din,
dout,
out_dims[0],
out_dims[1],
out_dims[2],
out_dims[3],
in_dims[1],
in_dims[2],
in_dims[3],
exclusive,
paddings[1],
paddings[3]);
return;
}
} else if (ksize[0] == 3 && strides[0] == 1 && paddings[0] == 1 &&
kps_equal) {
if (pooling_type == "max") {
lite::arm::math::pooling3x3s1p1_max(din,
dout,
out_dims[0],
out_dims[1],
out_dims[2],
out_dims[3],
in_dims[1],
in_dims[2],
in_dims[3],
paddings[1],
paddings[3]);
return;
} else if (pooling_type == "avg") {
lite::arm::math::pooling3x3s1p1_avg(din,
dout,
out_dims[0],
out_dims[1],
out_dims[2],
out_dims[3],
in_dims[1],
in_dims[2],
in_dims[3],
exclusive,
paddings[1],
paddings[3]);
return;
}
} else if (ksize[0] == 3 && strides[0] == 1 && paddings[0] == 0 &&
kps_equal) {
if (pooling_type == "max") {
lite::arm::math::pooling3x3s1p0_max(din,
dout,
out_dims[0],
out_dims[1],
out_dims[2],
out_dims[3],
in_dims[1],
in_dims[2],
in_dims[3],
paddings[1],
paddings[3]);
return;
} else if (pooling_type == "avg") {
lite::arm::math::pooling3x3s1p0_avg(din,
dout,
out_dims[0],
out_dims[1],
out_dims[2],
out_dims[3],
in_dims[1],
in_dims[2],
in_dims[3],
exclusive,
paddings[1],
paddings[3]);
return;
}
} else if (ksize[0] == 3 && strides[0] == 2 && paddings[0] == 0 &&
kps_equal) {
if (pooling_type == "max") {
lite::arm::math::pooling3x3s2p0_max(din,
dout,
out_dims[0],
out_dims[1],
out_dims[2],
out_dims[3],
in_dims[1],
in_dims[2],
in_dims[3],
paddings[1],
paddings[3]);
return;
} else if (pooling_type == "avg") {
lite::arm::math::pooling3x3s2p0_avg(din,
dout,
out_dims[0],
out_dims[1],
out_dims[2],
out_dims[3],
in_dims[1],
in_dims[2],
in_dims[3],
exclusive,
paddings[1],
paddings[3]);
return;
}
} else if (ksize[0] == 3 && strides[0] == 2 && paddings[0] == 1 &&
kps_equal) {
if (pooling_type == "max") {
lite::arm::math::pooling3x3s2p1_max(din,
dout,
out_dims[0],
out_dims[1],
out_dims[2],
out_dims[3],
in_dims[1],
in_dims[2],
in_dims[3],
paddings[1],
paddings[3]);
return;
} else if (pooling_type == "avg") {
lite::arm::math::pooling3x3s2p1_avg(din,
dout,
out_dims[0],
out_dims[1],
out_dims[2],
out_dims[3],
in_dims[1],
in_dims[2],
in_dims[3],
exclusive,
paddings[1],
paddings[3]);
return;
}
}
}
lite::arm::math::pooling_basic(din,
dout,
out_dims[0],
out_dims[1],
out_dims[2],
out_dims[3],
in_dims[1],
in_dims[2],
in_dims[3],
ksize,
strides,
paddings,
global_pooling,
exclusive,
adaptive,
ceil_mode,
use_quantizer,
pooling_type);
}
} // namespace arm
} // namespace kernels
} // namespace lite
} // namespace paddle
REGISTER_LITE_KERNEL(
pool2d, kARM, kFloat, kNCHW, paddle::lite::kernels::arm::PoolCompute, def)
.BindInput("X", {LiteType::GetTensorTy(TARGET(kARM))})
.BindOutput("Out", {LiteType::GetTensorTy(TARGET(kARM))})
.Finalize();
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.