patch
stringlengths
17
31.2k
y
int64
1
1
oldf
stringlengths
0
2.21M
idx
int64
1
1
id
int64
4.29k
68.4k
msg
stringlengths
8
843
proj
stringclasses
212 values
lang
stringclasses
9 values
@@ -16,7 +16,7 @@ module Faker return result end - raise RetryLimitExceeded + raise RetryLimitExceeded, "Retry limit exceeded for #{name}" end RetryLimitExceeded = Class.new(StandardError)
1
module Faker class UniqueGenerator def initialize(generator, max_retries) @generator = generator @max_retries = max_retries @previous_results = Hash.new { |hash, key| hash[key] = Set.new } end def method_missing(name, *arguments) @max_retries.times do result = @generator.public_send(name, *arguments) next if @previous_results[[name, arguments]].include?(result) @previous_results[[name, arguments]] << result return result end raise RetryLimitExceeded end RetryLimitExceeded = Class.new(StandardError) def clear @previous_results.clear end def self.clear ObjectSpace.each_object(self, &:clear) end end end
1
8,486
@AndrewRayCode thanks for contributing Could you write/modify the specs to make sure that this description is working properly?
faker-ruby-faker
rb
@@ -120,7 +120,8 @@ def default_bucket(request): try: response = request.invoke_subrequest(subrequest) except httpexceptions.HTTPException as error: - if error.content_type == 'application/json': + is_redirect = error.status_code < 400 + if error.content_type == 'application/json' or is_redirect: response = reapply_cors(subrequest, error) else: # Ask the upper level to format the error.
1
import uuid import six from pyramid import httpexceptions from pyramid.settings import asbool from pyramid.security import NO_PERMISSION_REQUIRED from cliquet.errors import raise_invalid from cliquet.utils import build_request, reapply_cors, hmac_digest from cliquet.storage import exceptions as storage_exceptions from kinto.authorization import RouteFactory from kinto.views.buckets import Bucket from kinto.views.collections import Collection def create_bucket(request, bucket_id): """Create a bucket if it doesn't exists.""" bucket_put = (request.method.lower() == 'put' and request.path.endswith('buckets/default')) # Do nothing if current request will already create the bucket. if bucket_put: return # Do not intent to create multiple times per request (e.g. in batch). already_created = request.bound_data.setdefault('buckets', {}) if bucket_id in already_created: return # Fake context to instantiate a Bucket resource. context = RouteFactory(request) context.get_permission_object_id = lambda r, i: '/buckets/%s' % bucket_id resource = Bucket(request, context) try: bucket = resource.model.create_record({'id': bucket_id}) except storage_exceptions.UnicityError as e: bucket = e.record already_created[bucket_id] = bucket def create_collection(request, bucket_id): # Do nothing if current request does not involve a collection. subpath = request.matchdict.get('subpath') if not (subpath and subpath.startswith('collections/')): return collection_id = subpath.split('/')[1] collection_uri = '/buckets/%s/collections/%s' % (bucket_id, collection_id) # Do not intent to create multiple times per request (e.g. in batch). already_created = request.bound_data.setdefault('collections', {}) if collection_uri in already_created: return # Do nothing if current request will already create the collection. collection_put = (request.method.lower() == 'put' and request.path.endswith(collection_id)) if collection_put: return # Fake context to instantiate a Collection resource. context = RouteFactory(request) context.get_permission_object_id = lambda r, i: collection_uri backup = request.matchdict request.matchdict = dict(bucket_id=bucket_id, id=collection_id, **request.matchdict) resource = Collection(request, context) if not resource.model.id_generator.match(collection_id): error_details = { 'location': 'path', 'description': "Invalid collection_id id" } raise_invalid(request, **error_details) try: collection = resource.model.create_record({'id': collection_id}) except storage_exceptions.UnicityError as e: collection = e.record already_created[collection_uri] = collection request.matchdict = backup def default_bucket(request): if request.method.lower() == 'options': path = request.path.replace('default', 'unknown') subrequest = build_request(request, { 'method': 'OPTIONS', 'path': path }) return request.invoke_subrequest(subrequest) if getattr(request, 'prefixed_userid', None) is None: # Pass through the forbidden_view_config raise httpexceptions.HTTPForbidden() settings = request.registry.settings if asbool(settings['readonly']): raise httpexceptions.HTTPMethodNotAllowed() bucket_id = request.default_bucket_id path = request.path.replace('/buckets/default', '/buckets/%s' % bucket_id) querystring = request.url[(request.url.index(request.path) + len(request.path)):] # Make sure bucket exists create_bucket(request, bucket_id) # Make sure the collection exists create_collection(request, bucket_id) subrequest = build_request(request, { 'method': request.method, 'path': path + querystring, 'body': request.body }) subrequest.bound_data = request.bound_data try: response = request.invoke_subrequest(subrequest) except httpexceptions.HTTPException as error: if error.content_type == 'application/json': response = reapply_cors(subrequest, error) else: # Ask the upper level to format the error. raise error return response def default_bucket_id(request): settings = request.registry.settings secret = settings['userid_hmac_secret'] # Build the user unguessable bucket_id UUID from its user_id digest = hmac_digest(secret, request.prefixed_userid) return six.text_type(uuid.UUID(digest[:32])) def get_user_info(request): user_info = { 'id': request.prefixed_userid, 'bucket': request.default_bucket_id } return user_info def includeme(config): # Redirect default to the right endpoint config.add_view(default_bucket, route_name='default_bucket', permission=NO_PERMISSION_REQUIRED) config.add_view(default_bucket, route_name='default_bucket_collection', permission=NO_PERMISSION_REQUIRED) config.add_route('default_bucket_collection', '/buckets/default/{subpath:.*}') config.add_route('default_bucket', '/buckets/default') # Provide helpers config.add_request_method(default_bucket_id, reify=True) # Override Cliquet default user info config.add_request_method(get_user_info)
1
8,643
I would have tested 304 only there.
Kinto-kinto
py
@@ -36,16 +36,15 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests { // Close socket immediately } - } - await loggerFactory.FilterLogger.LogTcs.Task; + await loggerFactory.FilterLogger.LogTcs.Task.TimeoutAfter(TimeSpan.FromSeconds(10)); + } Assert.Equal(1, loggerFactory.FilterLogger.LastEventId.Id); Assert.Equal(LogLevel.Information, loggerFactory.FilterLogger.LastLogLevel); Assert.Equal(0, loggerFactory.ErrorLogger.TotalErrorsLogged); } - [Fact] public async Task ClientHandshakeFailureLoggedAsInformation() {
1
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Net.Sockets; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Server.Kestrel.Https; using Microsoft.AspNetCore.Testing; using Microsoft.Extensions.Logging; using Xunit; namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests { public class HttpsTests { [Fact] public async Task EmptyRequestLoggedAsInformation() { var loggerFactory = new HandshakeErrorLoggerFactory(); var hostBuilder = new WebHostBuilder() .UseKestrel(options => { options.UseHttps(@"TestResources/testCert.pfx", "testPassword"); }) .UseUrls("https://127.0.0.1:0/") .UseLoggerFactory(loggerFactory) .Configure(app => { }); using (var host = hostBuilder.Build()) { host.Start(); using (await HttpClientSlim.GetSocket(new Uri($"http://127.0.0.1:{host.GetPort()}/"))) { // Close socket immediately } } await loggerFactory.FilterLogger.LogTcs.Task; Assert.Equal(1, loggerFactory.FilterLogger.LastEventId.Id); Assert.Equal(LogLevel.Information, loggerFactory.FilterLogger.LastLogLevel); Assert.Equal(0, loggerFactory.ErrorLogger.TotalErrorsLogged); } [Fact] public async Task ClientHandshakeFailureLoggedAsInformation() { var loggerFactory = new HandshakeErrorLoggerFactory(); var hostBuilder = new WebHostBuilder() .UseKestrel(options => { options.UseHttps(@"TestResources/testCert.pfx", "testPassword"); }) .UseUrls("https://127.0.0.1:0/") .UseLoggerFactory(loggerFactory) .Configure(app => { }); using (var host = hostBuilder.Build()) { host.Start(); using (var socket = await HttpClientSlim.GetSocket(new Uri($"https://127.0.0.1:{host.GetPort()}/"))) using (var stream = new NetworkStream(socket)) { // Send null bytes and close socket await stream.WriteAsync(new byte[10], 0, 10); } } await loggerFactory.FilterLogger.LogTcs.Task; Assert.Equal(1, loggerFactory.FilterLogger.LastEventId.Id); Assert.Equal(LogLevel.Information, loggerFactory.FilterLogger.LastLogLevel); Assert.Equal(0, loggerFactory.ErrorLogger.TotalErrorsLogged); } private class HandshakeErrorLoggerFactory : ILoggerFactory { public HttpsConnectionFilterLogger FilterLogger { get; } = new HttpsConnectionFilterLogger(); public ApplicationErrorLogger ErrorLogger { get; } = new ApplicationErrorLogger(); public ILogger CreateLogger(string categoryName) { if (categoryName == nameof(HttpsConnectionFilter)) { return FilterLogger; } else { return ErrorLogger; } } public void AddProvider(ILoggerProvider provider) { throw new NotImplementedException(); } public void Dispose() { } } private class HttpsConnectionFilterLogger : ILogger { public LogLevel LastLogLevel { get; set; } public EventId LastEventId { get; set; } public TaskCompletionSource<object> LogTcs { get; } = new TaskCompletionSource<object>(); public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter) { LastLogLevel = logLevel; LastEventId = eventId; LogTcs.SetResult(null); } public bool IsEnabled(LogLevel logLevel) { throw new NotImplementedException(); } public IDisposable BeginScope<TState>(TState state) { throw new NotImplementedException(); } } private class ApplicationErrorLogger : ILogger { public int TotalErrorsLogged { get; set; } public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter) { if (logLevel == LogLevel.Error) { TotalErrorsLogged++; } } public bool IsEnabled(LogLevel logLevel) { return true; } public IDisposable BeginScope<TState>(TState state) { throw new NotImplementedException(); } } } }
1
9,876
`TimeoutAfter` to be safe.
aspnet-KestrelHttpServer
.cs
@@ -244,8 +244,14 @@ init_build_bb(build_bb_t *bb, app_pc start_pc, bool app_interp, bool for_cache, * whose fall-through hits our hook. We avoid interpreting our own hook * by shifting it to the displaced pc. */ - if (DYNAMO_OPTION(hook_vsyscall) && start_pc == vsyscall_sysenter_return_pc) - start_pc = vsyscall_sysenter_displaced_pc; + if (DYNAMO_OPTION(hook_vsyscall) && start_pc == vsyscall_sysenter_return_pc) { + if (vsyscall_sysenter_displaced_pc != NULL) + start_pc = vsyscall_sysenter_displaced_pc; + else { + /* Our hook must have failed. */ + ASSERT(should_syscall_method_be_sysenter()); + } + } #endif bb->check_vm_area = true; bb->start_pc = start_pc;
1
/* ********************************************************** * Copyright (c) 2011-2021 Google, Inc. All rights reserved. * Copyright (c) 2001-2010 VMware, Inc. All rights reserved. * **********************************************************/ /* * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of VMware, Inc. nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL VMWARE, INC. OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. */ /* Copyright (c) 2003-2007 Determina Corp. */ /* Copyright (c) 2001-2003 Massachusetts Institute of Technology */ /* Copyright (c) 2001 Hewlett-Packard Company */ /* * interp.c - interpreter used for native trace selection */ #include "../globals.h" #include "../link.h" #include "../fragment.h" #include "../emit.h" #include "../dispatch.h" #include "../fcache.h" #include "../monitor.h" /* for trace_abort and monitor_data_t */ #include "arch.h" #include "instr.h" #include "instr_create_shared.h" #include "instrlist.h" #include "decode.h" #include "decode_fast.h" #include "disassemble.h" #include "instrument.h" #include "../hotpatch.h" #ifdef RETURN_AFTER_CALL # include "../rct.h" #endif #ifdef WINDOWS # include "ntdll.h" /* for EXCEPTION_REGISTRATION */ # include "../nudge.h" /* for generic_nudge_target() address */ #endif #include "../perscache.h" #include "../native_exec.h" #include "../jit_opt.h" #ifdef CHECK_RETURNS_SSE2 # include <setjmp.h> /* for warning when see libc setjmp */ #endif #ifdef VMX86_SERVER # include "vmkuw.h" /* VMKUW_SYSCALL_GATEWAY */ #endif #ifdef ANNOTATIONS # include "../annotations.h" #endif #ifdef AARCH64 # include "build_ldstex.h" #endif enum { DIRECT_XFER_LENGTH = 5 }; /* forward declarations */ static void process_nops_for_trace(dcontext_t *dcontext, instrlist_t *ilist, uint flags _IF_DEBUG(bool recreating)); static int fixup_last_cti(dcontext_t *dcontext, instrlist_t *trace, app_pc next_tag, uint next_flags, uint trace_flags, fragment_t *prev_f, linkstub_t *prev_l, bool record_translation, uint *num_exits_deleted /*OUT*/, /* If non-NULL, only looks inside trace between these two */ instr_t *start_instr, instr_t *end_instr); bool mangle_trace(dcontext_t *dcontext, instrlist_t *ilist, monitor_data_t *md); /* we use a branch limit of 1 to make it easier for the trace * creation mechanism to stitch basic blocks together */ #define BRANCH_LIMIT 1 /* we limit total bb size to handle cases like infinite loop or sequence * of calls. * also, we have a limit on fragment body sizes, which should be impossible * to break since x86 instrs are max 17 bytes and we only modify ctis. * Although...selfmod mangling does really expand fragments! * -selfmod_max_writes helps for selfmod bbs (case 7893/7909). * System call mangling is also large, for degenerate cases like tests/linux/infinite. * PR 215217: also client additions: we document and assert. * FIXME: need better way to know how big will get, b/c we can construct * cases that will trigger the size assertion! */ /* define replaced by -max_bb_instrs option */ /* exported so micro routines can assert whether held */ DECLARE_CXTSWPROT_VAR(mutex_t bb_building_lock, INIT_LOCK_FREE(bb_building_lock)); /* i#1111: we do not use the lock until the 2nd thread is created */ volatile bool bb_lock_start; static file_t bbdump_file = INVALID_FILE; #ifdef DEBUG DECLARE_NEVERPROT_VAR(uint debug_bb_count, 0); #endif /* initialization */ void interp_init() { if (INTERNAL_OPTION(bbdump_tags)) { bbdump_file = open_log_file("bbs", NULL, 0); ASSERT(bbdump_file != INVALID_FILE); } } #ifdef CUSTOM_TRACES_RET_REMOVAL # ifdef DEBUG /* don't bother with adding lock */ static int num_rets_removed; # endif #endif /* cleanup */ void interp_exit() { if (INTERNAL_OPTION(bbdump_tags)) { close_log_file(bbdump_file); } DELETE_LOCK(bb_building_lock); LOG(GLOBAL, LOG_INTERP | LOG_STATS, 1, "Total application code seen: %d KB\n", GLOBAL_STAT(app_code_seen) / 1024); #ifdef CUSTOM_TRACES_RET_REMOVAL # ifdef DEBUG LOG(GLOBAL, LOG_INTERP | LOG_STATS, 1, "Total rets removed: %d\n", num_rets_removed); # endif #endif } /**************************************************************************** **************************************************************************** * * B A S I C B L O C K B U I L D I N G */ /* we have a lot of data to pass around so we package it in this struct * so we can have separate routines for readability */ typedef struct { /* in */ app_pc start_pc; bool app_interp; /* building bb to interp app, as opposed to for pc * translation or figuring out what pages a bb touches? */ bool for_cache; /* normal to-be-executed build? */ bool record_vmlist; /* should vmareas be updated? */ bool mangle_ilist; /* should bb ilist be mangled? */ bool record_translation; /* store translation info for each instr_t? */ bool has_bb_building_lock; /* usually ==for_cache; used for aborting bb building */ bool checked_start_vmarea; /* caller called check_new_page_start() on start_pc */ file_t outf; /* send disassembly and notes to a file? * we use this mainly for dumping trace origins */ app_pc stop_pc; /* Optional: NULL for normal termination rules. * Only checked for full_decode. */ bool pass_to_client; /* pass to client, if a bb hook exists; * we store this up front to avoid race conditions * between full_decode setting and hook calling time. */ bool post_client; /* has the client already processed the bb? */ bool for_trace; /* PR 299808: we tell client if building a trace */ /* in and out */ overlap_info_t *overlap_info; /* if non-null, records overlap information here; * caller must initialize region_start and region_end */ /* out */ instrlist_t *ilist; uint flags; void *vmlist; app_pc end_pc; bool native_exec; /* replace cur ilist with a native_exec version */ bool native_call; /* the gateway is a call */ instrlist_t **unmangled_ilist; /* PR 299808: clone ilist pre-mangling */ /* internal usage only */ bool full_decode; /* decode every instruction into a separate instr_t? */ bool follow_direct; /* elide unconditional branches? */ bool check_vm_area; /* whether to call check_thread_vm_area() */ uint num_elide_jmp; uint num_elide_call; app_pc last_page; app_pc cur_pc; app_pc instr_start; app_pc checked_end; /* end of current vmarea checked */ cache_pc exit_target; /* fall-through target of final instr */ uint exit_type; /* indirect branch type */ ibl_branch_type_t ibl_branch_type; /* indirect branch type as an IBL selector */ instr_t *instr; /* the current instr */ int eflags; app_pc pretend_pc; /* selfmod only: decode from separate pc */ #ifdef ARM dr_pred_type_t svc_pred; /* predicate for conditional svc */ #endif DEBUG_DECLARE(bool initialized;) } build_bb_t; /* forward decl */ static inline bool bb_process_syscall(dcontext_t *dcontext, build_bb_t *bb); static void init_build_bb(build_bb_t *bb, app_pc start_pc, bool app_interp, bool for_cache, bool mangle_ilist, bool record_translation, file_t outf, uint known_flags, overlap_info_t *overlap_info) { memset(bb, 0, sizeof(*bb)); #if defined(LINUX) && defined(X86_32) /* With SA_RESTART (i#2659) we end up interpreting the int 0x80 in vsyscall, * whose fall-through hits our hook. We avoid interpreting our own hook * by shifting it to the displaced pc. */ if (DYNAMO_OPTION(hook_vsyscall) && start_pc == vsyscall_sysenter_return_pc) start_pc = vsyscall_sysenter_displaced_pc; #endif bb->check_vm_area = true; bb->start_pc = start_pc; bb->app_interp = app_interp; bb->for_cache = for_cache; if (bb->for_cache) bb->record_vmlist = true; bb->mangle_ilist = mangle_ilist; bb->record_translation = record_translation; bb->outf = outf; bb->overlap_info = overlap_info; bb->follow_direct = !TEST(FRAG_SELFMOD_SANDBOXED, known_flags); bb->flags = known_flags; bb->ibl_branch_type = IBL_GENERIC; /* initialization only */ #ifdef ARM bb->svc_pred = DR_PRED_NONE; #endif DODEBUG(bb->initialized = true;); } static void reset_overlap_info(dcontext_t *dcontext, build_bb_t *bb) { bb->overlap_info->start_pc = bb->start_pc; bb->overlap_info->min_pc = bb->start_pc; bb->overlap_info->max_pc = bb->start_pc; bb->overlap_info->contiguous = true; bb->overlap_info->overlap = false; } static void update_overlap_info(dcontext_t *dcontext, build_bb_t *bb, app_pc new_pc, bool jmp) { if (new_pc < bb->overlap_info->min_pc) bb->overlap_info->min_pc = new_pc; if (new_pc > bb->overlap_info->max_pc) bb->overlap_info->max_pc = new_pc; /* we get called at end of all contiguous intervals, so ignore jmps */ LOG(THREAD, LOG_ALL, 5, "\t app_bb_overlaps " PFX ".." PFX " %s\n", bb->last_page, new_pc, jmp ? "jmp" : ""); if (!bb->overlap_info->overlap && !jmp) { /* contiguous interval: prev_pc..new_pc (open-ended) */ if (bb->last_page < bb->overlap_info->region_end && new_pc > bb->overlap_info->region_start) { LOG(THREAD_GET, LOG_ALL, 5, "\t it overlaps!\n"); bb->overlap_info->overlap = true; } } if (bb->overlap_info->contiguous && jmp) bb->overlap_info->contiguous = false; } #ifdef DEBUG # define BBPRINT(bb, level, ...) \ do { \ LOG(THREAD, LOG_INTERP, level, __VA_ARGS__); \ if (bb->outf != INVALID_FILE && bb->outf != (THREAD)) \ print_file(bb->outf, __VA_ARGS__); \ } while (0); #else # ifdef INTERNAL # define BBPRINT(bb, level, ...) \ do { \ if (bb->outf != INVALID_FILE) \ print_file(bb->outf, __VA_ARGS__); \ } while (0); # else # define BBPRINT(bb, level, ...) /* nothing */ # endif #endif #ifdef WINDOWS extern void intercept_load_dll(void); extern void intercept_unload_dll(void); # ifdef INTERNAL extern void DllMainThreadAttach(void); # endif #endif /* forward declarations */ static bool mangle_bb_ilist(dcontext_t *dcontext, build_bb_t *bb); static void build_native_exec_bb(dcontext_t *dcontext, build_bb_t *bb); static bool at_native_exec_gateway(dcontext_t *dcontext, app_pc start, bool *is_call _IF_DEBUG(bool xfer_target)); #ifdef DEBUG static void report_native_module(dcontext_t *dcontext, app_pc modpc); #endif /*************************************************************************** * Image entry */ static bool reached_image_entry = false; static INLINE_FORCED bool check_for_image_entry(app_pc bb_start) { if (!reached_image_entry && bb_start == get_image_entry()) { LOG(THREAD_GET, LOG_ALL, 1, "Reached image entry point " PFX "\n", bb_start); set_reached_image_entry(); return true; } return false; } void set_reached_image_entry() { SELF_UNPROTECT_DATASEC(DATASEC_RARELY_PROT); reached_image_entry = true; SELF_PROTECT_DATASEC(DATASEC_RARELY_PROT); } bool reached_image_entry_yet() { return reached_image_entry; } /*************************************************************************** * Whether to inline or elide callees */ /* Return true if pc is a call target that should NOT be entered but should * still be mangled. */ static inline bool must_not_be_entered(app_pc pc) { return false #ifdef DR_APP_EXPORTS /* i#1237: DR will change dr_app_running_under_dynamorio return value * on seeing a bb starting at dr_app_running_under_dynamorio. */ || pc == (app_pc)dr_app_running_under_dynamorio #endif ; } /* Return true if pc is a call target that should NOT be inlined and left native. */ static inline bool leave_call_native(app_pc pc) { return ( #ifdef INTERNAL !dynamo_options.inline_calls #else 0 #endif #ifdef WINDOWS || pc == (app_pc)intercept_load_dll || pc == (app_pc)intercept_unload_dll /* we're guaranteed to have direct calls to the next routine since our * own DllMain calls it! */ # ifdef INTERNAL || pc == (app_pc)DllMainThreadAttach # endif /* check for nudge handling escape from cache */ || (pc == (app_pc)generic_nudge_handler) #else /* PR 200203: long-term we want to control loading of client * libs, but for now we have to let the loader call _fini() * in the client, which may end up calling __wrap_free(). * It's simpler to let those be interpreted and make a native * call to the real heap routine here as this is a direct * call whereas we'd need native_exec for the others: */ || pc == (app_pc)global_heap_free #endif ); } /* return true if pc is a direct jmp target that should NOT be elided and followed */ static inline bool must_not_be_elided(app_pc pc) { #ifdef WINDOWS /* Allow only the return jump in the landing pad to be elided, as we * interpret the return path from trampolines. The forward jump leads to * the trampoline and shouldn't be elided. */ if (is_on_interception_initial_route(pc)) return true; #endif return (0 #ifdef WINDOWS /* we insert trampolines by adding direct jmps to our interception code buffer * we don't want to interpret the code in that buffer, as it may swap to the * dstack and mess up a return-from-fcache. * N.B.: if use this routine anywhere else, pay attention to the * hack for is_syscall_trampoline() in the use here! */ || (is_in_interception_buffer(pc)) #else /* UNIX */ #endif ); } #ifdef DR_APP_EXPORTS /* This function allows automatically injected dynamo to ignore * dynamo API routines that would really mess things up */ static inline bool must_escape_from(app_pc pc) { /* if ever find ourselves at top of one of these, immediately issue * a ret instruction...haven't set up frame yet so stack fine, only * problem is return value, go ahead and overwrite xax, it's caller-saved * FIXME: is this ok? */ /* Note that we can't just look for direct calls to these functions * because of stubs, etc. that end up doing indirect jumps to them! */ bool res = false # ifdef DR_APP_EXPORTS || (automatic_startup && (pc == (app_pc)dynamorio_app_init || pc == (app_pc)dr_app_start || pc == (app_pc)dynamo_thread_init || pc == (app_pc)dynamorio_app_exit || /* dr_app_stop is a nop already */ pc == (app_pc)dynamo_thread_exit)) # endif ; # ifdef DEBUG if (res) { # ifdef DR_APP_EXPORTS LOG(THREAD_GET, LOG_INTERP, 3, "must_escape_from: found "); if (pc == (app_pc)dynamorio_app_init) LOG(THREAD_GET, LOG_INTERP, 3, "dynamorio_app_init\n"); else if (pc == (app_pc)dr_app_start) LOG(THREAD_GET, LOG_INTERP, 3, "dr_app_start\n"); /* FIXME: are dynamo_thread_* still needed hered? */ else if (pc == (app_pc)dynamo_thread_init) LOG(THREAD_GET, LOG_INTERP, 3, "dynamo_thread_init\n"); else if (pc == (app_pc)dynamorio_app_exit) LOG(THREAD_GET, LOG_INTERP, 3, "dynamorio_app_exit\n"); else if (pc == (app_pc)dynamo_thread_exit) LOG(THREAD_GET, LOG_INTERP, 3, "dynamo_thread_exit\n"); # endif } # endif return res; } #endif /* DR_APP_EXPORTS */ /* Adds bb->instr, which must be a direct call or jmp, to bb->ilist for native * execution. Makes sure its target is reachable from the code cache, which * is critical for jmps b/c they're native for our hooks of app code which may * not be reachable from the code cache. Also needed for calls b/c in the future * (i#774) the DR lib (and thus our leave_call_native() calls) won't be reachable * from the cache. */ static void bb_add_native_direct_xfer(dcontext_t *dcontext, build_bb_t *bb, bool appended) { #if defined(X86) && defined(X64) /* i#922: we're going to run this jmp from our code cache so we have to * make sure it still reaches its target. We could try to check * reachability from the likely code cache slot, but these should be * rare enough that making them indirect won't matter and then we have * fewer reachability dependences. * We do this here rather than in d_r_mangle() b/c we'd have a hard time * distinguishing native jmp/call due to DR's own operations from a * client's inserted meta jmp/call. */ /* Strategy: write target into xax (DR-reserved) slot and jmp through it. * Alternative would be to embed the target into the code stream. * We don't need to set translation b/c these are meta instrs and they * won't fault. */ ptr_uint_t tgt = (ptr_uint_t)opnd_get_pc(instr_get_target(bb->instr)); opnd_t tls_slot = opnd_create_sized_tls_slot(os_tls_offset(TLS_XAX_SLOT), OPSZ_4); instrlist_meta_append( bb->ilist, INSTR_CREATE_mov_imm(dcontext, tls_slot, OPND_CREATE_INT32((int)tgt))); opnd_set_disp(&tls_slot, opnd_get_disp(tls_slot) + 4); instrlist_meta_append( bb->ilist, INSTR_CREATE_mov_imm(dcontext, tls_slot, OPND_CREATE_INT32((int)(tgt >> 32)))); if (instr_is_ubr(bb->instr)) { instrlist_meta_append( bb->ilist, INSTR_CREATE_jmp_ind(dcontext, opnd_create_tls_slot(os_tls_offset(TLS_XAX_SLOT)))); bb->exit_type |= instr_branch_type(bb->instr); } else { ASSERT(instr_is_call_direct(bb->instr)); instrlist_meta_append( bb->ilist, INSTR_CREATE_call_ind(dcontext, opnd_create_tls_slot(os_tls_offset(TLS_XAX_SLOT)))); } if (appended) instrlist_remove(bb->ilist, bb->instr); instr_destroy(dcontext, bb->instr); bb->instr = NULL; #elif defined(ARM) ASSERT_NOT_IMPLEMENTED(false); /* i#1582 */ #else if (appended) { /* avoid assert about meta w/ translation but no restore_state callback */ instr_set_translation(bb->instr, NULL); } else instrlist_append(bb->ilist, bb->instr); /* Indicate that relative target must be * re-encoded, and that it is not an exit cti. * However, we must mangle this to ensure it reaches (i#992) * which we special-case in d_r_mangle(). */ instr_set_meta(bb->instr); instr_set_raw_bits_valid(bb->instr, false); #endif } /* Perform checks such as looking for dynamo stopping points and bad places * to be. We assume we only have to check after control transfer instructions, * i.e., we assume that all of these conditions are procedures that are only * entered by calling or jumping, never falling through. */ static inline bool check_for_stopping_point(dcontext_t *dcontext, build_bb_t *bb) { #ifdef DR_APP_EXPORTS if (must_escape_from(bb->cur_pc)) { /* x64 will zero-extend to rax, so we use eax here */ reg_id_t reg = IF_X86_ELSE(REG_EAX, DR_REG_R0); BBPRINT(bb, 3, "interp: emergency exit from " PFX "\n", bb->cur_pc); /* if ever find ourselves at top of one of these, immediately issue * a ret instruction...haven't set up frame yet so stack fine, only * problem is return value, go ahead and overwrite xax, it's * caller-saved. * FIXME: is this ok? */ /* move 0 into xax/r0 -- our functions return 0 to indicate success */ instrlist_append( bb->ilist, XINST_CREATE_load_int(dcontext, opnd_create_reg(reg), OPND_CREATE_INT32(0))); /* insert a ret instruction */ instrlist_append(bb->ilist, XINST_CREATE_return(dcontext)); /* should this be treated as a real return? */ bb->exit_type |= LINK_INDIRECT | LINK_RETURN; bb->exit_target = get_ibl_routine(dcontext, IBL_LINKED, DEFAULT_IBL_BB(), IBL_RETURN); return true; } #endif /* DR_APP_EXPORTS */ #ifdef CHECK_RETURNS_SSE2 if (bb->cur_pc == (app_pc)longjmp) { SYSLOG_INTERNAL_WARNING("encountered longjmp, which will cause ret mismatch!"); } #endif return is_stopping_point(dcontext, bb->cur_pc); } /* Arithmetic eflags analysis to see if sequence of instrs reads an * arithmetic flag prior to writing it. * Usage: first initialize status to 0 and eflags_6 to 0. * Then call this routine for each instr in sequence, assigning result to status. * eflags_6 holds flags written and read so far. * Uses these flags, defined in instr.h, as status values: * EFLAGS_WRITE_ARITH = writes all arith flags before reading any * EFLAGS_WRITE_OF = writes OF before reading it (x86-onlY) * EFLAGS_READ_ARITH = reads some of arith flags before writing * EFLAGS_READ_OF = reads OF before writing OF (x86-only) * 0 = no information yet * On ARM, Q and GE flags are ignored. */ static inline int eflags_analysis(instr_t *instr, int status, uint *eflags_6) { uint e6 = *eflags_6; /* local copy */ uint e6_w2r = EFLAGS_WRITE_TO_READ(e6); uint instr_eflags = instr_get_arith_flags(instr, DR_QUERY_DEFAULT); /* Keep going until result is non-zero, also keep going if * result is writes to OF to see if later writes to rest of flags * before reading any, and keep going if reads one of the 6 to see * if later writes to OF before reading it. */ if (instr_eflags == 0 || status == EFLAGS_WRITE_ARITH IF_X86(|| status == EFLAGS_READ_OF)) return status; /* we ignore interrupts */ if ((instr_eflags & EFLAGS_READ_ARITH) != 0 && (!instr_opcode_valid(instr) || !instr_is_interrupt(instr))) { /* store the flags we're reading */ e6 |= (instr_eflags & EFLAGS_READ_ARITH); *eflags_6 = e6; if ((e6_w2r | (instr_eflags & EFLAGS_READ_ARITH)) != e6_w2r) { /* we're reading a flag that has not been written yet */ status = EFLAGS_READ_ARITH; /* some read before all written */ LOG(THREAD_GET, LOG_INTERP, 4, "\treads flag before writing it!\n"); #ifdef X86 if ((instr_eflags & EFLAGS_READ_OF) != 0 && (e6 & EFLAGS_WRITE_OF) == 0) { status = EFLAGS_READ_OF; /* reads OF before writing! */ LOG(THREAD_GET, LOG_INTERP, 4, "\t reads OF prior to writing it!\n"); } #endif } } else if ((instr_eflags & EFLAGS_WRITE_ARITH) != 0) { /* store the flags we're writing */ e6 |= (instr_eflags & EFLAGS_WRITE_ARITH); *eflags_6 = e6; /* check if all written but none read yet */ if ((e6 & EFLAGS_WRITE_ARITH) == EFLAGS_WRITE_ARITH && (e6 & EFLAGS_READ_ARITH) == 0) { status = EFLAGS_WRITE_ARITH; /* all written before read */ LOG(THREAD_GET, LOG_INTERP, 4, "\twrote all 6 flags now!\n"); } #ifdef X86 /* check if at least OF was written but not read */ else if ((e6 & EFLAGS_WRITE_OF) != 0 && (e6 & EFLAGS_READ_OF) == 0) { status = EFLAGS_WRITE_OF; /* OF written before read */ LOG(THREAD_GET, LOG_INTERP, 4, "\twrote overflow flag before reading it!\n"); } #endif } return status; } /* check origins of code for several purposes: * 1) we need list of areas where this thread's fragments come * from, for faster flushing on munmaps * 2) also for faster flushing, each vmarea has a list of fragments * 3) we need to mark as read-only any writable region that * has a fragment come from it, to handle self-modifying code * 4) for PROGRAM_SHEPHERDING restricted code origins for security * 5) for restricted execution environments: not letting bb cross regions */ /* FIXME CASE 7380: since report security violation before execute off bad page, can be false positive due to: - a faulting instruction in middle of bb would have prevented getting there - ignorable syscall in middle - self-mod code would have ended bb sooner than bad page One solution is to have check_thread_vm_area() return false and have bb building stop at checked_end if a violation will occur when we get there. Then we only raise the violation once building a bb starting there. */ static inline void check_new_page_start(dcontext_t *dcontext, build_bb_t *bb) { DEBUG_DECLARE(bool ok;) if (!bb->check_vm_area) return; DEBUG_DECLARE(ok =) check_thread_vm_area(dcontext, bb->start_pc, bb->start_pc, (bb->record_vmlist ? &bb->vmlist : NULL), &bb->flags, &bb->checked_end, false /*!xfer*/); ASSERT(ok); /* cannot return false on non-xfer */ bb->last_page = bb->start_pc; if (bb->overlap_info != NULL) reset_overlap_info(dcontext, bb); } /* Walk forward in straight line from prev_pc to new_pc. * FIXME: with checked_end we don't need to call this on every contig end * while bb building like we used to. Should revisit the overlap info and * walk_app_bb reasons for keeping those contig() calls and see if we can * optimize them away for bb building at least. * i#993: new_pc points to the last byte of the current instruction and is not * an open-ended endpoint. */ static inline bool check_new_page_contig(dcontext_t *dcontext, build_bb_t *bb, app_pc new_pc) { bool is_first_instr = (bb->instr_start == bb->start_pc); if (!bb->check_vm_area) return true; if (bb->checked_end == NULL) { ASSERT(new_pc == bb->start_pc); } else if (new_pc >= bb->checked_end) { if (!check_thread_vm_area(dcontext, new_pc, bb->start_pc, (bb->record_vmlist ? &bb->vmlist : NULL), &bb->flags, &bb->checked_end, /* i#989: We don't want to fall through to an * incompatible vmarea, so we treat fall * through like a transfer. We can't end the * bb before the first instruction, so we pass * false to forcibly merge in the vmarea * flags. */ !is_first_instr /*xfer*/)) { return false; } } if (bb->overlap_info != NULL) update_overlap_info(dcontext, bb, new_pc, false /*not jmp*/); DOLOG(4, LOG_INTERP, { if (PAGE_START(bb->last_page) != PAGE_START(new_pc)) LOG(THREAD, LOG_INTERP, 4, "page boundary crossed\n"); }); bb->last_page = new_pc; /* update even if not new page, for walk_app_bb */ return true; } /* Direct cti from prev_pc to new_pc */ static bool check_new_page_jmp(dcontext_t *dcontext, build_bb_t *bb, app_pc new_pc) { /* For tracking purposes, check the last byte of the cti. */ bool ok = check_new_page_contig(dcontext, bb, bb->cur_pc - 1); ASSERT(ok && "should have checked cur_pc-1 in decode loop"); if (!ok) /* Don't follow the jmp in release build. */ return false; /* cur sandboxing doesn't handle direct cti * not good enough to only check this at top of interp -- could walk contig * from non-selfmod to selfmod page, and then do a direct cti, which * check_thread_vm_area would allow (no flag changes on direct cti)! * also not good enough to put this check in check_thread_vm_area, as that * only checks across pages. */ if ((bb->flags & FRAG_SELFMOD_SANDBOXED) != 0) return false; if (PAGE_START(bb->last_page) != PAGE_START(new_pc)) LOG(THREAD, LOG_INTERP, 4, "page boundary crossed\n"); /* do not walk into a native exec dll (we assume not currently there, * though could happen if bypass a gateway -- even then this is a feature * to allow getting back to native ASAP) * FIXME: we could assume that such direct calls only * occur from DGC, and rely on check_thread_vm_area to disallow, * as an (unsafe) optimization */ if (DYNAMO_OPTION(native_exec) && DYNAMO_OPTION(native_exec_dircalls) && !vmvector_empty(native_exec_areas) && is_native_pc(new_pc)) return false; /* i#805: If we're crossing a module boundary between two modules that are * and aren't on null_instrument_list, don't elide the jmp. * XXX i#884: if we haven't yet executed from the 2nd module, the client * won't receive the module load event yet and we might include code * from it here. It would be tricky to solve that, and it should only happen * if the client turns on elision, so we leave it. */ if ((!!os_module_get_flag(bb->cur_pc, MODULE_NULL_INSTRUMENT)) != (!!os_module_get_flag(new_pc, MODULE_NULL_INSTRUMENT))) return false; if (!bb->check_vm_area) return true; /* need to check this even if an intra-page jmp b/c we allow sub-page vm regions */ if (!check_thread_vm_area(dcontext, new_pc, bb->start_pc, (bb->record_vmlist ? &bb->vmlist : NULL), &bb->flags, &bb->checked_end, true /*xfer*/)) return false; if (bb->overlap_info != NULL) update_overlap_info(dcontext, bb, new_pc, true /*jmp*/); bb->flags |= FRAG_HAS_DIRECT_CTI; bb->last_page = new_pc; /* update even if not new page, for walk_app_bb */ return true; } static inline void bb_process_single_step(dcontext_t *dcontext, build_bb_t *bb) { LOG(THREAD, LOG_INTERP, 2, "interp: single step exception bb at " PFX "\n", bb->instr_start); /* FIXME i#2144 : handling a rep string operation. * In this case, we should test if only one iteration is done * before the single step exception. */ instrlist_append(bb->ilist, bb->instr); instr_set_translation(bb->instr, bb->instr_start); /* Mark instruction as special exit. */ instr_branch_set_special_exit(bb->instr, true); bb->exit_type |= LINK_SPECIAL_EXIT; /* Make this bb thread-private and a trace barrier. */ bb->flags &= ~FRAG_SHARED; bb->flags |= FRAG_CANNOT_BE_TRACE; } static inline void bb_process_invalid_instr(dcontext_t *dcontext, build_bb_t *bb) { /* invalid instr: end bb BEFORE the instr, we'll throw exception if we * reach the instr itself */ LOG(THREAD, LOG_INTERP, 2, "interp: invalid instr at " PFX "\n", bb->instr_start); /* This routine is called by more than just bb builder, also used * for recreating state, so check bb->app_interp parameter to find out * if building a real app bb to be executed */ if (bb->app_interp && bb->instr_start == bb->start_pc) { /* This is first instr in bb so it will be executed for sure and * we need to generate an invalid instruction exception. * A benefit of being first instr is that the state is easy * to translate. */ /* Copying the invalid bytes and having the processor generate the exception * would help on Windows where the kernel splits invalid instructions into * different cases (an invalid lock prefix and other distinctions, when the * underlying processor has a single interrupt 6), and it is hard to * duplicate Windows' behavior in our forged exception. However, we are not * certain that this instruction will raise a fault on the processor. It * might not if our decoder has a bug, or a new processor has added new * opcodes, or just due to processor variations in undefined gray areas. * Trying to copy without knowing the length of the instruction is a recipe * for disaster: it can lead to executing junk and even missing our exit cti * (i#3939). */ /* TODO i#1000: Give clients a chance to see this instruction for analysis, * and to change it. That's not easy to do though when we don't know what * it is. But it's confusing for the client to get the illegal instr fault * having never seen the problematic instr in a bb event. */ /* XXX i#57: provide a runtime option to specify new instruction formats to * avoid this app exception for new opcodes. */ ASSERT(dcontext->bb_build_info == bb); bb_build_abort(dcontext, true /*clean vm area*/, true /*unlock*/); /* XXX: we use illegal instruction here, even though we * know windows uses different exception codes for different * types of invalid instructions (for ex. STATUS_INVALID_LOCK * _SEQUENCE for lock prefix on a jmp instruction). */ if (TEST(DUMPCORE_FORGE_ILLEGAL_INST, DYNAMO_OPTION(dumpcore_mask))) os_dump_core("Warning: Encountered Illegal Instruction"); os_forge_exception(bb->instr_start, ILLEGAL_INSTRUCTION_EXCEPTION); ASSERT_NOT_REACHED(); } else { instr_destroy(dcontext, bb->instr); bb->instr = NULL; } } /* FIXME i#1668, i#2974: NYI on ARM/AArch64 */ #ifdef X86 /* returns true to indicate "elide and continue" and false to indicate "end bb now" * should be used both for converted indirect jumps and * FIXME: for direct jumps by bb_process_ubr */ static inline bool follow_direct_jump(dcontext_t *dcontext, build_bb_t *bb, app_pc target) { if (bb->follow_direct && !must_not_be_entered(target) && bb->num_elide_jmp < DYNAMO_OPTION(max_elide_jmp) && (DYNAMO_OPTION(elide_back_jmps) || bb->cur_pc <= target)) { if (check_new_page_jmp(dcontext, bb, target)) { /* Elide unconditional branch and follow target */ bb->num_elide_jmp++; STATS_INC(total_elided_jmps); STATS_TRACK_MAX(max_elided_jmps, bb->num_elide_jmp); bb->cur_pc = target; BBPRINT(bb, 4, " continuing at target " PFX "\n", bb->cur_pc); return true; /* keep bb going */ } else { BBPRINT(bb, 3, " NOT following jmp from " PFX " to " PFX "\n", bb->instr_start, target); } } else { BBPRINT(bb, 3, " NOT attempting to follow jump from " PFX " to " PFX "\n", bb->instr_start, target); } return false; /* stop bb */ } #endif /* X86 */ /* returns true to indicate "elide and continue" and false to indicate "end bb now" */ static inline bool bb_process_ubr(dcontext_t *dcontext, build_bb_t *bb) { app_pc tgt = (byte *)opnd_get_pc(instr_get_target(bb->instr)); BBPRINT(bb, 4, "interp: direct jump at " PFX "\n", bb->instr_start); if (must_not_be_elided(tgt)) { #ifdef WINDOWS byte *wrapper_start; if (is_syscall_trampoline(tgt, &wrapper_start)) { /* HACK to avoid entering the syscall trampoline that is meant * only for native syscalls -- we replace the jmp with the * original app mov immed that it replaced */ BBPRINT(bb, 3, "interp: replacing syscall trampoline @" PFX " w/ orig mov @" PFX "\n", bb->instr_start, wrapper_start); instr_reset(dcontext, bb->instr); /* leave bb->cur_pc unchanged */ decode(dcontext, wrapper_start, bb->instr); /* ASSUMPTION: syscall trampoline puts hooked instruction * (usually mov_imm but can be lea if hooked_deeper) here */ ASSERT(instr_get_opcode(bb->instr) == OP_mov_imm || (instr_get_opcode(bb->instr) == OP_lea && DYNAMO_OPTION(native_exec_hook_conflict) == HOOKED_TRAMPOLINE_HOOK_DEEPER)); instrlist_append(bb->ilist, bb->instr); /* translation should point to the trampoline at the * original application address */ if (bb->record_translation) instr_set_translation(bb->instr, bb->instr_start); if (instr_get_opcode(bb->instr) == OP_lea) { app_pc translation = bb->instr_start + instr_length(dcontext, bb->instr); ASSERT_CURIOSITY(instr_length(dcontext, bb->instr) == 4); /* we hooked deep need to add the int 2e instruction */ /* can't use create_syscall_instr because of case 5217 hack */ ASSERT(get_syscall_method() == SYSCALL_METHOD_INT); bb->instr = INSTR_CREATE_int(dcontext, opnd_create_immed_int((char)0x2e, OPSZ_1)); if (bb->record_translation) instr_set_translation(bb->instr, translation); ASSERT(instr_is_syscall(bb->instr) && instr_get_opcode(bb->instr) == OP_int); instrlist_append(bb->ilist, bb->instr); return bb_process_syscall(dcontext, bb); } return true; /* keep bb going */ } #endif BBPRINT(bb, 3, "interp: NOT following jmp to " PFX "\n", tgt); /* add instruction to instruction list */ bb_add_native_direct_xfer(dcontext, bb, false /*!appended*/); /* Case 8711: coarse-grain can't handle non-exit cti */ bb->flags &= ~FRAG_COARSE_GRAIN; STATS_INC(coarse_prevent_cti); return false; /* end bb now */ } else { if (bb->follow_direct && !must_not_be_entered(tgt) && bb->num_elide_jmp < DYNAMO_OPTION(max_elide_jmp) && (DYNAMO_OPTION(elide_back_jmps) || bb->cur_pc <= tgt)) { if (check_new_page_jmp(dcontext, bb, tgt)) { /* Elide unconditional branch and follow target */ bb->num_elide_jmp++; STATS_INC(total_elided_jmps); STATS_TRACK_MAX(max_elided_jmps, bb->num_elide_jmp); bb->cur_pc = tgt; BBPRINT(bb, 4, " continuing at target " PFX "\n", bb->cur_pc); /* pretend never saw this ubr: delete instr, then continue */ instr_destroy(dcontext, bb->instr); bb->instr = NULL; return true; /* keep bb going */ } else { BBPRINT(bb, 3, " NOT following direct jmp from " PFX " to " PFX "\n", bb->instr_start, tgt); } } /* End this bb now */ bb->exit_target = opnd_get_pc(instr_get_target(bb->instr)); instrlist_append(bb->ilist, bb->instr); return false; /* end bb */ } return true; /* keep bb going */ } #ifdef X86 /* returns true if call is elided, * and false if not following due to hitting a limit or other reason */ static bool follow_direct_call(dcontext_t *dcontext, build_bb_t *bb, app_pc callee) { /* FIXME: This code should be reused in bb_process_convertible_indcall() * and in bb_process_call_direct() */ if (bb->follow_direct && !must_not_be_entered(callee) && bb->num_elide_call < DYNAMO_OPTION(max_elide_call) && (DYNAMO_OPTION(elide_back_calls) || bb->cur_pc <= callee)) { if (check_new_page_jmp(dcontext, bb, callee)) { bb->num_elide_call++; STATS_INC(total_elided_calls); STATS_TRACK_MAX(max_elided_calls, bb->num_elide_call); bb->cur_pc = callee; BBPRINT(bb, 4, " continuing in callee at " PFX "\n", bb->cur_pc); return true; /* keep bb going in callee */ } else { BBPRINT(bb, 3, " NOT following direct (or converted) call from " PFX " to " PFX "\n", bb->instr_start, callee); } } else { BBPRINT(bb, 3, " NOT attempting to follow call from " PFX " to " PFX "\n", bb->instr_start, callee); } return false; /* stop bb */ } #endif /* X86 */ static inline void bb_stop_prior_to_instr(dcontext_t *dcontext, build_bb_t *bb, bool appended) { if (appended) instrlist_remove(bb->ilist, bb->instr); instr_destroy(dcontext, bb->instr); bb->instr = NULL; bb->cur_pc = bb->instr_start; } /* returns true to indicate "elide and continue" and false to indicate "end bb now" */ static inline bool bb_process_call_direct(dcontext_t *dcontext, build_bb_t *bb) { byte *callee = (byte *)opnd_get_pc(instr_get_target(bb->instr)); #ifdef CUSTOM_TRACES_RET_REMOVAL if (callee == bb->instr_start + 5) { LOG(THREAD, LOG_INTERP, 4, "found call to next instruction\n"); } else dcontext->num_calls++; #endif STATS_INC(num_all_calls); BBPRINT(bb, 4, "interp: direct call at " PFX "\n", bb->instr_start); if (leave_call_native(callee)) { BBPRINT(bb, 3, "interp: NOT inlining or mangling call to " PFX "\n", callee); /* Case 8711: coarse-grain can't handle non-exit cti. * If we allow this fragment to be coarse we must kill the freeze * nudge thread! */ bb->flags &= ~FRAG_COARSE_GRAIN; STATS_INC(coarse_prevent_cti); bb_add_native_direct_xfer(dcontext, bb, true /*appended*/); return true; /* keep bb going, w/o inlining call */ } else { if (DYNAMO_OPTION(coarse_split_calls) && DYNAMO_OPTION(coarse_units) && TEST(FRAG_COARSE_GRAIN, bb->flags)) { if (instrlist_first(bb->ilist) != bb->instr) { /* have call be in its own bb */ bb_stop_prior_to_instr(dcontext, bb, true /*appended already*/); return false; /* stop bb */ } else { /* single-call fine-grained bb */ bb->flags &= ~FRAG_COARSE_GRAIN; STATS_INC(coarse_prevent_cti); } } /* FIXME: use follow_direct_call() */ if (bb->follow_direct && !must_not_be_entered(callee) && bb->num_elide_call < DYNAMO_OPTION(max_elide_call) && (DYNAMO_OPTION(elide_back_calls) || bb->cur_pc <= callee)) { if (check_new_page_jmp(dcontext, bb, callee)) { bb->num_elide_call++; STATS_INC(total_elided_calls); STATS_TRACK_MAX(max_elided_calls, bb->num_elide_call); bb->cur_pc = callee; BBPRINT(bb, 4, " continuing in callee at " PFX "\n", bb->cur_pc); return true; /* keep bb going */ } } BBPRINT(bb, 3, " NOT following direct call from " PFX " to " PFX "\n", bb->instr_start, callee); /* End this bb now */ if (instr_is_cbr(bb->instr)) { /* Treat as cbr, not call */ instr_exit_branch_set_type(bb->instr, instr_branch_type(bb->instr)); } else { bb->exit_target = callee; } return false; /* end bb now */ } return true; /* keep bb going */ } #ifdef WINDOWS /* We check if the instrs call, mov, and sysenter are * "call (%xdx); mov %xsp -> %xdx" or "call %xdx; mov %xsp -> %xdx" * and "sysenter". */ bool instr_is_call_sysenter_pattern(instr_t *call, instr_t *mov, instr_t *sysenter) { instr_t *instr; if (call == NULL || mov == NULL || sysenter == NULL) return false; if (instr_is_meta(call) || instr_is_meta(mov) || instr_is_meta(sysenter)) return false; if (instr_get_next(call) != mov || instr_get_next(mov) != sysenter) return false; /* check sysenter */ if (instr_get_opcode(sysenter) != OP_sysenter) return false; /* FIXME Relax the pattern matching on the "mov; call" pair so that small * changes in the register dataflow and call construct are tolerated. */ /* Did we find a "mov %xsp -> %xdx"? */ instr = mov; if (!(instr != NULL && instr_get_opcode(instr) == OP_mov_ld && instr_num_srcs(instr) == 1 && instr_num_dsts(instr) == 1 && opnd_is_reg(instr_get_dst(instr, 0)) && opnd_get_reg(instr_get_dst(instr, 0)) == REG_XDX && opnd_is_reg(instr_get_src(instr, 0)) && opnd_get_reg(instr_get_src(instr, 0)) == REG_XSP)) { return false; } /* Did we find a "call (%xdx) or "call %xdx" that's already marked * for ind->direct call conversion? */ instr = call; if (!(instr != NULL && TEST(INSTR_IND_CALL_DIRECT, instr->flags) && instr_is_call_indirect(instr) && /* The 2nd src operand should always be %xsp. */ opnd_is_reg(instr_get_src(instr, 1)) && opnd_get_reg(instr_get_src(instr, 1)) == REG_XSP && /* Match 'call (%xdx)' for post-SP2. */ ((opnd_is_near_base_disp(instr_get_src(instr, 0)) && opnd_get_base(instr_get_src(instr, 0)) == REG_XDX && opnd_get_disp(instr_get_src(instr, 0)) == 0) || /* Match 'call %xdx' for pre-SP2. */ (opnd_is_reg(instr_get_src(instr, 0)) && opnd_get_reg(instr_get_src(instr, 0)) == REG_XDX)))) { return false; } return true; } /* Walk up from the bb->instr and verify that the preceding instructions * match the pattern that we expect to precede a sysenter. */ static instr_t * bb_verify_sysenter_pattern(dcontext_t *dcontext, build_bb_t *bb) { /* Walk back up 2 instructions and verify that there's a * "call (%xdx); mov %xsp -> %xdx" or "call %xdx; mov %xsp -> %xdx" * just prior to the sysenter. * We use "xsp" and "xdx" to be ready for x64 sysenter though we don't * expect to see it. */ instr_t *mov, *call; mov = instr_get_prev_expanded(dcontext, bb->ilist, bb->instr); if (mov == NULL) return NULL; call = instr_get_prev_expanded(dcontext, bb->ilist, mov); if (call == NULL) return NULL; if (!instr_is_call_sysenter_pattern(call, mov, bb->instr)) { BBPRINT(bb, 3, "bb_verify_sysenter_pattern -- pattern didn't match\n"); return NULL; } return call; } /* Only used for the Borland SEH exemption. */ /* FIXME - we can't really tell a push from a pop since both are typically a * mov to fs:[0], but double processing doesn't hurt. */ /* NOTE we don't see dynamic SEH frame pushes, we only see the first SEH push * per mov -> fs:[0] instruction in the app. So we don't see modified in place * handler addresses (see at_Borland_SEH_rct_exemption()) or handler addresses * that are passed into a shared routine that sets up the frame (not yet seen, * note that MS dlls that have a _SEH_prolog hardcode the handler address in * the _SEH_prolog routine, only the data is passed in). */ static void bb_process_SEH_push(dcontext_t *dcontext, build_bb_t *bb, void *value) { if (value == NULL || value == (void *)PTR_UINT_MINUS_1) { /* could be popping off the last frame (leaving -1) of the SEH stack */ STATS_INC(num_endlist_SEH_write); ASSERT_CURIOSITY(value != NULL); return; } LOG(THREAD, LOG_INTERP, 3, "App moving " PFX " to fs:[0]\n", value); # ifdef RETURN_AFTER_CALL if (DYNAMO_OPTION(borland_SEH_rct)) { /* xref case 5752, the Borland compiler SEH implementation uses a push * imm ret motif for fall through to the finally of a try finally block * (very similar to what the Microsoft NT at_SEH_rct_exception() is * doing). The layout will always look like this : * push e: (imm32) (e should be in the .E/.F table) * a: * ... * b: ret * c: jmp rel32 (c should be in the .E/.F table) * d: jmp a: (rel8/32) * ... (usually nothing) * e: * (where ret at b is targeting e, or a valid after call). The * exception dispatcher calls c (the SEH frame has c as the handler) * which jmps to the exception handler which, in turn, calls d to * execute the finally block. Fall through is as shown above. So, * we see a .E violation for the handlers call to d and a .C violation * for the fall trough case of the ret @ b targeting e. We may also * see a .E violation for a call to a as sometimes the handler computes * the target of the jmp @ d an passes that to a different exception * handler. * * For try-except we see the following layout : * I've only seen jmp ind in the case that led to needing * at_Borland_SEH_rct_exemption() to be added, not that * it makes any difference. * [ jmp z: (rel8/32) || (rarely) ret || (very rarely) jmp ind] * x: jmp rel32 (x should be in the .E/.F table) * y: * ... * call rel32 * [z: ... || ret ] * Though there may be other optimized layouts (the ret instead of the * jmp z: is one such) so we may not want to rely on anything other * then x y. The exception dispatcher calls x (the SEH frame has x as * the handler) which jmps to the exception handler which, in turn, * jmps to y to execute the except block. We see a .F violation from * the handler's jmp to y. at_Borland_SEH_rct_exemption() covers a * case where the address of x (and thus y) in an existing SEH frame * is changed in place instead of popping and pushing a new frame. * * All addresses (rel and otherwise) should be in the same module. So * we need to recognize the patter and add d:/y: to the .E/.F table * as well as a: (sometimes the handler calculates the target of d and * passes that up to a higher level routine, though I don't see the * point) and add e: to the .C table. * * It would be preferable to handle these exemptions reactively at * the violation point, but unfortunately, by the time we get to the * violation the SEH frame information has been popped off the stack * and is lost, so we have to do it pre-emptively here (pattern * matching at violation time has proven to difficult in the face of * certain compiler optimizations). See at_Borland_SEH_rct_exemption() * in callback.c, that could handle all ind branches to y and ind calls * to d (see below) at an acceptable level of security if we desired. * Handling the ret @ b to e reactively would require the ability to * recreate the exact src cti (so we can use the addr of the ret to * pattern match) at the violation point (something that can't always * currently be done, reset flushing etc.). Handling the ind call to * a (which I've never acutally seen, though I've seen the address * computed and it looks like it could likely be hit) reactively is * more tricky. Prob. the only way to handle that is to allow .E/.F * transistions to any address after a push imm32 of an address in the * same module, but that might be too permissive. FIXME - should still * revisit doing the exemptions reactively at some point, esp. once we * can reliably get the src cti. */ extern bool seen_Borland_SEH; /* set for callback.c */ /* First read in the SEH frame, this is the observed structure and * the first two fields (which are all that we use) are constrained by * ntdll exception dispatcher (see EXCEPTION_REGISTRATION decleration * in ntdll.h). */ /* FIXME - could just use EXCEPTION_REGISTRATION period since all we * need is the handler address and it would allow simpler curiosity * [see 8181] below. If, as is expected, other options make use of * this routine we'll probably have one shared get of the SEH frame * anyways. */ typedef struct _borland_seh_frame_t { EXCEPTION_REGISTRATION reg; reg_t xbp; /* not used by us */ } borland_seh_frame_t; borland_seh_frame_t frame; /* will hold [b,e] or [x-1,y] */ byte target_buf[RET_0_LENGTH + 2 * JMP_LONG_LENGTH]; app_pc handler_jmp_target = NULL; if (!d_r_safe_read(value, sizeof(frame), &frame)) { /* We already checked for NULL and -1 above so this should be * a valid SEH frame. Xref 8181, borland_seh_frame_t struct is * bigger then EXCEPTION_REGISTRATION (which is all that is * required) so verify smaller size is readable. */ ASSERT_CURIOSITY( sizeof(EXCEPTION_REGISTRATION) < sizeof(frame) && d_r_safe_read(value, sizeof(EXCEPTION_REGISTRATION), &frame)); goto post_borland; } /* frame.reg.handler is c or y, read extra prior bytes to look for b */ if (!d_r_safe_read((app_pc)frame.reg.handler - RET_0_LENGTH, sizeof(target_buf), target_buf)) { goto post_borland; } if (is_jmp_rel32(&target_buf[RET_0_LENGTH], (app_pc)frame.reg.handler, &handler_jmp_target)) { /* we have a possible match, now do the more expensive checking */ app_pc base; LOG(THREAD, LOG_INTERP, 3, "Read possible borland SEH frame @" PFX "\n\t" "next=" PFX " handler=" PFX " xbp=" PFX "\n\t", value, frame.reg.prev, frame.reg.handler, frame.xbp); DOLOG(3, LOG_INTERP, { dump_buffer_as_bytes(THREAD, target_buf, sizeof(target_buf), 0); }); /* optimize check if we've already processed this frame once */ if ((DYNAMO_OPTION(rct_ind_jump) != OPTION_DISABLED || DYNAMO_OPTION(rct_ind_call) != OPTION_DISABLED) && rct_ind_branch_target_lookup( dcontext, (app_pc)frame.reg.handler + JMP_LONG_LENGTH)) { /* we already processed this SEH frame once, this is prob. a * frame pop, no need to continue */ STATS_INC(num_borland_SEH_dup_frame); LOG(THREAD, LOG_INTERP, 3, "Processing duplicate Borland SEH frame\n"); goto post_borland; } base = get_module_base((app_pc)frame.reg.handler); STATS_INC(num_borland_SEH_initial_match); /* Perf opt, we use the cheaper get_allocation_base() below instead * of get_module_base(). We are checking the result against a * known module base (base) so no need to duplicate the is module * check. FIXME - the checks prob. aren't even necessary given the * later is_in_code_section checks. Xref case 8171. */ /* FIXME - (perf) we could cache the region from the first * is_in_code_section() call and check against that before falling * back on is_in_code_section in case of multiple code sections. */ if (base != NULL && get_allocation_base(handler_jmp_target) == base && get_allocation_base(bb->instr_start) == base && /* FIXME - with -rct_analyze_at_load we should be able to * verify that frame->handler (x: c:) is on the .E/.F * table already. We could also try to match known pre x: * post y: patterns. */ is_in_code_section(base, bb->instr_start, NULL, NULL) && is_in_code_section(base, handler_jmp_target, NULL, NULL) && is_range_in_code_section(base, (app_pc)frame.reg.handler, (app_pc)frame.reg.handler + JMP_LONG_LENGTH + 1, NULL, NULL)) { app_pc finally_target; byte push_imm_buf[PUSH_IMM32_LENGTH]; DEBUG_DECLARE(bool ok;) /* we have a match, add handler+JMP_LONG_LENGTH (y: d:) * to .E/.F table */ STATS_INC(num_borland_SEH_try_match); LOG(THREAD, LOG_INTERP, 2, "Found Borland SEH frame adding " PFX " to .E/.F table\n", (app_pc)frame.reg.handler + JMP_LONG_LENGTH); if ((DYNAMO_OPTION(rct_ind_jump) != OPTION_DISABLED || DYNAMO_OPTION(rct_ind_call) != OPTION_DISABLED)) { d_r_mutex_lock(&rct_module_lock); rct_add_valid_ind_branch_target( dcontext, (app_pc)frame.reg.handler + JMP_LONG_LENGTH); d_r_mutex_unlock(&rct_module_lock); } /* we set this as an enabler for another exemption in * callback .C, see notes there */ if (!seen_Borland_SEH) { SELF_UNPROTECT_DATASEC(DATASEC_RARELY_PROT); seen_Borland_SEH = true; SELF_PROTECT_DATASEC(DATASEC_RARELY_PROT); } /* case 8648: used to decide which RCT entries to persist */ DEBUG_DECLARE(ok =) os_module_set_flag(base, MODULE_HAS_BORLAND_SEH); ASSERT(ok); /* look for .C addresses for try finally */ if (target_buf[0] == RAW_OPCODE_ret && (is_jmp_rel32(&target_buf[RET_0_LENGTH + JMP_LONG_LENGTH], (app_pc)frame.reg.handler + JMP_LONG_LENGTH, &finally_target) || is_jmp_rel8(&target_buf[RET_0_LENGTH + JMP_LONG_LENGTH], (app_pc)frame.reg.handler + JMP_LONG_LENGTH, &finally_target)) && d_r_safe_read(finally_target - sizeof(push_imm_buf), sizeof(push_imm_buf), push_imm_buf) && push_imm_buf[0] == RAW_OPCODE_push_imm32) { app_pc push_val = *(app_pc *)&push_imm_buf[1]; /* do a few more, expensive, sanity checks */ /* FIXME - (perf) see earlier note on get_allocation_base() * and is_in_code_section() usage. */ if (get_allocation_base(finally_target) == base && is_in_code_section(base, finally_target, NULL, NULL) && get_allocation_base(push_val) == base && /* FIXME - could also check that push_val is in * .E/.F table, at least for -rct_analyze_at_load */ is_in_code_section(base, push_val, NULL, NULL)) { /* Full match, add push_val (e:) to the .C table * and finally_target (a:) to the .E/.F table */ STATS_INC(num_borland_SEH_finally_match); LOG(THREAD, LOG_INTERP, 2, "Found Borland SEH finally frame adding " PFX " to" " .C table and " PFX " to .E/.F table\n", push_val, finally_target); if ((DYNAMO_OPTION(rct_ind_jump) != OPTION_DISABLED || DYNAMO_OPTION(rct_ind_call) != OPTION_DISABLED)) { d_r_mutex_lock(&rct_module_lock); rct_add_valid_ind_branch_target(dcontext, finally_target); d_r_mutex_unlock(&rct_module_lock); } if (DYNAMO_OPTION(ret_after_call)) { fragment_add_after_call(dcontext, push_val); } } else { ASSERT_CURIOSITY(false && "partial borland seh finally match"); } } } } } post_borland: # endif /* RETURN_AFTER_CALL */ return; } /* helper routine for bb_process_fs_ref * return true if bb should be continued, false if it shouldn't */ static bool bb_process_fs_ref_opnd(dcontext_t *dcontext, build_bb_t *bb, opnd_t dst, bool *is_to_fs0) { ASSERT(is_to_fs0 != NULL); *is_to_fs0 = false; if (opnd_is_far_base_disp(dst) && /* FIXME - check size? */ opnd_get_segment(dst) == SEG_FS) { /* is a write to fs:[*] */ if (bb->instr_start != bb->start_pc) { /* Not first instruction in the bb, end bb before this * instruction, so we can see it as the first instruction of a * new bb where we can use the register state. */ /* As is, always ending the bb here has a mixed effect on mem usage * with default options. We do end up with slightly more bb's * (and associated bookeeping costs), but frequently with MS dlls * we reduce code cache dupliaction from jmp/call ellision * (_SEH_[Pro,Epi]log otherwise ends up frequently duplicated for * instance). */ /* FIXME - we must stop the bb here even if there's already * a bb built for the next instruction, as we have to have * reproducible bb building for recreate app state. We should * only get here through code duplication (typically jmp/call * inlining, though can also be through multiple entry points into * the same block of non cti instructions). */ bb_stop_prior_to_instr(dcontext, bb, false /*not appended yet*/); return false; /* stop bb */ } /* Only process the push if building a new bb for cache, can't check * this any earlier since have to preserve bb building/ending behavior * even when not for cache (for recreation etc.). */ if (bb->app_interp) { /* check is write to fs:[0] */ /* XXX: this won't identify all memory references (need to switch to * instr_compute_address_ex_priv() in order to handle VSIB) but the * current usage is just to identify the Borland pattern so that's ok. */ if (opnd_compute_address_priv(dst, get_mcontext(dcontext)) == NULL) { /* we have new mov to fs:[0] */ *is_to_fs0 = true; } } } return true; } /* While currently only used for Borland SEH exemptions, this analysis could * also be helpful for other SEH tasks (xref case 5824). */ static bool bb_process_fs_ref(dcontext_t *dcontext, build_bb_t *bb) { ASSERT(DYNAMO_OPTION(process_SEH_push) && instr_get_prefix_flag(bb->instr, PREFIX_SEG_FS)); /* If this is the first instruction of a bb for the cache we * want to fully decode it, check if it's pushing an SEH frame * and, if so, pass it to the SEH checking routines (currently * just used for the Borland SEH rct handling). If this is not * the first instruction of the bb then we want to stop the bb * just before this instruction so that when we do process this * instruction it will be the first in the bb (allowing us to * use the register state). */ if (!bb->full_decode) { instr_decode(dcontext, bb->instr); /* is possible this is an invalid instr that made it through the fast * decode, FIXME is there a better way to handle this? */ if (!instr_valid(bb->instr)) { ASSERT_NOT_TESTED(); if (bb->cur_pc == NULL) bb->cur_pc = bb->instr_start; bb_process_invalid_instr(dcontext, bb); return false; /* stop bb */ } ASSERT(instr_get_prefix_flag(bb->instr, PREFIX_SEG_FS)); } /* expect to see only simple mov's to fs:[0] for new SEH frames * FIXME - might we see other types we'd want to intercept? * do we want to proccess pop instructions (usually just for removing * a frame)? */ if (instr_get_opcode(bb->instr) == OP_mov_st) { bool is_to_fs0; opnd_t dst = instr_get_dst(bb->instr, 0); if (!bb_process_fs_ref_opnd(dcontext, bb, dst, &is_to_fs0)) return false; /* end bb */ /* Only process the push if building a new bb for cache, can't check * this any earlier since have to preserve bb building/ending behavior * even when not for cache (for recreation etc.). */ if (bb->app_interp) { if (is_to_fs0) { ptr_int_t value = 0; opnd_t src = instr_get_src(bb->instr, 0); if (opnd_is_immed_int(src)) { value = opnd_get_immed_int(src); } else if (opnd_is_reg(src)) { value = reg_get_value_priv(opnd_get_reg(src), get_mcontext(dcontext)); } else { ASSERT_NOT_REACHED(); } STATS_INC(num_SEH_pushes_processed); LOG(THREAD, LOG_INTERP, 3, "found mov to fs:[0] @ " PFX "\n", bb->instr_start); bb_process_SEH_push(dcontext, bb, (void *)value); } else { STATS_INC(num_fs_movs_not_SEH); } } } # if defined(DEBUG) && defined(INTERNAL) else if (INTERNAL_OPTION(check_for_SEH_push)) { /* Debug build Sanity check that we aren't missing SEH frame pushes */ int i; int num_dsts = instr_num_dsts(bb->instr); for (i = 0; i < num_dsts; i++) { bool is_to_fs0; opnd_t dst = instr_get_dst(bb->instr, i); if (!bb_process_fs_ref_opnd(dcontext, bb, dst, &is_to_fs0)) { STATS_INC(num_process_SEH_bb_early_terminate_debug); return false; /* end bb */ } /* common case is pop instructions to fs:[0] when popping an * SEH frame stored on tos */ if (is_to_fs0) { if (instr_get_opcode(bb->instr) == OP_pop) { LOG(THREAD, LOG_INTERP, 4, "found pop to fs:[0] @ " PFX "\n", bb->instr_start); STATS_INC(num_process_SEH_pop_fs0); } else { /* an unexpected SEH frame push */ LOG(THREAD, LOG_INTERP, 1, "found unexpected write to fs:[0] @" PFX "\n", bb->instr_start); DOLOG(1, LOG_INTERP, { d_r_loginst(dcontext, 1, bb->instr, ""); }); ASSERT_CURIOSITY(!is_to_fs0); } } } } # endif return true; /* continue bb */ } #endif /* win32 */ #if defined(UNIX) && !defined(DGC_DIAGNOSTICS) && defined(X86) /* The basic strategy for mangling mov_seg instruction is: * For mov fs/gs => reg/[mem], simply mangle it to write * the app's fs/gs selector value into dst. * For mov reg/mem => fs/gs, we make it as the first instruction * of bb, and mark that bb not linked and has mov_seg instr, * and change that instruction to be a nop. * Then whenever before entering code cache, we check if that's the bb * has mov_seg. If yes, we will update the information we maintained * about the app's fs/gs. */ /* check if the basic block building should continue on a mov_seg instr. */ static bool bb_process_mov_seg(dcontext_t *dcontext, build_bb_t *bb) { reg_id_t seg; if (!INTERNAL_OPTION(mangle_app_seg)) return true; /* continue bb */ /* if it is a read, we only need mangle the instruction. */ ASSERT(instr_num_srcs(bb->instr) == 1); if (opnd_is_reg(instr_get_src(bb->instr, 0)) && reg_is_segment(opnd_get_reg(instr_get_src(bb->instr, 0)))) return true; /* continue bb */ /* it is an update, we need set to be the first instr of bb */ ASSERT(instr_num_dsts(bb->instr) == 1); ASSERT(opnd_is_reg(instr_get_dst(bb->instr, 0))); seg = opnd_get_reg(instr_get_dst(bb->instr, 0)); ASSERT(reg_is_segment(seg)); /* we only need handle fs/gs */ if (seg != SEG_GS && seg != SEG_FS) return true; /* continue bb */ /* if no private loader, we only need mangle the non-tls seg */ if (seg == IF_X64_ELSE(SEG_FS, SEG_FS) && !INTERNAL_OPTION(private_loader)) return true; /* continue bb */ if (bb->instr_start == bb->start_pc) { /* the first instruction, we can continue build bb. */ /* this bb cannot be part of trace! */ bb->flags |= FRAG_CANNOT_BE_TRACE; bb->flags |= FRAG_HAS_MOV_SEG; return true; /* continue bb */ } LOG(THREAD, LOG_INTERP, 3, "ending bb before mov_seg\n"); /* Set cur_pc back to the start of this instruction and delete this * instruction from the bb ilist. */ bb->cur_pc = instr_get_raw_bits(bb->instr); instrlist_remove(bb->ilist, bb->instr); instr_destroy(dcontext, bb->instr); /* Set instr to NULL in order to get translation of exit cti correct. */ bb->instr = NULL; /* this block must be the last one in a trace * breaking traces here shouldn't be a perf issue b/c this is so rare, * it should happen only once per thread on setting up tls. */ bb->flags |= FRAG_MUST_END_TRACE; return false; /* stop bb here */ } #endif /* UNIX && X86 */ /* Returns true to indicate that ignorable syscall processing is completed * with *continue_bb indicating if the bb should be continued or not. * When returning false, continue_bb isn't pertinent. */ static bool bb_process_ignorable_syscall(dcontext_t *dcontext, build_bb_t *bb, int sysnum, bool *continue_bb) { STATS_INC(ignorable_syscalls); BBPRINT(bb, 3, "found ignorable system call 0x%04x\n", sysnum); #ifdef WINDOWS if (get_syscall_method() != SYSCALL_METHOD_SYSENTER) { DOCHECK(1, { if (get_syscall_method() == SYSCALL_METHOD_WOW64) ASSERT_NOT_TESTED(); }); if (continue_bb != NULL) *continue_bb = true; return true; } else { /* Can we continue interp after the sysenter at the instruction * after the call to sysenter? */ instr_t *call = bb_verify_sysenter_pattern(dcontext, bb); if (call != NULL) { /* If we're continuing code discovery at the after-call address, * change the cur_pc to continue at the after-call addr. This is * safe since the preceding call is in the fragment and * %xsp/(%xsp) hasn't changed since the call. Obviously, we assume * that the sysenter breaks control flow in fashion such any * instruction that follows it isn't reached by DR. */ if (DYNAMO_OPTION(ignore_syscalls_follow_sysenter)) { bb->cur_pc = instr_get_raw_bits(call) + instr_length(dcontext, call); if (continue_bb != NULL) *continue_bb = true; return true; } else { /* End this bb now. We set the exit target so that control * skips the vsyscall 'ret' that's executed natively after the * syscall and ends up at the correct place. */ /* FIXME Assigning exit_target causes the fragment to end * with a direct exit stub to the after-call address, which * is fine. If bb->exit_target < bb->start_pc, the future * fragment for exit_target is marked as a trace head which * isn't intended. A potentially undesirable side effect * is that exit_target's fragment can't be included in * trace for start_pc. */ bb->exit_target = instr_get_raw_bits(call) + instr_length(dcontext, call); if (continue_bb != NULL) *continue_bb = false; return true; } } STATS_INC(ignorable_syscalls_failed_sysenter_pattern); /* Pattern match failed but the syscall is ignorable so maybe we * can try shared syscall? */ /* Decrement the stat to prevent double counting. We rarely expect to hit * this case. */ STATS_DEC(ignorable_syscalls); return false; } #elif defined(MACOS) if (instr_get_opcode(bb->instr) == OP_sysenter) { /* To continue after the sysenter we need to go to the ret ibl, as user-mode * sysenter wrappers put the retaddr into edx as the post-kernel continuation. */ bb->exit_type |= LINK_INDIRECT | LINK_RETURN; bb->ibl_branch_type = IBL_RETURN; bb->exit_target = get_ibl_routine(dcontext, get_ibl_entry_type(bb->exit_type), DEFAULT_IBL_BB(), bb->ibl_branch_type); LOG(THREAD, LOG_INTERP, 4, "sysenter exit target = " PFX "\n", bb->exit_target); if (continue_bb != NULL) *continue_bb = false; } else if (continue_bb != NULL) *continue_bb = true; return true; #else if (continue_bb != NULL) *continue_bb = true; return true; #endif } #ifdef WINDOWS /* Process a syscall that is executed via shared syscall. */ static void bb_process_shared_syscall(dcontext_t *dcontext, build_bb_t *bb, int sysnum) { ASSERT(DYNAMO_OPTION(shared_syscalls)); DODEBUG({ if (ignorable_system_call(sysnum, bb->instr, NULL)) STATS_INC(ignorable_syscalls); else STATS_INC(optimizable_syscalls); }); BBPRINT(bb, 3, "found %soptimizable system call 0x%04x\n", INTERNAL_OPTION(shared_eq_ignore) ? "ignorable-" : "", sysnum); LOG(THREAD, LOG_INTERP, 3, "ending bb at syscall & NOT removing the interrupt itself\n"); /* Mark the instruction as pointing to shared syscall */ bb->instr->flags |= INSTR_SHARED_SYSCALL; /* this block must be the last one in a trace */ bb->flags |= FRAG_MUST_END_TRACE; /* we redirect all optimizable syscalls to a single shared piece of code. * Once a fragment reaches the shared syscall code, it can be safely * deleted, for example, if the thread is interrupted for a callback and * DR needs to delete fragments for cache management. * * Note that w/shared syscall, syscalls can be executed from TWO * places -- shared_syscall and do_syscall. */ bb->exit_target = shared_syscall_routine(dcontext); /* make sure translation for ending jmp ends up right, mangle will * remove this instruction, so set to NULL so translation does the * right thing */ bb->instr = NULL; } #endif /* WINDOWS */ #ifdef ARM /* This routine walks back to find the IT instr for the current IT block * and the position of instr in the current IT block, and returns whether * instr is the last instruction in the block. */ static bool instr_is_last_in_it_block(instr_t *instr, instr_t **it_out, uint *pos_out) { instr_t *it; int num_instrs; ASSERT(instr != NULL && instr_get_isa_mode(instr) == DR_ISA_ARM_THUMB && instr_is_predicated(instr) && instr_is_app(instr)); /* walk backward to find the IT instruction */ for (it = instr_get_prev(instr), num_instrs = 1; /* meta and app instrs are treated identically here */ it != NULL && num_instrs <= 4 /* max 4 instr in an IT block */; it = instr_get_prev(it)) { if (instr_is_label(it)) continue; if (instr_get_opcode(it) == OP_it) break; num_instrs++; } ASSERT(it != NULL && instr_get_opcode(it) == OP_it); ASSERT(num_instrs <= instr_it_block_get_count(it)); if (it_out != NULL) *it_out = it; if (pos_out != NULL) *pos_out = num_instrs - 1; /* pos starts from 0 */ if (num_instrs == instr_it_block_get_count(it)) return true; return false; } static void adjust_it_instr_for_split(dcontext_t *dcontext, instr_t *it, uint pos) { dr_pred_type_t block_pred[IT_BLOCK_MAX_INSTRS]; uint i, block_count = instr_it_block_get_count(it); byte firstcond[2], mask[2]; DEBUG_DECLARE(bool ok;) ASSERT(pos < instr_it_block_get_count(it) - 1); for (i = 0; i < block_count; i++) block_pred[i] = instr_it_block_get_pred(it, i); DOCHECK(CHKLVL_ASSERTS, { instr_t *instr; for (instr = instr_get_next_app(it), i = 0; instr != NULL; instr = instr_get_next_app(instr)) { ASSERT(instr_is_predicated(instr) && i <= pos); ASSERT(block_pred[i++] == instr_get_predicate(instr)); } }); DEBUG_DECLARE(ok =) instr_it_block_compute_immediates( block_pred[0], (pos > 0) ? block_pred[1] : DR_PRED_NONE, (pos > 1) ? block_pred[2] : DR_PRED_NONE, DR_PRED_NONE, /* at most 3 preds */ &firstcond[0], &mask[0]); ASSERT(ok); DOCHECK(CHKLVL_ASSERTS, { DEBUG_DECLARE(ok =) instr_it_block_compute_immediates( block_pred[pos + 1], (block_count > pos + 2) ? block_pred[pos + 2] : DR_PRED_NONE, (block_count > pos + 3) ? block_pred[pos + 3] : DR_PRED_NONE, DR_PRED_NONE, /* at most 3 preds */ &firstcond[1], &mask[1]); ASSERT(ok); }); /* firstcond should be unchanged */ ASSERT(opnd_get_immed_int(instr_get_src(it, 0)) == firstcond[0]); instr_set_src(it, 1, OPND_CREATE_INT(mask[0])); LOG(THREAD, LOG_INTERP, 3, "ending bb in an IT block & adjusting the IT instruction\n"); /* FIXME i#1669: NYI on passing split it block info to next bb */ ASSERT_NOT_IMPLEMENTED(false); } #endif /* ARM */ static bool bb_process_non_ignorable_syscall(dcontext_t *dcontext, build_bb_t *bb, int sysnum) { BBPRINT(bb, 3, "found non-ignorable system call 0x%04x\n", sysnum); STATS_INC(non_ignorable_syscalls); bb->exit_type |= LINK_NI_SYSCALL; /* destroy the interrupt instruction */ LOG(THREAD, LOG_INTERP, 3, "ending bb at syscall & removing the interrupt itself\n"); /* Indicate that this is a non-ignorable syscall so mangle will remove */ /* FIXME i#1551: maybe we should union int80 and svc as both are inline syscall? */ #ifdef UNIX if (instr_get_opcode(bb->instr) == IF_X86_ELSE(OP_int, OP_svc)) { # if defined(MACOS) && defined(X86) int num = instr_get_interrupt_number(bb->instr); if (num == 0x81 || num == 0x82) { bb->exit_type |= LINK_SPECIAL_EXIT; bb->instr->flags |= INSTR_BRANCH_SPECIAL_EXIT; } else { ASSERT(num == 0x80); # endif /* MACOS && X86 */ bb->exit_type |= LINK_NI_SYSCALL_INT; bb->instr->flags |= INSTR_NI_SYSCALL_INT; # ifdef MACOS } # endif } else #endif bb->instr->flags |= INSTR_NI_SYSCALL; #ifdef ARM /* we assume all conditional syscalls are treated as non-ignorable */ if (instr_is_predicated(bb->instr)) { instr_t *it; uint pos; ASSERT(instr_is_syscall(bb->instr)); bb->svc_pred = instr_get_predicate(bb->instr); if (instr_get_isa_mode(bb->instr) == DR_ISA_ARM_THUMB && !instr_is_last_in_it_block(bb->instr, &it, &pos)) { /* FIXME i#1669: we violate the transparency and clients will see * modified IT instr. We should adjust the IT instr at mangling * stage after client instrumentation, but that is complex. */ adjust_it_instr_for_split(dcontext, it, pos); } } #endif /* Set instr to NULL in order to get translation of exit cti correct. */ bb->instr = NULL; /* this block must be the last one in a trace */ bb->flags |= FRAG_MUST_END_TRACE; return false; /* end bb now */ } /* returns true to indicate "continue bb" and false to indicate "end bb now" */ static inline bool bb_process_syscall(dcontext_t *dcontext, build_bb_t *bb) { int sysnum; /* PR 307284: for simplicity do syscall/int processing post-client. * We give up on inlining but we can still use ignorable/shared syscalls * and trace continuation. */ if (bb->pass_to_client && !bb->post_client) return false; #ifdef DGC_DIAGNOSTICS if (TEST(FRAG_DYNGEN, bb->flags) && !is_dyngen_vsyscall(bb->instr_start)) { LOG(THREAD, LOG_INTERP, 1, "WARNING: syscall @ " PFX " in dyngen code!\n", bb->instr_start); } #endif BBPRINT(bb, 4, "interp: syscall @ " PFX "\n", bb->instr_start); check_syscall_method(dcontext, bb->instr); bb->flags |= FRAG_HAS_SYSCALL; /* if we can identify syscall number and it is an ignorable syscall, * we let bb keep going, else we end bb and flag it */ sysnum = find_syscall_num(dcontext, bb->ilist, bb->instr); #ifdef VMX86_SERVER DOSTATS({ if (instr_get_opcode(bb->instr) == OP_int && instr_get_interrupt_number(bb->instr) == VMKUW_SYSCALL_GATEWAY) { STATS_INC(vmkuw_syscall_sites); LOG(THREAD, LOG_SYSCALLS, 2, "vmkuw system call site: #=%d\n", sysnum); } }); #endif BBPRINT(bb, 3, "syscall # is %d\n", sysnum); if (sysnum != -1 && instrument_filter_syscall(dcontext, sysnum)) { BBPRINT(bb, 3, "client asking to intercept => pretending syscall # %d is -1\n", sysnum); sysnum = -1; } #ifdef ARM if (sysnum != -1 && instr_is_predicated(bb->instr)) { BBPRINT(bb, 3, "conditional system calls cannot be inlined => " "pretending syscall # %d is -1\n", sysnum); sysnum = -1; } #endif if (sysnum != -1 && DYNAMO_OPTION(ignore_syscalls) && ignorable_system_call(sysnum, bb->instr, NULL) #ifdef X86 /* PR 288101: On Linux we do not yet support inlined sysenter instrs as we * do not have in-cache support for the post-sysenter continuation: we rely * for now on very simple sysenter handling where d_r_dispatch uses asynch_target * to know where to go next. */ IF_LINUX(&&instr_get_opcode(bb->instr) != OP_sysenter) #endif /* X86 */ ) { bool continue_bb; if (bb_process_ignorable_syscall(dcontext, bb, sysnum, &continue_bb)) { if (!DYNAMO_OPTION(inline_ignored_syscalls)) continue_bb = false; return continue_bb; } } #ifdef WINDOWS if (sysnum != -1 && DYNAMO_OPTION(shared_syscalls) && optimizable_system_call(sysnum)) { bb_process_shared_syscall(dcontext, bb, sysnum); return false; } #endif /* Fall thru and handle as a non-ignorable syscall. */ return bb_process_non_ignorable_syscall(dcontext, bb, sysnum); } /* Case 3922: for wow64 we treat "call *fs:0xc0" as a system call. * Only sets continue_bb if it returns true. */ static bool bb_process_indcall_syscall(dcontext_t *dcontext, build_bb_t *bb, bool *continue_bb) { ASSERT(continue_bb != NULL); #ifdef WINDOWS if (instr_is_wow64_syscall(bb->instr)) { /* we could check the preceding instrs but we don't bother */ *continue_bb = bb_process_syscall(dcontext, bb); return true; } #endif return false; } /* returns true to indicate "continue bb" and false to indicate "end bb now" */ static inline bool bb_process_interrupt(dcontext_t *dcontext, build_bb_t *bb) { #if defined(DEBUG) || defined(INTERNAL) || defined(WINDOWS) int num = instr_get_interrupt_number(bb->instr); #endif /* PR 307284: for simplicity do syscall/int processing post-client. * We give up on inlining but we can still use ignorable/shared syscalls * and trace continuation. * PR 550752: we cannot end at int 0x2d: we live w/ client consequences */ if (bb->pass_to_client && !bb->post_client IF_WINDOWS(&&num != 0x2d)) return false; BBPRINT(bb, 3, "int 0x%x @ " PFX "\n", num, bb->instr_start); #ifdef WINDOWS if (num == 0x2b) { /* interrupt 0x2B signals return from callback */ /* end block here and come back to dynamo to perform interrupt */ bb->exit_type |= LINK_CALLBACK_RETURN; BBPRINT(bb, 3, "ending bb at cb ret & removing the interrupt itself\n"); /* Set instr to NULL in order to get translation of exit cti * correct. mangle will destroy the instruction */ bb->instr = NULL; bb->flags |= FRAG_MUST_END_TRACE; STATS_INC(num_int2b); return false; } else { SYSLOG_INTERNAL_INFO_ONCE("non-syscall, non-int2b 0x%x @ " PFX " from " PFX, num, bb->instr_start, bb->start_pc); } #endif /* WINDOWS */ return true; } /* If the current instr in the BB is an indirect call that can be converted into a * direct call, process it and return true, else, return false. * FIXME PR 288327: put in linux call* to vsyscall page */ static bool bb_process_convertible_indcall(dcontext_t *dcontext, build_bb_t *bb) { #ifdef X86 /* We perform several levels of checking, each increasingly more stringent * and expensive, with a false return should any fail. */ instr_t *instr; opnd_t src0; instr_t *call_instr; int call_src_reg; app_pc callee; bool vsyscall = false; /* Check if this BB can be extended and the instr is a (near) indirect call */ if (instr_get_opcode(bb->instr) != OP_call_ind) return false; /* Check if we have a "mov <imm> -> %reg; call %reg" or a * "mov <imm> -> %reg; call (%reg)" pair. First check for the call. */ /* The 'if' conditions are broken up to make the code more readable * while #ifdef-ing the WINDOWS case. It's still ugly though. */ instr = bb->instr; if (!( # ifdef WINDOWS /* Match 'call (%xdx)' for a post-SP2 indirect call to sysenter. */ (opnd_is_near_base_disp(instr_get_src(instr, 0)) && opnd_get_base(instr_get_src(instr, 0)) == REG_XDX && opnd_get_disp(instr_get_src(instr, 0)) == 0) || # endif /* Match 'call %reg'. */ opnd_is_reg(instr_get_src(instr, 0)))) return false; /* If there's no CTI in the BB, we can check if there are 5+ preceding * bytes and if they could hold a "mov" instruction. */ if (!TEST(FRAG_HAS_DIRECT_CTI, bb->flags) && bb->instr_start - 5 >= bb->start_pc) { byte opcode = *((byte *)bb->instr_start - 5); /* Check the opcode. Do we see a "mov ... -> %reg"? Valid opcodes are in * the 0xb8-0xbf range (Intel IA-32 ISA ref, v.2) and specify the * destination register, i.e., 0xb8 means that %xax is the destination. */ if (opcode < 0xb8 || opcode > 0xbf) return false; } /* Check the previous instruction -- is it really a "mov"? */ src0 = instr_get_src(instr, 0); call_instr = instr; instr = instr_get_prev_expanded(dcontext, bb->ilist, bb->instr); call_src_reg = opnd_is_near_base_disp(src0) ? opnd_get_base(src0) : opnd_get_reg(src0); if (instr == NULL || instr_get_opcode(instr) != OP_mov_imm || opnd_get_reg(instr_get_dst(instr, 0)) != call_src_reg) return false; /* For the general case, we don't try to optimize a call * thru memory -- just check that the call uses a register. */ callee = NULL; if (opnd_is_reg(src0)) { /* Extract the target address. */ callee = (app_pc)opnd_get_immed_int(instr_get_src(instr, 0)); # ifdef WINDOWS # ifdef PROGRAM_SHEPHERDING /* FIXME - is checking for on vsyscall page better or is checking == to * VSYSCALL_BOOTSTRAP_ADDR? Both are hacky. */ if (is_dyngen_vsyscall((app_pc)opnd_get_immed_int(instr_get_src(instr, 0)))) { LOG(THREAD, LOG_INTERP, 4, "Pre-SP2 style indirect call " "to sysenter found at " PFX "\n", bb->instr_start); STATS_INC(num_sysenter_indcalls); vsyscall = true; ASSERT(opnd_get_immed_int(instr_get_src(instr, 0)) == (ptr_int_t)VSYSCALL_BOOTSTRAP_ADDR); ASSERT(!use_ki_syscall_routines()); /* double check our determination */ } else # endif # endif STATS_INC(num_convertible_indcalls); } # ifdef WINDOWS /* Match the "call (%xdx)" to sysenter case for SP2-patched os's. Memory at * address VSYSCALL_BOOTSTRAP_ADDR (0x7ffe0300) holds the address of * KiFastSystemCall or (FIXME - not handled) on older platforms KiIntSystemCall. * FIXME It's unsavory to hard-code 0x7ffe0300, but the constant has little * context in an SP2 os. It's a hold-over from pre-SP2. */ else if (get_syscall_method() == SYSCALL_METHOD_SYSENTER && call_src_reg == REG_XDX && opnd_get_immed_int(instr_get_src(instr, 0)) == (ptr_int_t)VSYSCALL_BOOTSTRAP_ADDR) { /* Extract the target address. We expect that the memory read using the * value in the immediate field is ok as it's the vsyscall page * which 1) cannot be made unreadable and 2) cannot be made writable so * the stored value will not change. Of course, it's possible that the * os could change the page contents. */ callee = (app_pc) * ((ptr_uint_t *)opnd_get_immed_int(instr_get_src(instr, 0))); if (get_app_sysenter_addr() == NULL) { /* For the first call* we've yet to decode an app syscall, yet we * cannot have later recreations have differing behavior, so we must * handle that case (even though it doesn't matter performance-wise * as the first call* is usually in runtime init code that's * executed once). So we do a raw byte compare to: * ntdll!KiFastSystemCall: * 7c82ed50 8bd4 mov xdx,xsp * 7c82ed52 0f34 sysenter */ uint raw; if (!d_r_safe_read(callee, sizeof(raw), &raw) || raw != 0x340fd48b) callee = NULL; } else { /* The callee should be a 2 byte "mov %xsp -> %xdx" followed by the * sysenter -- check the sysenter's address as 2 bytes past the callee. */ if (callee + 2 != get_app_sysenter_addr()) callee = NULL; } vsyscall = (callee != NULL); ASSERT(use_ki_syscall_routines()); /* double check our determination */ DODEBUG({ if (callee == NULL) ASSERT_CURIOSITY(false && "call* to vsyscall unexpected mismatch"); else { LOG(THREAD, LOG_INTERP, 4, "Post-SP2 style indirect call " "to sysenter found at " PFX "\n", bb->instr_start); STATS_INC(num_sysenter_indcalls); } }); } # endif /* Check if register dataflow matched and we were able to extract * the callee address. */ if (callee == NULL) return false; if (vsyscall) { /* Case 8917: abandon coarse-grainness in favor of performance */ bb->flags &= ~FRAG_COARSE_GRAIN; STATS_INC(coarse_prevent_indcall); } LOG(THREAD, LOG_INTERP, 4, "interp: possible convertible" " indirect call from " PFX " to " PFX "\n", bb->instr_start, callee); if (leave_call_native(callee) || must_not_be_entered(callee)) { BBPRINT(bb, 3, " NOT inlining indirect call to " PFX "\n", callee); /* Case 8711: coarse-grain can't handle non-exit cti */ bb->flags &= ~FRAG_COARSE_GRAIN; STATS_INC(coarse_prevent_cti); ASSERT_CURIOSITY_ONCE(!vsyscall && "leaving call* to vsyscall"); /* no need for bb_add_native_direct_xfer() b/c it's already indirect */ return true; /* keep bb going, w/o inlining call */ } if (bb->follow_direct && !must_not_be_entered(callee) && bb->num_elide_call < DYNAMO_OPTION(max_elide_call) && (DYNAMO_OPTION(elide_back_calls) || bb->cur_pc <= callee)) { /* FIXME This is identical to the code for evaluating a * direct call's callee. If such code appears in another * (3rd) place, we should outline it. * FIXME: use follow_direct_call() */ if (vsyscall) { /* As a flag to allow our xfer from now-non-coarse to coarse * (for vsyscall-in-ntdll) we pre-emptively mark as has-syscall. */ ASSERT(!TEST(FRAG_HAS_SYSCALL, bb->flags)); bb->flags |= FRAG_HAS_SYSCALL; } if (check_new_page_jmp(dcontext, bb, callee)) { if (vsyscall) /* Restore */ bb->flags &= ~FRAG_HAS_SYSCALL; bb->num_elide_call++; STATS_INC(total_elided_calls); STATS_TRACK_MAX(max_elided_calls, bb->num_elide_call); bb->cur_pc = callee; /* FIXME: when using follow_direct_call don't forget to set this */ call_instr->flags |= INSTR_IND_CALL_DIRECT; BBPRINT(bb, 4, " continuing in callee at " PFX "\n", bb->cur_pc); return true; /* keep bb going */ } if (vsyscall) { /* Case 8917: Restore, just in case, though we certainly expect to have * this flag set as soon as we decode a few more instrs and hit the * syscall itself -- but for pre-sp2 we currently could be elsewhere on * the same page, so let's be safe here. */ bb->flags &= ~FRAG_HAS_SYSCALL; } } /* FIXME: we're also not converting to a direct call - was this intended? */ BBPRINT(bb, 3, " NOT following indirect call from " PFX " to " PFX "\n", bb->instr_start, callee); DODEBUG({ if (vsyscall) { DO_ONCE({ /* Case 9095: don't complain so loudly if user asked for no elision */ if (DYNAMO_OPTION(max_elide_call) <= 2) SYSLOG_INTERNAL_WARNING("leaving call* to vsyscall"); else ASSERT_CURIOSITY(false && "leaving call* to vsyscall"); }); } }); ; #elif defined(ARM) /* FIXME i#1551: NYI on ARM */ ASSERT_NOT_IMPLEMENTED(false); #endif /* X86 */ return false; /* stop bb */ } /* FIXME i#1668, i#2974: NYI on ARM/AArch64 */ #ifdef X86 /* if we make the IAT sections unreadable we will need to map to proper location */ static inline app_pc read_from_IAT(app_pc iat_reference) { /* FIXME: we should have looked up where the real IAT should be at * the time of checking whether is_in_IAT */ return *(app_pc *)iat_reference; } /* returns whether target is an IAT of a module that we convert. Note * users still have to check the referred to value to verify targeting * a native module. */ static bool is_targeting_convertible_IAT(dcontext_t *dcontext, instr_t *instr, app_pc *iat_reference /* OUT */) { /* FIXME: we could give up on optimizing a particular module, * if too many writes to its IAT are found, * even 1 may be too much to handle! */ /* We only allow constant address, * any registers used for effective address calculation * can not be guaranteed to be constant dynamically. */ /* FIXME: yet a 'call %reg' if that value is an export would be a * good sign that we should go backwards and look for a possible * mov IAT[func] -> %reg and then optimize that as well - case 1948 */ app_pc memory_reference = NULL; opnd_t opnd = instr_get_target(instr); LOG(THREAD, LOG_INTERP, 4, "is_targeting_convertible_IAT: "); /* A typical example of a proper call * ff 15 8810807c call dword ptr [kernel32+0x1088 (7c801088)] * where * [7c801088] = 7c90f04c ntdll!RtlAnsiStringToUnicodeString * * The ModR/M byte for a displacement only with no SIB should be * 15 for CALL, 25 for JMP, (no far versions for IAT) */ if (opnd_is_near_base_disp(opnd)) { /* FIXME PR 253930: pattern-match x64 IAT calls */ IF_X64(ASSERT_NOT_IMPLEMENTED(false)); memory_reference = (app_pc)(ptr_uint_t)opnd_get_disp(opnd); /* now should check all other fields */ if (opnd_get_base(opnd) != REG_NULL || opnd_get_index(opnd) != REG_NULL) { /* this is not a pure memory reference, can't be IAT */ return false; } ASSERT(opnd_get_scale(opnd) == 0); } else { return false; } LOG(THREAD, LOG_INTERP, 3, "is_targeting_convertible_IAT: memory_reference " PFX "\n", memory_reference); /* FIXME: if we'd need some more additional structures those can * be looked up in a separate hashtable based on the IAT base, or * we'd have to extend the vmareas with custom fields */ ASSERT(DYNAMO_OPTION(IAT_convert)); if (vmvector_overlap(IAT_areas, memory_reference, memory_reference + 1)) { /* IAT has to be in the same module as current instruction, * but even in the unlikely reference by address from another * module there is really no problem, so not worth checking */ ASSERT_CURIOSITY(get_module_base(instr->bytes) == get_module_base(memory_reference)); /* FIXME: now that we know it is in IAT/GOT, * we have to READ the contents and return that * safely to the caller so they can convert accordingly */ /* FIXME: we would want to add the IAT section to the vmareas * of a region that has a converted block. Then on a write to * IAT we can flush efficiently only blocks affected by a * particular module, for a first hack though flushing * everything on a hooker will do. */ *iat_reference = memory_reference; return true; } else { /* plain global function * e.g. ntdll!RtlUnicodeStringToAnsiString+0x4c: * ff15c009917c call dword ptr [ntdll!RtlAllocateStringRoutine (7c9109c0)] */ return false; } } #endif /* X86 */ /* If the current instr in the BB is an indirect call through IAT that * can be converted into a direct call, process it and return true, * else, return false. */ static bool bb_process_IAT_convertible_indjmp(dcontext_t *dcontext, build_bb_t *bb, bool *elide_continue) { #ifdef X86 app_pc iat_reference; app_pc target; ASSERT(DYNAMO_OPTION(IAT_convert)); /* Check if the instr is a (near) indirect jump */ if (instr_get_opcode(bb->instr) != OP_jmp_ind) { ASSERT_CURIOSITY(false && "far ind jump"); return false; /* not matching, stop bb */ } if (!is_targeting_convertible_IAT(dcontext, bb->instr, &iat_reference)) { DOSTATS({ if (EXIT_IS_IND_JMP_PLT(bb->exit_type)) { /* see how often we mark as likely a PLT a JMP which in * fact is not going through IAT */ STATS_INC(num_indirect_jumps_PLT_not_IAT); LOG(THREAD, LOG_INTERP, 3, "bb_process_IAT_convertible_indjmp: indirect jmp not PLT instr=" PFX "\n", bb->instr->bytes); } }); return false; /* not matching, stop bb */ } target = read_from_IAT(iat_reference); DOLOG(4, LOG_INTERP, { char name[MAXIMUM_SYMBOL_LENGTH]; print_symbolic_address(target, name, sizeof(name), false); LOG(THREAD, LOG_INTERP, 4, "bb_process_IAT_convertible_indjmp: target=" PFX " %s\n", target, name); }); STATS_INC(num_indirect_jumps_IAT); DOSTATS({ if (!EXIT_IS_IND_JMP_PLT(bb->exit_type)) { /* count any other known uses for an indirect jump to go * through the IAT other than PLT uses, although a block * reaching max_elide_call would prevent the above * match */ STATS_INC(num_indirect_jumps_IAT_not_PLT); /* FIXME: case 6459 for further inquiry */ LOG(THREAD, LOG_INTERP, 4, "bb_process_IAT_convertible_indjmp: indirect jmp not PLT target=" PFX "\n", target); } }); if (must_not_be_elided(target)) { ASSERT_NOT_TESTED(); BBPRINT(bb, 3, " NOT inlining indirect jmp to must_not_be_elided " PFX "\n", target); return false; /* do not convert indirect jump, will stop bb */ } /* Verify not targeting native exec DLLs, note that the IATs of * any module may have imported a native DLL. Note it may be * possible to optimize with a range check on IAT subregions, but * this check isn't much slower. */ /* IAT_elide should definitely not touch native_exec modules. * * FIXME: we also prevent IAT_convert from optimizing imports in * native_exec_list DLLs, although we could let that convert to a * direct jump and require native_exec_dircalls to be always on to * intercept those jmps. */ if (DYNAMO_OPTION(native_exec) && is_native_pc(target)) { BBPRINT(bb, 3, " NOT inlining indirect jump to native exec module " PFX "\n", target); STATS_INC(num_indirect_jumps_IAT_native); return false; /* do not convert indirect jump, stop bb */ } /* mangle mostly as such as direct jumps would be mangled in * bb_process_ubr(dcontext, bb) but note bb->instr has already * been appended so has to reverse some of its actions */ /* pretend never saw an indirect JMP, we'll either add a new direct JMP or we'll just continue in target */ instrlist_remove(bb->ilist, bb->instr); /* bb->instr has been appended already */ instr_destroy(dcontext, bb->instr); bb->instr = NULL; if (DYNAMO_OPTION(IAT_elide)) { /* try to elide just as a direct jmp would have been elided */ /* We could have used follow_direct_call instead since * commonly this really is a disguised CALL*. Yet for PLT use * of the form of CALL PLT[foo]; JMP* IAT[foo] we would have * already counted the CALL. If we have tail call elimination * that converts a CALL* into a JMP* it is also OK to treat as * a JMP instead of a CALL just as if sharing tails. */ if (follow_direct_jump(dcontext, bb, target)) { LOG(THREAD, LOG_INTERP, 4, "bb_process_IAT_convertible_indjmp: eliding jmp* target=" PFX "\n", target); STATS_INC(num_indirect_jumps_IAT_elided); *elide_continue = true; /* do not stop bb */ return true; /* converted indirect to direct */ } } /* otherwise convert to direct jump without eliding */ /* we set bb->instr to NULL so unlike bb_process_ubr * we get the final exit_target added by build_bb_ilist * FIXME: case 85: which will work only when we're using bb->mangle_ilist * FIXME: what are callers supposed to see when we do NOT mangle? */ LOG(THREAD, LOG_INTERP, 4, "bb_process_IAT_convertible_indjmp: converting jmp* target=" PFX "\n", target); STATS_INC(num_indirect_jumps_IAT_converted); /* end basic block with a direct JMP to target */ bb->exit_target = target; *elide_continue = false; /* matching, but should stop bb */ return true; /* matching */ #elif defined(AARCHXX) /* FIXME i#1551, i#1569: NYI on ARM/AArch64 */ ASSERT_NOT_IMPLEMENTED(false); return false; #endif /* X86/ARM */ } /* Returns true if the current instr in the BB is an indirect call * through IAT that can be converted into a direct call, process it * and sets elide_continue. Otherwise function return false. * OUT elide_continue is set when bb building should continue in target, * and not set when bb building should be stopped. */ static bool bb_process_IAT_convertible_indcall(dcontext_t *dcontext, build_bb_t *bb, bool *elide_continue) { #ifdef X86 app_pc iat_reference; app_pc target; ASSERT(DYNAMO_OPTION(IAT_convert)); /* FIXME: the code structure is the same as * bb_process_IAT_convertible_indjmp, could fuse the two */ /* We perform several levels of checking, each increasingly more stringent * and expensive, with a false return should any fail. */ /* Check if the instr is a (near) indirect call */ if (instr_get_opcode(bb->instr) != OP_call_ind) { ASSERT_CURIOSITY(false && "far call"); return false; /* not matching, stop bb */ } if (!is_targeting_convertible_IAT(dcontext, bb->instr, &iat_reference)) { return false; /* not matching, stop bb */ } target = read_from_IAT(iat_reference); DOLOG(4, LOG_INTERP, { char name[MAXIMUM_SYMBOL_LENGTH]; print_symbolic_address(target, name, sizeof(name), false); LOG(THREAD, LOG_INTERP, 4, "bb_process_IAT_convertible_indcall: target=" PFX " %s\n", target, name); }); STATS_INC(num_indirect_calls_IAT); /* mangle mostly as such as direct calls are mangled with * bb_process_call_direct(dcontext, bb) */ if (leave_call_native(target) || must_not_be_entered(target)) { ASSERT_NOT_TESTED(); BBPRINT(bb, 3, " NOT inlining indirect call to leave_call_native " PFX "\n", target); return false; /* do not convert indirect call, stop bb */ } /* Verify not targeting native exec DLLs, note that the IATs of * any module may have imported a native DLL. Note it may be * possible to optimize with a range check on IAT subregions, but * this check isn't much slower. */ if (DYNAMO_OPTION(native_exec) && is_native_pc(target)) { BBPRINT(bb, 3, " NOT inlining indirect call to native exec module " PFX "\n", target); STATS_INC(num_indirect_calls_IAT_native); return false; /* do not convert indirect call, stop bb */ } /* mangle_indirect_call and calculate return address as of * bb->instr and will remove bb->instr * FIXME: it would have been * better to replace in instrlist with a direct call and have * mangle_{in,}direct_call use other than the raw bytes, but this for now does the * job. */ bb->instr->flags |= INSTR_IND_CALL_DIRECT; if (DYNAMO_OPTION(IAT_elide)) { /* try to elide just as a direct call would have been elided */ if (follow_direct_call(dcontext, bb, target)) { LOG(THREAD, LOG_INTERP, 4, "bb_process_IAT_convertible_indcall: eliding call* flags=0x%08x " "target=" PFX "\n", bb->instr->flags, target); STATS_INC(num_indirect_calls_IAT_elided); *elide_continue = true; /* do not stop bb */ return true; /* converted indirect to direct */ } } /* otherwise convert to direct call without eliding */ LOG(THREAD, LOG_INTERP, 4, "bb_process_IAT_convertible_indcall: converting call* flags=0x%08x target=" PFX "\n", bb->instr->flags, target); STATS_INC(num_indirect_calls_IAT_converted); /* bb->instr has been appended already, and will get removed by * mangle_indirect_call. We don't need to set to NULL, since this * instr is a CTI and the final jump's translation target should * still be the original indirect call. */ bb->exit_target = target; /* end basic block with a direct CALL to target. With default * options it should get mangled to a PUSH; JMP */ *elide_continue = false; /* matching, but should stop bb */ return true; /* converted indirect to direct */ #elif defined(AARCHXX) /* FIXME i#1551, i#1569: NYI on ARM/AArch64 */ ASSERT_NOT_IMPLEMENTED(false); return false; #endif /* X86/ARM */ } /* Called on instructions that save the FPU state */ static void bb_process_float_pc(dcontext_t *dcontext, build_bb_t *bb) { /* i#698: for instructions that save the floating-point state * (e.g., fxsave), we go back to d_r_dispatch to translate the fp pc. * We rule out being in a trace (and thus a potential alternative * would be to use a FRAG_ flag). These are rare instructions so that * shouldn't have a significant perf impact: except we've been hitting * libm code that uses fnstenv and is not rare, so we have non-inlined * translation under an option for now. */ if (DYNAMO_OPTION(translate_fpu_pc)) { bb->exit_type |= LINK_SPECIAL_EXIT; bb->flags |= FRAG_CANNOT_BE_TRACE; } /* If we inline the pc update, we can't persist. Simplest to keep fine-grained. */ bb->flags &= ~FRAG_COARSE_GRAIN; } static bool instr_will_be_exit_cti(instr_t *inst) { /* can't use instr_is_exit_cti() on pre-mangled instrs */ return (instr_is_app(inst) && instr_is_cti(inst) && (!instr_is_near_call_direct(inst) || !leave_call_native(instr_get_branch_target_pc(inst))) /* PR 239470: ignore wow64 syscall, which is an ind call */ IF_WINDOWS(&&!instr_is_wow64_syscall(inst))); } /* PR 215217: check syscall restrictions */ static bool client_check_syscall(instrlist_t *ilist, instr_t *inst, bool *found_syscall, bool *found_int) { int op_int = IF_X86_ELSE(OP_int, OP_svc); /* We do consider the wow64 call* a syscall here (it is both * a syscall and a call*: PR 240258). */ if (instr_is_syscall(inst) || instr_get_opcode(inst) == op_int) { if (instr_is_syscall(inst) && found_syscall != NULL) *found_syscall = true; /* Xref PR 313869 - we should be ignoring int 3 here. */ if (instr_get_opcode(inst) == op_int && found_int != NULL) *found_int = true; /* For linux an ignorable syscall is not a problem. Our * pre-syscall-exit jmp is added post client mangling so should * be robust. * FIXME: now that we have -no_inline_ignored_syscalls should * we assert on ignorable also? Probably we'd have to have * an exception for the middle of a trace? */ if (IF_UNIX(TEST(INSTR_NI_SYSCALL, inst->flags)) /* PR 243391: only block-ending interrupt 2b matters */ IF_WINDOWS(instr_is_syscall(inst) || ((instr_get_opcode(inst) == OP_int && instr_get_interrupt_number(inst) == 0x2b)))) { /* This check means we shouldn't hit the exit_type flags * check below but we leave it in place in case we add * other flags in future */ if (inst != instrlist_last(ilist)) { CLIENT_ASSERT(false, "a syscall or interrupt must terminate the block"); return false; } /* should we forcibly delete the subsequent instrs? * or the client has to deal w/ bad behavior in release build? */ } } return true; } /* Pass bb to client, and afterward check for criteria we require and rescan for * eflags and other flags that might have changed. * Returns true normally; returns false to indicate "go native". */ static bool client_process_bb(dcontext_t *dcontext, build_bb_t *bb) { dr_emit_flags_t emitflags = DR_EMIT_DEFAULT; instr_t *inst; bool found_exit_cti = false; bool found_syscall = false; bool found_int = false; #ifdef ANNOTATIONS app_pc trailing_annotation_pc = NULL, instrumentation_pc = NULL; bool found_instrumentation_pc = false; instr_t *annotation_label = NULL; #endif instr_t *last_app_instr = NULL; /* This routine is called by more than just bb builder, also used * for recreating state, so only call if caller requested it * (usually that coincides w/ bb->app_interp being set, but not * when recreating state on a fault (PR 214962)). * FIXME: hot patches shouldn't be injected during state recreations; * does predicating on bb->app_interp take care of this issue? */ if (!bb->pass_to_client) return true; /* i#995: DR may build a bb with one invalid instruction, which won't be * passed to cliennt. * FIXME: i#1000, we should present the bb to the client. * i#1000-c#1: the bb->ilist could be empty. */ if (instrlist_first(bb->ilist) == NULL) return true; if (!instr_opcode_valid(instrlist_first(bb->ilist)) && /* For -fast_client_decode we can have level 0 instrs so check * to ensure this is a single-instr bb that was built just to * raise the fault for us. * XXX i#1000: shouldn't we pass this to the client? It might not handle an * invalid instr properly though. */ instrlist_first(bb->ilist) == instrlist_last(bb->ilist)) { return true; } /* Call the bb creation callback(s) */ if (!instrument_basic_block(dcontext, /* DrMem#1735: pass app pc, not selfmod copy pc */ (bb->pretend_pc == NULL ? bb->start_pc : bb->pretend_pc), bb->ilist, bb->for_trace, !bb->app_interp, &emitflags)) { /* although no callback was called we must process syscalls/ints (PR 307284) */ } if (bb->for_cache && TEST(DR_EMIT_GO_NATIVE, emitflags)) { LOG(THREAD, LOG_INTERP, 2, "client requested that we go native\n"); SYSLOG_INTERNAL_INFO("thread " TIDFMT " is going native at client request", d_r_get_thread_id()); /* we leverage the existing native_exec mechanism */ dcontext->native_exec_postsyscall = bb->start_pc; dcontext->next_tag = BACK_TO_NATIVE_AFTER_SYSCALL; /* dynamo_thread_not_under_dynamo() will be called in dispatch_enter_native(). */ return false; } bb->post_client = true; /* FIXME: instrumentor may totally mess us up -- our flags * or syscall info might be wrong. xref PR 215217 */ /* PR 215217, PR 240265: * We need to check for client changes that require a new exit * target. We can't practically analyze the instrlist to decipher * the exit, so we'll search backwards and require that the last * cti is the exit cti. Typically, the last instruction in the * block should be the exit. Post-mbr and post-syscall positions * are particularly fragile, as our mangling code sets state up for * the exit that could be messed up by instrs inserted after the * mbr/syscall. We thus disallow such instrs (except for * dr_insert_mbr_instrumentation()). xref cases 10503, 10782, 10784 * * Here's what we support: * - more than one exit cti; all but the last must be a ubr * - an exit cbr or call must be the final instr in the block * - only one mbr; must be the final instr in the block and the exit target * - clients can't change the exit of blocks ending in a syscall * (or int), and the syscall must be the final instr in the block; * client can, however, remove the syscall and then add a different exit * - client can't add a translation target that's outside of the original * source code bounds, or else our cache consistency breaks down * (the one exception to this is that a jump can translate to its target) */ /* we set to NULL to have a default of fall-through */ bb->exit_target = NULL; bb->exit_type = 0; /* N.B.: we're walking backward */ for (inst = instrlist_last(bb->ilist); inst != NULL; inst = instr_get_prev(inst)) { if (!instr_opcode_valid(inst)) continue; if (instr_is_cti(inst) && inst != instrlist_last(bb->ilist)) { /* PR 213005: coarse_units can't handle added ctis (meta or not) * since decode_fragment(), used for state recreation, can't * distinguish from exit cti. * i#665: we now support intra-fragment meta ctis * to make persistence usable for clients */ if (!opnd_is_instr(instr_get_target(inst)) || instr_is_app(inst)) { bb->flags &= ~FRAG_COARSE_GRAIN; STATS_INC(coarse_prevent_client); } } if (instr_is_meta(inst)) { #ifdef ANNOTATIONS /* Save the trailing_annotation_pc in case a client truncated the bb there. */ if (is_annotation_label(inst) && last_app_instr == NULL) { dr_instr_label_data_t *label_data = instr_get_label_data_area(inst); trailing_annotation_pc = GET_ANNOTATION_APP_PC(label_data); instrumentation_pc = GET_ANNOTATION_INSTRUMENTATION_PC(label_data); annotation_label = inst; } #endif continue; } #ifdef X86 if (!d_r_is_avx512_code_in_use()) { if (ZMM_ENABLED()) { if (instr_may_write_zmm_or_opmask_register(inst)) { LOG(THREAD, LOG_INTERP, 2, "Detected AVX-512 code in use\n"); d_r_set_avx512_code_in_use(true, NULL); proc_set_num_simd_saved(MCXT_NUM_SIMD_SLOTS); } } } #endif #ifdef ANNOTATIONS if (instrumentation_pc != NULL && !found_instrumentation_pc && instr_get_translation(inst) == instrumentation_pc) found_instrumentation_pc = true; #endif /* in case bb was truncated, find last non-meta fall-through */ if (last_app_instr == NULL) last_app_instr = inst; /* PR 215217: client should not add new source code regions, else our * cache consistency (both page prot and selfmod) will fail */ ASSERT(!bb->for_cache || bb->vmlist != NULL); /* For selfmod recreation we don't check vmareas so we don't have vmlist. * We live w/o the checks there. */ CLIENT_ASSERT( !bb->for_cache || vm_list_overlaps(dcontext, bb->vmlist, instr_get_translation(inst), instr_get_translation(inst) + 1) || (instr_is_ubr(inst) && opnd_is_pc(instr_get_target(inst)) && instr_get_translation(inst) == opnd_get_pc(instr_get_target(inst))) /* the displaced code and jmp return from intercept buffer * has translation fields set to hooked app routine */ IF_WINDOWS(|| dr_fragment_app_pc(bb->start_pc) != bb->start_pc), "block's app sources (instr_set_translation() targets) " "must remain within original bounds"); #ifdef AARCH64 if (instr_get_opcode(inst) == OP_isb) { CLIENT_ASSERT(inst == instrlist_last(bb->ilist), "OP_isb must be last instruction in block"); } #endif /* PR 307284: we didn't process syscalls and ints pre-client * so do so now to get bb->flags and bb->exit_type set */ if (instr_is_syscall(inst) || instr_get_opcode(inst) == IF_X86_ELSE(OP_int, OP_svc)) { instr_t *tmp = bb->instr; bb->instr = inst; if (instr_is_syscall(bb->instr)) bb_process_syscall(dcontext, bb); else if (instr_get_opcode(bb->instr) == IF_X86_ELSE(OP_int, OP_svc)) { /* non-syscall int */ bb_process_interrupt(dcontext, bb); } if (inst != instrlist_last(bb->ilist)) bb->instr = tmp; } /* ensure syscall/int2b terminates block */ client_check_syscall(bb->ilist, inst, &found_syscall, &found_int); if (instr_will_be_exit_cti(inst)) { if (!found_exit_cti) { /* We're about to clobber the exit_type and could lose any * special flags set above, even if the client doesn't change * the exit target. We undo such flags after this ilist walk * to support client removal of syscalls/ints. * EXIT_IS_IND_JMP_PLT() is used for -IAT_{convert,elide}, which * is off by default for CI; it's also used for native_exec, * but we're not sure if we want to support that with CI. * xref case 10846 and i#198 */ CLIENT_ASSERT( !TEST(~(LINK_DIRECT | LINK_INDIRECT | LINK_CALL | LINK_RETURN | LINK_JMP | LINK_NI_SYSCALL_ALL | LINK_SPECIAL_EXIT IF_WINDOWS(| LINK_CALLBACK_RETURN)), bb->exit_type) && !EXIT_IS_IND_JMP_PLT(bb->exit_type), "client unsupported block exit type internal error"); found_exit_cti = true; bb->instr = inst; if ((instr_is_near_ubr(inst) || instr_is_near_call_direct(inst)) /* conditional OP_bl needs the cbr code below */ IF_ARM(&&!instr_is_cbr(inst))) { CLIENT_ASSERT(instr_is_near_ubr(inst) || inst == instrlist_last(bb->ilist) || /* for elision we assume calls are followed * by their callee target code */ DYNAMO_OPTION(max_elide_call) > 0, "an exit call must terminate the block"); /* a ubr need not be the final instr */ if (inst == last_app_instr) { bb->exit_target = instr_get_branch_target_pc(inst); bb->exit_type = instr_branch_type(inst); } } else if (instr_is_mbr(inst) || instr_is_far_cti(inst) IF_ARM(/* mode-switch direct is treated as indirect */ || instr_get_opcode(inst) == OP_blx)) { CLIENT_ASSERT(inst == instrlist_last(bb->ilist), "an exit mbr or far cti must terminate the block"); bb->exit_type = instr_branch_type(inst); #ifdef ARM if (instr_get_opcode(inst) == OP_blx) bb->ibl_branch_type = IBL_INDCALL; else #endif bb->ibl_branch_type = get_ibl_branch_type(inst); bb->exit_target = get_ibl_routine(dcontext, get_ibl_entry_type(bb->exit_type), DEFAULT_IBL_BB(), bb->ibl_branch_type); } else { ASSERT(instr_is_cbr(inst)); CLIENT_ASSERT(inst == instrlist_last(bb->ilist), "an exit cbr must terminate the block"); /* A null exit target specifies a cbr (see below). */ bb->exit_target = NULL; bb->exit_type = 0; instr_exit_branch_set_type(bb->instr, instr_branch_type(inst)); } /* since we're walking backward, at the first exit cti * we can check for post-cti code */ if (inst != instrlist_last(bb->ilist)) { if (TEST(FRAG_COARSE_GRAIN, bb->flags)) { /* PR 213005: coarse can't handle code beyond ctis */ bb->flags &= ~FRAG_COARSE_GRAIN; STATS_INC(coarse_prevent_client); } /* decode_fragment can't handle code beyond ctis */ if (!instr_is_near_call_direct(inst) || DYNAMO_OPTION(max_elide_call) == 0) bb->flags |= FRAG_CANNOT_BE_TRACE; } } /* Case 10784: Clients can confound trace building when they * introduce more than one exit cti; we'll just disable traces * for these fragments. */ else { CLIENT_ASSERT(instr_is_near_ubr(inst) || (instr_is_near_call_direct(inst) && /* for elision we assume calls are followed * by their callee target code */ DYNAMO_OPTION(max_elide_call) > 0), "a second exit cti must be a ubr"); if (!instr_is_near_call_direct(inst) || DYNAMO_OPTION(max_elide_call) == 0) bb->flags |= FRAG_CANNOT_BE_TRACE; /* our cti check above should have already turned off coarse */ ASSERT(!TEST(FRAG_COARSE_GRAIN, bb->flags)); } } } /* To handle the client modifying syscall numbers we cannot inline * syscalls in the middle of a bb. */ ASSERT(!DYNAMO_OPTION(inline_ignored_syscalls)); ASSERT((TEST(FRAG_HAS_SYSCALL, bb->flags) && found_syscall) || (!TEST(FRAG_HAS_SYSCALL, bb->flags) && !found_syscall)); IF_WINDOWS(ASSERT(!TEST(LINK_CALLBACK_RETURN, bb->exit_type) || found_int)); /* Note that we do NOT remove, or set, FRAG_HAS_DIRECT_CTI based on * client modifications: setting it for a selfmod fragment could * result in an infinite loop, and it is mainly used for elision, which we * are not doing for client ctis. Clients are not supposed add new * app source regions (PR 215217). */ /* Client might have truncated: re-set fall-through, accounting for annotations. */ if (last_app_instr != NULL) { bool adjusted_cur_pc = false; app_pc xl8 = instr_get_translation(last_app_instr); #ifdef ANNOTATIONS if (annotation_label != NULL) { if (found_instrumentation_pc) { /* i#1613: if the last app instruction precedes an annotation, extend the * translation footprint of `bb` to include the annotation (such that * the next bb starts after the annotation, avoiding duplication). */ bb->cur_pc = trailing_annotation_pc; adjusted_cur_pc = true; LOG(THREAD, LOG_INTERP, 3, "BB ends immediately prior to an annotation. " "Setting `bb->cur_pc` (for fall-through) to " PFX " so that the " "annotation will be included.\n", bb->cur_pc); } else { /* i#1613: the client removed the app instruction prior to an annotation. * We infer that the client wants to skip the annotation. Remove it now. */ instr_t *annotation_next = instr_get_next(annotation_label); instrlist_remove(bb->ilist, annotation_label); instr_destroy(dcontext, annotation_label); if (is_annotation_return_placeholder(annotation_next)) { instrlist_remove(bb->ilist, annotation_next); instr_destroy(dcontext, annotation_next); } } } #endif #if defined(WINDOWS) && !defined(STANDALONE_DECODER) /* i#1632: if the last app instruction was taken from an intercept because it was * occluded by the corresponding hook, `bb->cur_pc` should point to the original * app pc (where that instruction was copied from). Cannot use `decode_next_pc()` * on the original app pc because it is now in the middle of the hook. */ if (!adjusted_cur_pc && could_be_hook_occluded_pc(xl8)) { app_pc intercept_pc = get_intercept_pc_from_app_pc( xl8, true /* occlusions only */, false /* exclude start */); if (intercept_pc != NULL) { app_pc next_intercept_pc = decode_next_pc(dcontext, intercept_pc); bb->cur_pc = xl8 + (next_intercept_pc - intercept_pc); adjusted_cur_pc = true; LOG(THREAD, LOG_INTERP, 3, "BB ends in the middle of an intercept. " "Offsetting `bb->cur_pc` (for fall-through) to " PFX " in parallel " "to intercept instr at " PFX "\n", intercept_pc, bb->cur_pc); } } #endif /* We do not take instr_length of what the client put in, but rather * the length of the translation target */ if (!adjusted_cur_pc) { bb->cur_pc = decode_next_pc(dcontext, xl8); LOG(THREAD, LOG_INTERP, 3, "setting cur_pc (for fall-through) to " PFX "\n", bb->cur_pc); } /* don't set bb->instr if last instr is still syscall/int. * FIXME: I'm not 100% convinced the logic here covers everything * build_bb_ilist does. * FIXME: what about if last instr was invalid, or if client adds * some invalid instrs: xref bb_process_invalid_instr() */ if (bb->instr != NULL || (!found_int && !found_syscall)) bb->instr = last_app_instr; } else bb->instr = NULL; /* no app instrs left */ /* PR 215217: re-scan for accurate eflags. * FIXME: should we not do eflags tracking while decoding, then, and always * do it afterward? */ /* for -fast_client_decode, we don't support the client changing the app code */ if (!INTERNAL_OPTION(fast_client_decode)) { bb->eflags = forward_eflags_analysis(dcontext, bb->ilist, instrlist_first(bb->ilist)); } if (TEST(DR_EMIT_STORE_TRANSLATIONS, emitflags)) { /* PR 214962: let client request storage instead of recreation */ bb->flags |= FRAG_HAS_TRANSLATION_INFO; /* if we didn't have record on from start, can't store translation info */ CLIENT_ASSERT(!INTERNAL_OPTION(fast_client_decode), "-fast_client_decode not compatible with " "DR_EMIT_STORE_TRANSLATIONS"); ASSERT(bb->record_translation && bb->full_decode); } if (DYNAMO_OPTION(coarse_enable_freeze)) { /* If we're not persisting, ignore the presence or absence of the flag * so we avoid undoing savings from -opt_memory with a tool that * doesn't support persistence. */ if (!TEST(DR_EMIT_PERSISTABLE, emitflags)) { bb->flags &= ~FRAG_COARSE_GRAIN; STATS_INC(coarse_prevent_client); } } if (TEST(DR_EMIT_MUST_END_TRACE, emitflags)) { /* i#848: let client terminate traces */ bb->flags |= FRAG_MUST_END_TRACE; } return true; } #ifdef DR_APP_EXPORTS static void mangle_pre_client(dcontext_t *dcontext, build_bb_t *bb) { if (bb->start_pc == (app_pc)dr_app_running_under_dynamorio) { /* i#1237: set return value to be true in dr_app_running_under_dynamorio */ instr_t *ret = instrlist_last(bb->ilist); instr_t *mov = instr_get_prev(ret); LOG(THREAD, LOG_INTERP, 3, "Found dr_app_running_under_dynamorio\n"); ASSERT(ret != NULL && instr_is_return(ret) && mov != NULL && IF_X86(instr_get_opcode(mov) == OP_mov_imm &&) IF_ARM(instr_get_opcode(mov) == OP_mov && OPND_IS_IMMED_INT(instr_get_src(mov, 0)) &&) IF_AARCH64(instr_get_opcode(mov) == OP_movz &&)( bb->start_pc == instr_get_raw_bits(mov) || /* the translation field might be NULL */ bb->start_pc == instr_get_translation(mov))); /* i#1998: ensure the instr is Level 3+ */ instr_decode(dcontext, mov); instr_set_src(mov, 0, OPND_CREATE_INT32(1)); } } #endif /* DR_APP_EXPORTS */ /* This routine is called from build_bb_ilist when the number of instructions reaches or * exceeds max_bb_instr. It checks if bb is safe to stop after instruction stop_after. * On ARM, we do not stop bb building in the middle of an IT block unless there is a * conditional syscall. */ static bool bb_safe_to_stop(dcontext_t *dcontext, instrlist_t *ilist, instr_t *stop_after) { #ifdef ARM ASSERT(ilist != NULL && instrlist_last(ilist) != NULL); /* only thumb mode could have IT blocks */ if (dr_get_isa_mode(dcontext) != DR_ISA_ARM_THUMB) return true; if (stop_after == NULL) stop_after = instrlist_last_app(ilist); if (instr_get_opcode(stop_after) == OP_it) return false; if (!instr_is_predicated(stop_after)) return true; if (instr_is_cti(stop_after) /* must be the last instr if in IT block */ || /* we do not stop in the middle of an IT block unless it is a syscall */ instr_is_syscall(stop_after) || instr_is_interrupt(stop_after)) return true; return instr_is_last_in_it_block(stop_after, NULL, NULL); #endif /* ARM */ return true; } /* Interprets the application's instructions until the end of a basic * block is found, and prepares the resulting instrlist for creation of * a fragment, but does not create the fragment, just returns the instrlist. * Caller is responsible for freeing the list and its instrs! * * Input parameters in bb control aspects of creation: * If app_interp is true, this is considered real app code. * If pass_to_client is true, * calls instrument routine on bb->ilist before mangling * If mangle_ilist is true, mangles the ilist, else leaves it in app form * If record_vmlist is true, updates the vmareas data structures * If for_cache is true, bb building lock is assumed to be held. * record_vmlist should also be true. * Caller must set and later clear dcontext->bb_build_info. * For !for_cache, build_bb_ilist() sets and clears it, making the * assumption that the caller is doing no other reading from the region. * If record_translation is true, records translation for inserted instrs * If outf != NULL, does full disassembly with comments to outf * If overlap_info != NULL, records overlap information for the block in * the overlap_info (caller must fill in region_start and region_end). * * FIXME: now that we have better control over following direct ctis, * should we have adaptive mechanism to decided whether to follow direct * ctis, since some bmarks are better doing so (gap, vortex, wupwise) * and others are worse (apsi, perlbmk)? */ static void build_bb_ilist(dcontext_t *dcontext, build_bb_t *bb) { /* Design decision: we will not try to identify branches that target * instructions in this basic block, when we take those branches we will * just make a new basic block and duplicate part of this one */ int total_branches = 0; uint total_instrs = 0; /* maximum number of instructions for current basic block */ uint cur_max_bb_instrs = DYNAMO_OPTION(max_bb_instrs); uint total_writes = 0; /* only used for selfmod */ instr_t *non_cti; /* used if !full_decode */ byte *non_cti_start_pc; /* used if !full_decode */ uint eflags_6 = 0; /* holds arith eflags written so far (in read slots) */ #ifdef HOT_PATCHING_INTERFACE bool hotp_should_inject = false, hotp_injected = false; #endif app_pc page_start_pc = (app_pc)NULL; bool bb_build_nested = false; /* Caller will free objects allocated here so we must use the passed-in * dcontext for allocation; we need separate var for non-global dcontext. */ dcontext_t *my_dcontext = get_thread_private_dcontext(); DEBUG_DECLARE(bool regenerated = false;) bool stop_bb_on_fallthrough = false; ASSERT(bb->initialized); /* note that it's ok for bb->start_pc to be NULL as our check_new_page_start * will catch it */ /* vmlist must start out empty (or N/A) */ ASSERT(bb->vmlist == NULL || !bb->record_vmlist || bb->checked_start_vmarea); ASSERT(!bb->for_cache || bb->record_vmlist); /* for_cache assumes record_vmlist */ #ifdef CUSTOM_TRACES_RET_REMOVAL my_dcontext->num_calls = 0; my_dcontext->num_rets = 0; #endif /* Support bb abort on decode fault */ if (my_dcontext != NULL) { if (bb->for_cache) { /* Caller should have set! */ ASSERT(bb == (build_bb_t *)my_dcontext->bb_build_info); } else if (my_dcontext->bb_build_info == NULL) { my_dcontext->bb_build_info = (void *)bb; } else { /* For nested we leave the original, which should be the only vmlist, * and we give up on freeing dangling instr_t and instrlist_t from this * decode. * We need the original's for_cache so we know to free the bb_building_lock. * FIXME: use TRY to handle decode exceptions locally? Shouldn't have * violation remediations on a !for_cache build. */ ASSERT(bb->vmlist == NULL && !bb->for_cache && ((build_bb_t *)my_dcontext->bb_build_info)->for_cache); /* FIXME: add nested as a field so we can have stat on nested faults */ bb_build_nested = true; } } else ASSERT(dynamo_exited); if ((bb->record_translation && !INTERNAL_OPTION(fast_client_decode)) || !bb->for_cache /* to split riprel, need to decode every instr */ /* in x86_to_x64, need to translate every x86 instr */ IF_X64(|| DYNAMO_OPTION(coarse_split_riprel) || DYNAMO_OPTION(x86_to_x64)) || INTERNAL_OPTION(full_decode) /* We separate rseq regions into their own blocks to make this check easier. */ IF_LINUX(|| (!vmvector_empty(d_r_rseq_areas) && vmvector_overlap(d_r_rseq_areas, bb->start_pc, bb->start_pc + 1)))) bb->full_decode = true; else { #ifdef CHECK_RETURNS_SSE2 bb->full_decode = true; #endif } LOG(THREAD, LOG_INTERP, 3, "\ninterp%s: ", IF_X86_64_ELSE(X64_MODE_DC(dcontext) ? "" : " (x86 mode)", "")); BBPRINT(bb, 3, "start_pc = " PFX "\n", bb->start_pc); DOSTATS({ if (bb->app_interp) { if (fragment_lookup_deleted(dcontext, bb->start_pc)) { /* this will look up private 1st, so yes we will get * dup stats if multiple threads have regnerated the * same private tag, or if a shared tag is deleted and * multiple privates created */ regenerated = true; STATS_INC(num_fragments_deja_vu); } } }); /* start converting instructions into IR */ if (!bb->checked_start_vmarea) check_new_page_start(dcontext, bb); #if defined(WINDOWS) && !defined(STANDALONE_DECODER) /* i#1632: if `bb->start_pc` points into the middle of a DR intercept hook, change * it so instructions are taken from the intercept instead (note that * `instr_set_translation` will hide this adjustment from the client). N.B.: this * must follow `check_new_page_start()` (above) or `bb.vmlist` will be wrong. */ if (could_be_hook_occluded_pc(bb->start_pc)) { app_pc intercept_pc = get_intercept_pc_from_app_pc( bb->start_pc, true /* occlusions only */, true /* exclude start pc */); if (intercept_pc != NULL) { LOG(THREAD, LOG_INTERP, 3, "Changing start_pc from hook-occluded app pc " PFX " to intercept pc " PFX "\n", bb->start_pc, intercept_pc); bb->start_pc = intercept_pc; } } #endif bb->cur_pc = bb->start_pc; /* for translation in case we break out of loop before decoding any * instructions, (i.e. check_for_stopping_point()) */ bb->instr_start = bb->cur_pc; /* create instrlist after check_new_page_start to avoid memory leak * on unreadable memory -- though we now properly clean up and won't leak * on unreadable on any check_thread_vm_area call */ bb->ilist = instrlist_create(dcontext); bb->instr = NULL; /* avoid discrepancy in finding invalid instructions between fast decode * and the full decode of sandboxing by doing full decode up front */ if (TEST(FRAG_SELFMOD_SANDBOXED, bb->flags)) { bb->full_decode = true; bb->follow_direct = false; } if (TEST(FRAG_HAS_TRANSLATION_INFO, bb->flags)) { bb->full_decode = true; bb->record_translation = true; } if (my_dcontext != NULL && my_dcontext->single_step_addr == bb->start_pc) { /* Decodes only one instruction because of single step exception. */ cur_max_bb_instrs = 1; } KSTART(bb_decoding); while (true) { if (check_for_stopping_point(dcontext, bb)) { BBPRINT(bb, 3, "interp: found DynamoRIO stopping point at " PFX "\n", bb->cur_pc); break; } /* fill in a new instr structure and update bb->cur_pc */ bb->instr = instr_create(dcontext); /* if !full_decode: * All we need to decode are control-transfer instructions * For efficiency, put all non-cti into a single instr_t structure */ non_cti_start_pc = bb->cur_pc; do { /* If the thread's vmareas aren't being added to, indicate the * page that's being decoded. */ if (!bb->record_vmlist && page_start_pc != (app_pc)PAGE_START(bb->cur_pc)) { page_start_pc = (app_pc)PAGE_START(bb->cur_pc); set_thread_decode_page_start(my_dcontext == NULL ? dcontext : my_dcontext, page_start_pc); } bb->instr_start = bb->cur_pc; if (bb->full_decode) { /* only going through this do loop once! */ bb->cur_pc = IF_AARCH64_ELSE(decode_with_ldstex, decode)(dcontext, bb->cur_pc, bb->instr); if (bb->record_translation) instr_set_translation(bb->instr, bb->instr_start); } else { /* must reset, may go through loop multiple times */ instr_reset(dcontext, bb->instr); bb->cur_pc = IF_AARCH64_ELSE(decode_cti_with_ldstex, decode_cti)(dcontext, bb->cur_pc, bb->instr); #if defined(ANNOTATIONS) && !(defined(X64) && defined(WINDOWS)) /* Quickly check whether this may be a Valgrind annotation. */ if (is_encoded_valgrind_annotation_tail(bb->instr_start)) { /* Might be an annotation, so try the (slower) full check. */ if (is_encoded_valgrind_annotation(bb->instr_start, bb->start_pc, (app_pc)PAGE_START(bb->cur_pc))) { /* Valgrind annotation needs full decode; clean up and repeat. */ KSTOP(bb_decoding); instr_destroy(dcontext, bb->instr); instrlist_clear_and_destroy(dcontext, bb->ilist); if (bb->vmlist != NULL) { vm_area_destroy_list(dcontext, bb->vmlist); bb->vmlist = NULL; } bb->full_decode = true; build_bb_ilist(dcontext, bb); return; } } #endif } ASSERT(!bb->check_vm_area || bb->checked_end != NULL); if (bb->check_vm_area && bb->cur_pc != NULL && bb->cur_pc - 1 >= bb->checked_end) { /* We're beyond the vmarea allowed -- so check again. * Ideally we'd want to check BEFORE we decode from the * subsequent page, as it could be inaccessible, but not worth * the time estimating the size from a variable number of bytes * before the page boundary. Instead we rely on other * mechanisms to handle faults while decoding, which we need * anyway to handle racy unmaps by the app. */ uint old_flags = bb->flags; DEBUG_DECLARE(bool is_first_instr = (bb->instr_start == bb->start_pc)); if (!check_new_page_contig(dcontext, bb, bb->cur_pc - 1)) { /* i#989: Stop bb building before falling through to an * incompatible vmarea. */ ASSERT(!is_first_instr); bb->cur_pc = NULL; stop_bb_on_fallthrough = true; break; } if (!TEST(FRAG_SELFMOD_SANDBOXED, old_flags) && TEST(FRAG_SELFMOD_SANDBOXED, bb->flags)) { /* Restart the decode loop with full_decode and * !follow_direct, which are needed for sandboxing. This * can't happen more than once because sandboxing is now on. */ ASSERT(is_first_instr); bb->full_decode = true; bb->follow_direct = false; bb->cur_pc = bb->instr_start; instr_reset(dcontext, bb->instr); continue; } } total_instrs++; DOELOG(3, LOG_INTERP, { disassemble_with_bytes(dcontext, bb->instr_start, THREAD); }); if (bb->outf != INVALID_FILE) disassemble_with_bytes(dcontext, bb->instr_start, bb->outf); if (!instr_valid(bb->instr)) break; /* before eflags analysis! */ #ifdef X86 /* If the next instruction at bb->cur_pc fires a debug register, * then we should stop this basic block before getting to it. */ if (my_dcontext != NULL && debug_register_fire_on_addr(bb->instr_start)) { stop_bb_on_fallthrough = true; break; } if (!d_r_is_avx512_code_in_use()) { if (ZMM_ENABLED()) { if (instr_get_prefix_flag(bb->instr, PREFIX_EVEX)) { /* For AVX-512 detection in bb builder, we're checking only * for the prefix flag, which for example can be set by * decode_cti. In client_process_bb, post-client instructions * are checked with instr_may_write_zmm_register. */ LOG(THREAD, LOG_INTERP, 2, "Detected AVX-512 code in use\n"); d_r_set_avx512_code_in_use(true, instr_get_app_pc(bb->instr)); proc_set_num_simd_saved(MCXT_NUM_SIMD_SLOTS); } } } #endif /* Eflags analysis: * We do this even if -unsafe_ignore_eflags_prefix b/c it doesn't cost that * much and we can use the analysis to detect any bb that reads a flag * prior to writing it. */ if (bb->eflags != EFLAGS_WRITE_ARITH IF_X86(&&bb->eflags != EFLAGS_READ_OF)) bb->eflags = eflags_analysis(bb->instr, bb->eflags, &eflags_6); /* stop decoding at an invalid instr (tested above) or a cti *(== opcode valid) or a possible SEH frame push (if * -process_SEH_push). */ #ifdef WINDOWS if (DYNAMO_OPTION(process_SEH_push) && instr_get_prefix_flag(bb->instr, PREFIX_SEG_FS)) { STATS_INC(num_bb_build_fs); break; } #endif #ifdef X64 if (instr_has_rel_addr_reference(bb->instr)) { /* PR 215397: we need to split these out for re-relativization */ break; } #endif #if defined(UNIX) && defined(X86) if (INTERNAL_OPTION(mangle_app_seg) && instr_get_prefix_flag(bb->instr, PREFIX_SEG_FS | PREFIX_SEG_GS)) { /* These segment prefix flags are not persistent and are * only used as hints just after decoding. * They are not accurate later and can be misleading. * This can only be used right after decoding for quick check, * and a walk of operands should be performed to look for * actual far mem refs. */ /* i#107, mangle reference with segment register */ /* we up-decode the instr when !full_decode to make sure it will * pass the instr_opcode_valid check in mangle and be mangled. */ instr_get_opcode(bb->instr); break; } #endif /* i#107, opcode mov_seg will be set in decode_cti, * so instr_opcode_valid(bb->instr) is true, and terminates the loop. */ } while (!instr_opcode_valid(bb->instr) && total_instrs <= cur_max_bb_instrs); if (bb->cur_pc == NULL) { /* invalid instr or vmarea change: reset bb->cur_pc, will end bb * after updating stats */ bb->cur_pc = bb->instr_start; } /* We need the translation when mangling calls and jecxz/loop*. * May as well set it for all cti's since there's * really no extra overhead in doing so. Note that we go * through the above loop only once for cti's, so it's safe * to set the translation here. */ if (instr_opcode_valid(bb->instr) && (instr_is_cti(bb->instr) || bb->record_translation)) instr_set_translation(bb->instr, bb->instr_start); #ifdef HOT_PATCHING_INTERFACE /* If this lookup succeeds then the current bb needs to be patched. * In hotp_inject(), address lookup will be done for each instruction * pc in this bb and patching will be done if an exact match is found. * * Hot patching should be done only for app interp and recreating * pc, not for reproducing app code. Hence we use mangle_ilist. * See case 5981. * * FIXME: this lookup can further be reduced by determining whether or * not the current bb's module needs patching via check_new_page* */ if (DYNAMO_OPTION(hot_patching) && bb->mangle_ilist && !hotp_should_inject) { /* case 8780: we may hold the lock; FIXME: figure out if this can * be avoided - messy to hold hotp_vul_table lock like this for * unnecessary operations. */ bool owns_hotp_lock = self_owns_write_lock(hotp_get_lock()); if (hotp_does_region_need_patch(non_cti_start_pc, bb->cur_pc, owns_hotp_lock)) { BBPRINT(bb, 2, "hotpatch match in " PFX ": " PFX "-" PFX "\n", bb->start_pc, non_cti_start_pc, bb->cur_pc); hotp_should_inject = true; /* Don't elide if we are going to hot patch this bb because * the patch point can be a direct cti; eliding would result * in the patch not being applied. See case 5901. * FIXME: we could make this more efficient by only turning * off follow_direct if the instr is direct cti. */ bb->follow_direct = false; DOSTATS({ if (TEST(FRAG_HAS_DIRECT_CTI, bb->flags)) STATS_INC(hotp_num_frag_direct_cti); }); } } #endif if (bb->full_decode) { if (TEST(FRAG_SELFMOD_SANDBOXED, bb->flags) && instr_valid(bb->instr) && instr_writes_memory(bb->instr)) { /* to allow tailing non-writes, end prior to the write beyond the max */ total_writes++; if (total_writes > DYNAMO_OPTION(selfmod_max_writes)) { BBPRINT(bb, 3, "reached selfmod write limit %d, stopping\n", DYNAMO_OPTION(selfmod_max_writes)); STATS_INC(num_max_selfmod_writes_enforced); bb_stop_prior_to_instr(dcontext, bb, false /*not added to bb->ilist*/); break; } } } else if (bb->instr_start != non_cti_start_pc) { /* instr now holds the cti, so create an instr_t for the non-cti */ non_cti = instr_create(dcontext); IF_X64(ASSERT(CHECK_TRUNCATE_TYPE_uint(bb->instr_start - non_cti_start_pc))); instr_set_raw_bits(non_cti, non_cti_start_pc, (uint)(bb->instr_start - non_cti_start_pc)); if (bb->record_translation) instr_set_translation(non_cti, non_cti_start_pc); /* add non-cti instructions to instruction list */ instrlist_append(bb->ilist, non_cti); } DOSTATS({ /* This routine is also called for recreating state, we only want * to count app code when we build new bbs, which is indicated by * the bb->app_interp parameter */ if (bb->app_interp && !regenerated) { /* avoid double-counting for adaptive working set */ /* FIXME - ubr ellision leads to double couting. We also * double count when we have multiple entry points into the * same block of cti free instructinos. */ STATS_ADD(app_code_seen, (bb->cur_pc - non_cti_start_pc)); LOG(THREAD, LOG_INTERP, 5, "adding %d bytes to total app code seen\n", bb->cur_pc - non_cti_start_pc); } }); if (!instr_valid(bb->instr)) { bb_process_invalid_instr(dcontext, bb); break; } if (stop_bb_on_fallthrough) { bb_stop_prior_to_instr(dcontext, bb, false /*not appended*/); break; } #ifdef ANNOTATIONS # if !(defined(X64) && defined(WINDOWS)) /* Quickly check whether this may be a Valgrind annotation. */ if (is_decoded_valgrind_annotation_tail(bb->instr)) { /* Might be an annotation, so try the (slower) full check. */ if (is_encoded_valgrind_annotation(bb->instr_start, bb->start_pc, (app_pc)PAGE_START(bb->cur_pc))) { instrument_valgrind_annotation(dcontext, bb->ilist, bb->instr, bb->instr_start, bb->cur_pc, total_instrs); continue; } } else /* Top-level annotation recognition is unambiguous (xchg vs. jmp). */ # endif if (is_annotation_jump_over_dead_code(bb->instr)) { instr_t *substitution = NULL; if (instrument_annotation( dcontext, &bb->cur_pc, &substitution _IF_WINDOWS_X64(bb->cur_pc < bb->checked_end))) { instr_destroy(dcontext, bb->instr); if (substitution == NULL) continue; /* ignore annotation if no handlers are registered */ else bb->instr = substitution; } } #endif #ifdef WINDOWS if (DYNAMO_OPTION(process_SEH_push) && instr_get_prefix_flag(bb->instr, PREFIX_SEG_FS)) { DEBUG_DECLARE(ssize_t dbl_count = bb->cur_pc - bb->instr_start); if (!bb_process_fs_ref(dcontext, bb)) { DOSTATS({ if (bb->app_interp) { LOG(THREAD, LOG_INTERP, 3, "stopping bb at fs-using instr @ " PFX "\n", bb->instr_start); STATS_INC(num_process_SEH_bb_early_terminate); /* don't double count the fs instruction itself * since we removed it from this bb */ if (!regenerated) STATS_ADD(app_code_seen, -dbl_count); } }); break; } } #else # if defined(X86) && defined(LINUX) if (instr_get_prefix_flag(bb->instr, (SEG_TLS == SEG_GS) ? PREFIX_SEG_GS : PREFIX_SEG_FS) /* __errno_location is interpreted when global, though it's hidden in TOT */ IF_UNIX(&&!is_in_dynamo_dll(bb->instr_start)) && /* i#107 allows DR/APP using the same segment register. */ !INTERNAL_OPTION(mangle_app_seg)) { CLIENT_ASSERT(false, "no support for app using DR's segment w/o -mangle_app_seg"); ASSERT_BUG_NUM(205276, false); } # endif /* X86 */ #endif /* WINDOWS */ if (my_dcontext != NULL && my_dcontext->single_step_addr == bb->instr_start) { bb_process_single_step(dcontext, bb); /* Stops basic block right now. */ break; } /* far direct is treated as indirect (i#823) */ if (instr_is_near_ubr(bb->instr)) { if (bb_process_ubr(dcontext, bb)) continue; else { if (bb->instr != NULL) /* else, bb_process_ubr() set exit_type */ bb->exit_type |= instr_branch_type(bb->instr); break; } } else instrlist_append(bb->ilist, bb->instr); #ifdef RETURN_AFTER_CALL if (bb->app_interp && dynamo_options.ret_after_call) { if (instr_is_call(bb->instr)) { /* add after call instruction to valid return targets */ add_return_target(dcontext, bb->instr_start, bb->instr); } } #endif /* RETURN_AFTER_CALL */ #ifdef X64 /* must be prior to mbr check since mbr location could be rip-rel */ if (DYNAMO_OPTION(coarse_split_riprel) && DYNAMO_OPTION(coarse_units) && TEST(FRAG_COARSE_GRAIN, bb->flags) && instr_has_rel_addr_reference(bb->instr)) { if (instrlist_first(bb->ilist) != bb->instr) { /* have ref be in its own bb */ bb_stop_prior_to_instr(dcontext, bb, true /*appended already*/); break; /* stop bb */ } else { /* single-instr fine-grained bb */ bb->flags &= ~FRAG_COARSE_GRAIN; STATS_INC(coarse_prevent_riprel); } } #endif if (instr_is_near_call_direct(bb->instr)) { if (!bb_process_call_direct(dcontext, bb)) { if (bb->instr != NULL) bb->exit_type |= instr_branch_type(bb->instr); break; } } else if (instr_is_mbr(bb->instr) /* including indirect calls */ IF_X86( /* far direct is treated as indirect (i#823) */ || instr_get_opcode(bb->instr) == OP_jmp_far || instr_get_opcode(bb->instr) == OP_call_far) IF_ARM(/* mode-switch direct is treated as indirect */ || instr_get_opcode(bb->instr) == OP_blx)) { /* Manage the case where we don't need to perform 'normal' * indirect branch processing. */ bool normal_indirect_processing = true; bool elide_and_continue_if_converted = true; if (instr_is_return(bb->instr)) { bb->ibl_branch_type = IBL_RETURN; STATS_INC(num_returns); } else if (instr_is_call_indirect(bb->instr)) { STATS_INC(num_all_calls); STATS_INC(num_indirect_calls); if (DYNAMO_OPTION(coarse_split_calls) && DYNAMO_OPTION(coarse_units) && TEST(FRAG_COARSE_GRAIN, bb->flags)) { if (instrlist_first(bb->ilist) != bb->instr) { /* have call be in its own bb */ bb_stop_prior_to_instr(dcontext, bb, true /*appended already*/); break; /* stop bb */ } else { /* single-call fine-grained bb */ bb->flags &= ~FRAG_COARSE_GRAIN; STATS_INC(coarse_prevent_cti); } } /* If the indirect call can be converted into a direct one, * bypass normal indirect call processing. * First, check for a call* that we treat as a syscall. */ if (bb_process_indcall_syscall(dcontext, bb, &elide_and_continue_if_converted)) { normal_indirect_processing = false; } else if (DYNAMO_OPTION(indcall2direct) && bb_process_convertible_indcall(dcontext, bb)) { normal_indirect_processing = false; elide_and_continue_if_converted = true; } else if (DYNAMO_OPTION(IAT_convert) && bb_process_IAT_convertible_indcall( dcontext, bb, &elide_and_continue_if_converted)) { normal_indirect_processing = false; } else bb->ibl_branch_type = IBL_INDCALL; #ifdef X86 } else if (instr_get_opcode(bb->instr) == OP_jmp_far) { /* far direct is treated as indirect (i#823) */ bb->ibl_branch_type = IBL_INDJMP; } else if (instr_get_opcode(bb->instr) == OP_call_far) { /* far direct is treated as indirect (i#823) */ bb->ibl_branch_type = IBL_INDCALL; #elif defined(ARM) } else if (instr_get_opcode(bb->instr) == OP_blx) { /* mode-changing direct call is treated as indirect */ bb->ibl_branch_type = IBL_INDCALL; #endif /* X86 */ } else { /* indirect jump */ /* was prev instr a direct call? if so, this is a PLT-style ind call */ instr_t *prev = instr_get_prev(bb->instr); if (prev != NULL && instr_opcode_valid(prev) && instr_is_call_direct(prev)) { bb->exit_type |= INSTR_IND_JMP_PLT_EXIT; /* just because we have a CALL to JMP* makes it only a _likely_ PLT call, we still have to make sure it goes through IAT - see case 4269 */ STATS_INC(num_indirect_jumps_likely_PLT); } elide_and_continue_if_converted = true; if (DYNAMO_OPTION(IAT_convert) && bb_process_IAT_convertible_indjmp(dcontext, bb, &elide_and_continue_if_converted)) { /* Clear the IND_JMP_PLT_EXIT flag since we've converted * the PLT to a direct transition (and possibly elided). * Xref case 7867 for why leaving this flag in the eliding * case can cause later failures. */ bb->exit_type &= ~INSTR_CALL_EXIT; /* leave just JMP */ normal_indirect_processing = false; } else /* FIXME: this can always be set */ bb->ibl_branch_type = IBL_INDJMP; STATS_INC(num_indirect_jumps); } #ifdef CUSTOM_TRACES_RET_REMOVAL if (instr_is_return(bb->instr)) my_dcontext->num_rets++; else if (instr_is_call_indirect(bb->instr)) my_dcontext->num_calls++; #endif /* set exit type since this instruction will get mangled */ if (normal_indirect_processing) { bb->exit_type |= instr_branch_type(bb->instr); bb->exit_target = get_ibl_routine(dcontext, get_ibl_entry_type(bb->exit_type), DEFAULT_IBL_BB(), bb->ibl_branch_type); LOG(THREAD, LOG_INTERP, 4, "mbr exit target = " PFX "\n", bb->exit_target); break; } else { /* decide whether to stop bb here */ if (!elide_and_continue_if_converted) break; /* fall through for -max_bb_instrs check */ } } else if (instr_is_cti(bb->instr) && (!instr_is_call(bb->instr) || instr_is_cbr(bb->instr))) { total_branches++; if (total_branches >= BRANCH_LIMIT) { /* set type of 1st exit cti for cbr (bb->exit_type is for fall-through) */ instr_exit_branch_set_type(bb->instr, instr_branch_type(bb->instr)); break; } } else if (instr_is_syscall(bb->instr)) { if (!bb_process_syscall(dcontext, bb)) break; } /* end syscall */ else if (instr_get_opcode(bb->instr) == IF_X86_ELSE(OP_int, OP_svc)) { /* non-syscall int */ if (!bb_process_interrupt(dcontext, bb)) break; } #ifdef AARCH64 /* OP_isb, when mangled, has a potential side exit. */ else if (instr_get_opcode(bb->instr) == OP_isb) break; #endif #if 0 /*i#1313, i#1314*/ else if (instr_get_opcode(bb->instr) == OP_getsec) { /* XXX i#1313: if we support CPL0 in the future we'll need to * dynamically handle the leaf functions here, which can change eip * and other state. We'll need OP_getsec in decode_cti(). */ } else if (instr_get_opcode(bb->instr) == OP_xend || instr_get_opcode(bb->instr) == OP_xabort) { /* XXX i#1314: support OP_xend failing and setting eip to the * fallback pc recorded by OP_xbegin. We'll need both in decode_cti(). */ } #endif #ifdef CHECK_RETURNS_SSE2 /* There are SSE and SSE2 instrs that operate on MMX instead of XMM, but * we perform a simple coarse-grain check here. */ else if (instr_is_sse_or_sse2(bb->instr)) { FATAL_USAGE_ERROR(CHECK_RETURNS_SSE2_XMM_USED, 2, get_application_name(), get_application_pid()); } #endif #if defined(UNIX) && !defined(DGC_DIAGNOSTICS) && defined(X86) else if (instr_get_opcode(bb->instr) == OP_mov_seg) { if (!bb_process_mov_seg(dcontext, bb)) break; } #endif else if (instr_saves_float_pc(bb->instr)) { bb_process_float_pc(dcontext, bb); break; } if (bb->cur_pc == bb->stop_pc) { /* We only check stop_pc for full_decode, so not in inner loop. */ BBPRINT(bb, 3, "reached end pc " PFX ", stopping\n", bb->stop_pc); break; } if (total_instrs > DYNAMO_OPTION(max_bb_instrs)) { /* this could be an enormous basic block, or it could * be some degenerate infinite-loop case like a call * to a function that calls exit() and then calls itself, * so just end it here, we'll pick up where we left off * if it's legit */ BBPRINT(bb, 3, "reached -max_bb_instrs(%d): %d, ", DYNAMO_OPTION(max_bb_instrs), total_instrs); if (bb_safe_to_stop(dcontext, bb->ilist, NULL)) { BBPRINT(bb, 3, "stopping\n"); STATS_INC(num_max_bb_instrs_enforced); break; } else { /* XXX i#1669: cannot stop bb now, what's the best way to handle? * We can either roll-back and find previous safe stop point, or * simply extend the bb with a few more instructions. * We can always lower the -max_bb_instrs to offset the additional * instructions. In contrast, roll-back seems complex and * potentially problematic. */ BBPRINT(bb, 3, "cannot stop, continuing\n"); } } } /* end of while (true) */ KSTOP(bb_decoding); #ifdef DEBUG_MEMORY /* make sure anyone who destroyed also set to NULL */ ASSERT(bb->instr == NULL || (bb->instr->bytes != (byte *)HEAP_UNALLOCATED_PTR_UINT && bb->instr->bytes != (byte *)HEAP_ALLOCATED_PTR_UINT && bb->instr->bytes != (byte *)HEAP_PAD_PTR_UINT)); #endif if (!check_new_page_contig(dcontext, bb, bb->cur_pc - 1)) { ASSERT(false && "Should have checked cur_pc-1 in decode loop"); } bb->end_pc = bb->cur_pc; BBPRINT(bb, 3, "end_pc = " PFX "\n\n", bb->end_pc); /* We could put this in check_new_page_jmp where it already checks * for native_exec overlap, but selfmod ubrs don't even call that routine */ if (DYNAMO_OPTION(native_exec) && DYNAMO_OPTION(native_exec_callcall) && !vmvector_empty(native_exec_areas) && bb->app_interp && bb->instr != NULL && (instr_is_near_ubr(bb->instr) || instr_is_near_call_direct(bb->instr)) && instrlist_first(bb->ilist) == instrlist_last(bb->ilist)) { /* Case 4564/3558: handle .NET COM method table where a call* targets * a call to a native_exec dll -- we need to put the gateway at the * call* to avoid retaddr mangling of the method table call. * As a side effect we can also handle call*, jmp. * We don't actually verify or care that it was specifically a call*, * whatever at_native_exec_gateway() requires to assure itself that we're * at a return-address-clobberable point. */ app_pc tgt = opnd_get_pc(instr_get_target(bb->instr)); if (is_native_pc(tgt) && at_native_exec_gateway(dcontext, tgt, &bb->native_call _IF_DEBUG(true /*xfer tgt*/))) { /* replace this ilist w/ a native exec one */ LOG(THREAD, LOG_INTERP, 2, "direct xfer @gateway @" PFX " to native_exec module " PFX "\n", bb->start_pc, tgt); bb->native_exec = true; /* add this ubr/call to the native_exec_list, both as an optimization * for future entrances and b/c .NET changes its method table call * from targeting a native_exec image to instead target DGC directly, * thwarting our gateway! * FIXME: if heap region de-allocated, we'll remove, but what if re-used * w/o going through syscalls? Just written over w/ something else? * We'll keep it on native_exec_list... */ ASSERT(bb->end_pc == bb->start_pc + DIRECT_XFER_LENGTH); vmvector_add(native_exec_areas, bb->start_pc, bb->end_pc, NULL); DODEBUG({ report_native_module(dcontext, tgt); }); STATS_INC(num_native_module_entrances_callcall); return; } } #ifdef UNIX /* XXX: i#1247: After a call to a native module throught plt, DR * loses control of the app b/c of _dl_runtime_resolve */ int ret_imm; if (DYNAMO_OPTION(native_exec) && DYNAMO_OPTION(native_exec_opt) && bb->app_interp && bb->instr != NULL && instr_is_return(bb->instr) && at_dl_runtime_resolve_ret(dcontext, bb->start_pc, &ret_imm)) { dr_insert_clean_call(dcontext, bb->ilist, bb->instr, (void *)native_module_at_runtime_resolve_ret, false, 2, opnd_create_reg(REG_XSP), OPND_CREATE_INT32(ret_imm)); } #endif STATS_TRACK_MAX(max_instrs_in_a_bb, total_instrs); if (stop_bb_on_fallthrough && TEST(FRAG_HAS_DIRECT_CTI, bb->flags)) { /* If we followed a direct cti to an instruction straddling a vmarea * boundary, we can't actually do the elision. See the * sandbox_last_byte() test case in security-common/sandbox.c. Restart * bb building without follow_direct. Alternatively, we could check the * vmareas of the targeted instruction before performing elision. */ /* FIXME: a better assert is needed because this can trigger if * hot patching turns off follow_direct, the current bb was elided * earlier and is marked as selfmod. hotp_num_frag_direct_cti will * track this for now. */ ASSERT(bb->follow_direct); /* else, infinite loop possible */ BBPRINT(bb, 2, "*** must rebuild bb to avoid following direct cti to " "incompatible vmarea\n"); STATS_INC(num_bb_end_early); instrlist_clear_and_destroy(dcontext, bb->ilist); if (bb->vmlist != NULL) { vm_area_destroy_list(dcontext, bb->vmlist); bb->vmlist = NULL; } /* Remove FRAG_HAS_DIRECT_CTI, since we're turning off follow_direct. * Try to keep the known flags. We stopped the bb before merging in any * incompatible flags. */ bb->flags &= ~FRAG_HAS_DIRECT_CTI; bb->follow_direct = false; bb->exit_type = 0; /* i#577 */ bb->exit_target = NULL; /* i#928 */ /* overlap info will be reset by check_new_page_start */ build_bb_ilist(dcontext, bb); return; } if (TEST(FRAG_SELFMOD_SANDBOXED, bb->flags)) { ASSERT(bb->full_decode); ASSERT(!bb->follow_direct); ASSERT(!TEST(FRAG_HAS_DIRECT_CTI, bb->flags)); } #ifdef HOT_PATCHING_INTERFACE /* CAUTION: This can't be moved below client interface as the basic block * can be changed by the client. This will mess up hot patching. * The same is true for mangling. */ if (hotp_should_inject) { ASSERT(DYNAMO_OPTION(hot_patching)); hotp_injected = hotp_inject(dcontext, bb->ilist); /* Fix for 5272. Hot patch injection uses dr clean call api which * accesses dcontext fields directly, so the injected bbs can't be * shared until that is changed or the clean call mechanism is replaced * with bb termination to execute hot patchces. * Case 9995 assumes that hotp fragments are fine-grained, which we * achieve today by being private; if we make shared we must explicitly * prevent from being coarse-grained. */ if (hotp_injected) { bb->flags &= ~FRAG_SHARED; bb->flags |= FRAG_CANNOT_BE_TRACE; } } #endif /* Until we're more confident in our decoder/encoder consistency this is * at the default debug build -checklevel 2. */ IF_ARM(DOCHECK(2, check_encode_decode_consistency(dcontext, bb->ilist);)); #ifdef DR_APP_EXPORTS /* changes by DR that are visible to clients */ mangle_pre_client(dcontext, bb); #endif /* DR_APP_EXPORTS */ #ifdef DEBUG /* This is a special debugging feature */ if (bb->for_cache && INTERNAL_OPTION(go_native_at_bb_count) > 0 && debug_bb_count++ >= INTERNAL_OPTION(go_native_at_bb_count)) { SYSLOG_INTERNAL_INFO("thread " TIDFMT " is going native @%d bbs to " PFX, d_r_get_thread_id(), debug_bb_count - 1, bb->start_pc); /* we leverage the existing native_exec mechanism */ dcontext->native_exec_postsyscall = bb->start_pc; dcontext->next_tag = BACK_TO_NATIVE_AFTER_SYSCALL; dynamo_thread_not_under_dynamo(dcontext); IF_UNIX(os_swap_context(dcontext, true /*to app*/, DR_STATE_GO_NATIVE)); /* i#1921: for now we do not support re-attach, so remove handlers */ os_process_not_under_dynamorio(dcontext); bb_build_abort(dcontext, true /*free vmlist*/, false /*don't unlock*/); return; } #endif if (!client_process_bb(dcontext, bb)) { bb_build_abort(dcontext, true /*free vmlist*/, false /*don't unlock*/); return; } /* i#620: provide API to set fall-through and retaddr targets at end of bb */ if (instrlist_get_return_target(bb->ilist) != NULL || instrlist_get_fall_through_target(bb->ilist) != NULL) { CLIENT_ASSERT(instr_is_cbr(instrlist_last(bb->ilist)) || instr_is_call(instrlist_last(bb->ilist)), "instr_set_return_target/instr_set_fall_through_target" " can only be used in a bb ending with call/cbr"); /* the bb cannot be added to a trace */ bb->flags |= FRAG_CANNOT_BE_TRACE; } if (bb->unmangled_ilist != NULL) *bb->unmangled_ilist = instrlist_clone(dcontext, bb->ilist); if (bb->instr != NULL && instr_opcode_valid(bb->instr) && instr_is_far_cti(bb->instr)) { /* Simplify far_ibl (i#823) vs trace_cmp ibl as well as * cross-mode direct stubs varying in a trace by disallowing * far cti in middle of trace */ bb->flags |= FRAG_MUST_END_TRACE; /* Simplify coarse by not requiring extra prefix stubs */ bb->flags &= ~FRAG_COARSE_GRAIN; } /* create a final instruction that will jump to the exit stub * corresponding to the fall-through of the conditional branch or * the target of the final indirect branch (the indirect branch itself * will get mangled into a non-cti) */ if (bb->exit_target == NULL) { /* not set by ind branch, etc. */ /* fall-through pc */ /* i#620: provide API to set fall-through target at end of bb */ bb->exit_target = instrlist_get_fall_through_target(bb->ilist); if (bb->exit_target == NULL) bb->exit_target = (cache_pc)bb->cur_pc; else { LOG(THREAD, LOG_INTERP, 3, "set fall-throught target " PFX " by client\n", bb->exit_target); } if (bb->instr != NULL && instr_opcode_valid(bb->instr) && instr_is_cbr(bb->instr) && (int)(bb->exit_target - bb->start_pc) <= SHRT_MAX && (int)(bb->exit_target - bb->start_pc) >= SHRT_MIN && /* rule out jecxz, etc. */ !instr_is_cti_loop(bb->instr)) bb->flags |= FRAG_CBR_FALLTHROUGH_SHORT; } /* we share all basic blocks except selfmod (since want no-synch quick deletion) * or syscall-containing ones (to bound delay on threads exiting shared cache, * for cache management, both consistency and capacity) * bbs injected with hot patches are also not shared (see case 5272). */ if (DYNAMO_OPTION(shared_bbs) && !TEST(FRAG_SELFMOD_SANDBOXED, bb->flags) && !TEST(FRAG_TEMP_PRIVATE, bb->flags) #ifdef HOT_PATCHING_INTERFACE && !hotp_injected #endif && (my_dcontext == NULL || my_dcontext->single_step_addr != bb->instr_start)) { /* If the fragment doesn't have a syscall or contains a * non-ignorable one -- meaning that the frag will exit the cache * to execute the syscall -- it can be shared. * We don't support ignorable syscalls in shared fragments, as they * don't set at_syscall and so are incompatible w/ -syscalls_synch_flush. */ if (!TEST(FRAG_HAS_SYSCALL, bb->flags) || TESTANY(LINK_NI_SYSCALL_ALL, bb->exit_type) || TEST(LINK_SPECIAL_EXIT, bb->exit_type)) bb->flags |= FRAG_SHARED; #ifdef WINDOWS /* A fragment can be shared if it contains a syscall that will be * executed via the version of shared syscall that can be targetted by * shared frags. */ else if (TEST(FRAG_HAS_SYSCALL, bb->flags) && DYNAMO_OPTION(shared_fragment_shared_syscalls) && bb->exit_target == shared_syscall_routine(dcontext)) bb->flags |= FRAG_SHARED; else { ASSERT((TEST(FRAG_HAS_SYSCALL, bb->flags) && (DYNAMO_OPTION(ignore_syscalls) || (!DYNAMO_OPTION(shared_fragment_shared_syscalls) && bb->exit_target == shared_syscall_routine(dcontext)))) && "BB not shared for unknown reason"); } #endif } else if (my_dcontext != NULL && my_dcontext->single_step_addr == bb->instr_start) { /* Field exit_type might have been cleared by client_process_bb. */ bb->exit_type |= LINK_SPECIAL_EXIT; } if (TEST(FRAG_COARSE_GRAIN, bb->flags) && (!TEST(FRAG_SHARED, bb->flags) || /* Ignorable syscalls on linux are mangled w/ intra-fragment jmps, which * decode_fragment() cannot handle -- and on win32 this overlaps w/ * FRAG_MUST_END_TRACE and LINK_NI_SYSCALL */ TEST(FRAG_HAS_SYSCALL, bb->flags) || TEST(FRAG_MUST_END_TRACE, bb->flags) || TEST(FRAG_CANNOT_BE_TRACE, bb->flags) || TEST(FRAG_SELFMOD_SANDBOXED, bb->flags) || /* PR 214142: coarse units does not support storing translations */ TEST(FRAG_HAS_TRANSLATION_INFO, bb->flags) || /* FRAG_HAS_DIRECT_CTI: we never elide (assert is below); * not-inlined call/jmp: we turn off FRAG_COARSE_GRAIN up above */ #ifdef WINDOWS TEST(LINK_CALLBACK_RETURN, bb->exit_type) || #endif TESTANY(LINK_NI_SYSCALL_ALL, bb->exit_type))) { /* Currently not supported in a coarse unit */ STATS_INC(num_fine_in_coarse); DOSTATS({ if (!TEST(FRAG_SHARED, bb->flags)) STATS_INC(coarse_prevent_private); else if (TEST(FRAG_HAS_SYSCALL, bb->flags)) STATS_INC(coarse_prevent_syscall); else if (TEST(FRAG_MUST_END_TRACE, bb->flags)) STATS_INC(coarse_prevent_end_trace); else if (TEST(FRAG_CANNOT_BE_TRACE, bb->flags)) STATS_INC(coarse_prevent_no_trace); else if (TEST(FRAG_SELFMOD_SANDBOXED, bb->flags)) STATS_INC(coarse_prevent_selfmod); else if (TEST(FRAG_HAS_TRANSLATION_INFO, bb->flags)) STATS_INC(coarse_prevent_translation); else if (IF_WINDOWS_ELSE_0(TEST(LINK_CALLBACK_RETURN, bb->exit_type))) STATS_INC(coarse_prevent_cbret); else if (TESTANY(LINK_NI_SYSCALL_ALL, bb->exit_type)) STATS_INC(coarse_prevent_syscall); else ASSERT_NOT_REACHED(); }); bb->flags &= ~FRAG_COARSE_GRAIN; } ASSERT(!TEST(FRAG_COARSE_GRAIN, bb->flags) || !TEST(FRAG_HAS_DIRECT_CTI, bb->flags)); /* now that we know whether shared, ensure we have the right ibl routine */ if (!TEST(FRAG_SHARED, bb->flags) && TEST(LINK_INDIRECT, bb->exit_type)) { ASSERT(bb->exit_target == get_ibl_routine(dcontext, get_ibl_entry_type(bb->exit_type), DEFAULT_IBL_BB(), bb->ibl_branch_type)); bb->exit_target = get_ibl_routine(dcontext, get_ibl_entry_type(bb->exit_type), IBL_BB_PRIVATE, bb->ibl_branch_type); } if (bb->mangle_ilist && (bb->instr == NULL || !instr_opcode_valid(bb->instr) || !instr_is_near_ubr(bb->instr) || instr_is_meta(bb->instr))) { instr_t *exit_instr = XINST_CREATE_jump(dcontext, opnd_create_pc(bb->exit_target)); if (bb->record_translation) { app_pc translation = NULL; if (bb->instr == NULL || !instr_opcode_valid(bb->instr)) { /* we removed (or mangle will remove) the last instruction * for special handling (invalid/syscall/int 2b) or there were * no instructions added (i.e. check_stopping_point in which * case instr_start == cur_pc), use last instruction's start * address for the translation */ translation = bb->instr_start; } else if (instr_is_cti(bb->instr)) { /* last instruction is a cti, consider the exit jmp part of * the mangling of the cti (since we might not know the target * if, for ex., its indirect) */ translation = instr_get_translation(bb->instr); } else { /* target is the instr after the last instr in the list */ translation = bb->cur_pc; ASSERT(bb->cur_pc == bb->exit_target); } ASSERT(translation != NULL); instr_set_translation(exit_instr, translation); } /* PR 214962: we need this jmp to be marked as "our mangling" so that * we won't relocate a thread there and re-do a ret pop or call push */ instr_set_our_mangling(exit_instr, true); /* here we need to set exit_type */ LOG(THREAD, LOG_EMIT, 3, "exit_branch_type=0x%x bb->exit_target=" PFX "\n", bb->exit_type, bb->exit_target); instr_exit_branch_set_type(exit_instr, bb->exit_type); instrlist_append(bb->ilist, exit_instr); #ifdef ARM if (bb->svc_pred != DR_PRED_NONE) { /* we have a conditional syscall, add predicate to current exit */ instr_set_predicate(exit_instr, bb->svc_pred); /* add another ubr exit as the fall-through */ exit_instr = XINST_CREATE_jump(dcontext, opnd_create_pc(bb->exit_target)); if (bb->record_translation) instr_set_translation(exit_instr, bb->cur_pc); instr_set_our_mangling(exit_instr, true); instr_exit_branch_set_type(exit_instr, LINK_DIRECT | LINK_JMP); instrlist_append(bb->ilist, exit_instr); /* XXX i#1734: instr svc.cc will be deleted later in mangle_syscall, * so we need reset encode state to avoid holding a dangling pointer. */ encode_reset_it_block(dcontext); } #endif } /* set flags */ #ifdef DGC_DIAGNOSTICS /* no traces in dyngen code, that would mess up our exit tracking */ if (TEST(FRAG_DYNGEN, bb->flags)) bb->flags |= FRAG_CANNOT_BE_TRACE; #endif if (!INTERNAL_OPTION(unsafe_ignore_eflags_prefix) IF_X64(|| !INTERNAL_OPTION(unsafe_ignore_eflags_trace))) { bb->flags |= instr_eflags_to_fragment_eflags(bb->eflags); if (TEST(FRAG_WRITES_EFLAGS_OF, bb->flags)) { LOG(THREAD, LOG_INTERP, 4, "fragment writes OF prior to reading it!\n"); STATS_INC(bbs_eflags_writes_of); } else if (TEST(FRAG_WRITES_EFLAGS_6, bb->flags)) { IF_X86(ASSERT(TEST(FRAG_WRITES_EFLAGS_OF, bb->flags))); LOG(THREAD, LOG_INTERP, 4, "fragment writes all 6 flags prior to reading any\n"); STATS_INC(bbs_eflags_writes_6); } else { DOSTATS({ if (bb->eflags == EFLAGS_READ_ARITH) { /* Reads a flag before writing any. Won't get here if * reads one flag and later writes OF, or writes OF and * later reads one flag before writing that flag. */ STATS_INC(bbs_eflags_reads); } else { STATS_INC(bbs_eflags_writes_none); if (TEST(LINK_INDIRECT, bb->exit_type)) STATS_INC(bbs_eflags_writes_none_ind); } }); } } /* can only have proactive translation info if flag was set from the beginning */ if (TEST(FRAG_HAS_TRANSLATION_INFO, bb->flags) && (!bb->record_translation || !bb->full_decode)) bb->flags &= ~FRAG_HAS_TRANSLATION_INFO; /* if for_cache, caller must clear once done emitting (emitting can deref * app memory so we wait until all done) */ if (!bb_build_nested && !bb->for_cache && my_dcontext != NULL) { ASSERT(my_dcontext->bb_build_info == (void *)bb); my_dcontext->bb_build_info = NULL; } bb->instr = NULL; /* mangle the instruction list */ if (!bb->mangle_ilist) { /* do not mangle! * caller must use full_decode to find invalid instrs and avoid * a discrepancy w/ for_cache case that aborts b/c of selfmod sandbox * returning false (in code below) */ return; } if (!mangle_bb_ilist(dcontext, bb)) { /* have to rebuild bb w/ new bb flags set by mangle_bb_ilist */ build_bb_ilist(dcontext, bb); return; } } /* Call when about to throw exception or other drastic action in the * middle of bb building, in order to free resources */ void bb_build_abort(dcontext_t *dcontext, bool clean_vmarea, bool unlock) { ASSERT(dcontext->bb_build_info != NULL); /* caller should check */ if (dcontext->bb_build_info != NULL) { build_bb_t *bb = (build_bb_t *)dcontext->bb_build_info; /* free instr memory */ if (bb->instr != NULL && bb->ilist != NULL && instrlist_last(bb->ilist) != bb->instr) instr_destroy(dcontext, bb->instr); /* not added to bb->ilist yet */ DODEBUG({ bb->instr = NULL; }); if (bb->ilist != NULL) { instrlist_clear_and_destroy(dcontext, bb->ilist); DODEBUG({ bb->ilist = NULL; }); } if (clean_vmarea) { /* Free the vmlist and any locks held (we could have been in * the middle of check_thread_vm_area and had a decode fault * during code origins checking!) */ check_thread_vm_area_abort(dcontext, &bb->vmlist, bb->flags); } /* else we were presumably called from vmarea so caller does cleanup */ if (unlock) { /* Assumption: bb building lock is held iff bb->for_cache, * and on a nested app bb build where !bb->for_cache we do keep the * original bb info in dcontext (see build_bb_ilist()). */ if (bb->has_bb_building_lock) { ASSERT_OWN_MUTEX(USE_BB_BUILDING_LOCK(), &bb_building_lock); SHARED_BB_UNLOCK(); KSTOP_REWIND(bb_building); } else ASSERT_DO_NOT_OWN_MUTEX(USE_BB_BUILDING_LOCK(), &bb_building_lock); } dcontext->bb_build_info = NULL; } } bool expand_should_set_translation(dcontext_t *dcontext) { if (dcontext->bb_build_info != NULL) { build_bb_t *bb = (build_bb_t *)dcontext->bb_build_info; /* Expanding to a higher level should set the translation to * the raw bytes if we're building a bb where we can assume * the raw byte pointer is the app pc. */ return bb->record_translation; } return false; } /* returns false if need to rebuild bb: in that case this routine will * set the bb flags needed to ensure successful mangling 2nd time around */ static bool mangle_bb_ilist(dcontext_t *dcontext, build_bb_t *bb) { #ifdef X86 if (TEST(FRAG_SELFMOD_SANDBOXED, bb->flags)) { byte *selfmod_start, *selfmod_end; /* sandbox requires that bb have no direct cti followings! * check_thread_vm_area should have ensured this for us */ ASSERT(!TEST(FRAG_HAS_DIRECT_CTI, bb->flags)); LOG(THREAD, LOG_INTERP, 2, "fragment overlaps selfmod area, inserting sandboxing\n"); /* only reason can't be trace is don't have mechanism set up * to store app code for each trace bb and update sandbox code * to point there */ bb->flags |= FRAG_CANNOT_BE_TRACE; if (bb->pretend_pc != NULL) { selfmod_start = bb->pretend_pc; selfmod_end = bb->pretend_pc + (bb->cur_pc - bb->start_pc); } else { selfmod_start = bb->start_pc; selfmod_end = bb->cur_pc; } if (!insert_selfmod_sandbox(dcontext, bb->ilist, bb->flags, selfmod_start, selfmod_end, bb->record_translation, bb->for_cache)) { /* have to rebuild bb using full decode -- it has invalid instrs * in middle, which we don't want to deal w/ for sandboxing! */ ASSERT(!bb->full_decode); /* else, how did we get here??? */ LOG(THREAD, LOG_INTERP, 2, "*** must rebuild bb to avoid invalid instr in middle ***\n"); STATS_INC(num_bb_end_early); instrlist_clear_and_destroy(dcontext, bb->ilist); if (bb->vmlist != NULL) { vm_area_destroy_list(dcontext, bb->vmlist); bb->vmlist = NULL; } bb->flags = FRAG_SELFMOD_SANDBOXED; /* lose all other flags */ bb->full_decode = true; /* full decode this time! */ bb->follow_direct = false; bb->exit_type = 0; /* i#577 */ bb->exit_target = NULL; /* i#928 */ /* overlap info will be reset by check_new_page_start */ return false; } STATS_INC(num_sandboxed_fragments); } #endif /* X86 */ DOLOG(4, LOG_INTERP, { LOG(THREAD, LOG_INTERP, 4, "bb ilist before mangling:\n"); instrlist_disassemble(dcontext, bb->start_pc, bb->ilist, THREAD); }); d_r_mangle(dcontext, bb->ilist, &bb->flags, true, bb->record_translation); DOLOG(4, LOG_INTERP, { LOG(THREAD, LOG_INTERP, 4, "bb ilist after mangling:\n"); instrlist_disassemble(dcontext, bb->start_pc, bb->ilist, THREAD); }); return true; } /* Interprets the application's instructions until the end of a basic * block is found, following all the rules that build_bb_ilist follows * with regard to terminating the block. Does no mangling or anything of * the app code, though -- this routine is intended only for building the * original code! * Caller is responsible for freeing the list and its instrs! * If outf != INVALID_FILE, does full disassembly with comments to outf. */ instrlist_t * build_app_bb_ilist(dcontext_t *dcontext, byte *start_pc, file_t outf) { build_bb_t bb; init_build_bb(&bb, start_pc, false /*not interp*/, false /*not for cache*/, false /*do not mangle*/, false /*no translation*/, outf, 0 /*no pre flags*/, NULL /*no overlap*/); build_bb_ilist(dcontext, &bb); return bb.ilist; } /* Client routine to decode instructions at an arbitrary app address, * following all the rules that DynamoRIO follows internally for * terminating basic blocks. Note that DynamoRIO does not validate * that start_pc is actually the first instruction of a basic block. * \note Caller is reponsible for freeing the list and its instrs! */ instrlist_t * decode_as_bb(void *drcontext, byte *start_pc) { build_bb_t bb; /* Case 10009: When we hook ntdll functions, we hide the jump to * the interception buffer from the client BB callback. If the * client asks to decode that address here, we need to decode the * instructions in the interception buffer instead so that we * again hide our hooking. * We will have the jmp from the buffer back to after the hooked * app code visible to the client (just like it is for the * real bb built there, so at least we're consistent). */ #ifdef WINDOWS byte *real_pc; if (is_intercepted_app_pc((app_pc)start_pc, &real_pc)) start_pc = real_pc; #endif init_build_bb(&bb, start_pc, false /*not interp*/, false /*not for cache*/, false /*do not mangle*/, true, /* translation; xref case 10070 where this * currently turns on full decode; today we * provide no way to turn that off, as IR * expansion routines are not exported (PR 200409). */ INVALID_FILE, 0 /*no pre flags*/, NULL /*no overlap*/); build_bb_ilist((dcontext_t *)drcontext, &bb); return bb.ilist; } /* Client routine to decode a trace. We return the instructions in * the original app code, i.e., no client modifications. */ instrlist_t * decode_trace(void *drcontext, void *tag) { dcontext_t *dcontext = (dcontext_t *)drcontext; fragment_t *frag = fragment_lookup(dcontext, tag); /* We don't support asking about other threads, for synch purposes * (see recreate_fragment_ilist() synch notes) */ if (get_thread_private_dcontext() != dcontext) return NULL; if (frag != NULL && TEST(FRAG_IS_TRACE, frag->flags)) { instrlist_t *ilist; bool alloc_res; /* Support being called from bb/trace hook (couldbelinking) or * from cache clean call (nolinking). We disallow asking about * another thread's private traces. */ if (!is_couldbelinking(dcontext)) d_r_mutex_lock(&thread_initexit_lock); ilist = recreate_fragment_ilist(dcontext, NULL, &frag, &alloc_res, false /*no mangling*/, false /*do not re-call client*/); ASSERT(!alloc_res); if (!is_couldbelinking(dcontext)) d_r_mutex_unlock(&thread_initexit_lock); return ilist; } return NULL; } app_pc find_app_bb_end(dcontext_t *dcontext, byte *start_pc, uint flags) { build_bb_t bb; init_build_bb(&bb, start_pc, false /*not interp*/, false /*not for cache*/, false /*do not mangle*/, false /*no translation*/, INVALID_FILE, flags, NULL /*no overlap*/); build_bb_ilist(dcontext, &bb); instrlist_clear_and_destroy(dcontext, bb.ilist); return bb.end_pc; } bool app_bb_overlaps(dcontext_t *dcontext, byte *start_pc, uint flags, byte *region_start, byte *region_end, overlap_info_t *info_res) { build_bb_t bb; overlap_info_t info; info.region_start = region_start; info.region_end = region_end; init_build_bb(&bb, start_pc, false /*not interp*/, false /*not for cache*/, false /*do not mangle*/, false /*no translation*/, INVALID_FILE, flags, &info); build_bb_ilist(dcontext, &bb); instrlist_clear_and_destroy(dcontext, bb.ilist); info.bb_end = bb.end_pc; if (info_res != NULL) *info_res = info; return info.overlap; } #ifdef DEBUG static void report_native_module(dcontext_t *dcontext, app_pc modpc) { char name[MAX_MODNAME_INTERNAL]; const char *modname = name; if (os_get_module_name_buf(modpc, name, BUFFER_SIZE_ELEMENTS(name)) == 0) { /* for native_exec_callcall we do end up putting DGC on native_exec_list */ ASSERT(DYNAMO_OPTION(native_exec_callcall)); modname = "<DGC>"; } LOG(THREAD, LOG_INTERP | LOG_VMAREAS, 2, "module %s is on native list, executing natively\n", modname); STATS_INC(num_native_module_entrances); SYSLOG_INTERNAL_WARNING_ONCE("module %s set up for native execution", modname); } #endif /* WARNING: breaks all kinds of rules, like ret addr transparency and * assuming app stack and not doing calls out of the cache and not having * control during dll loads, etc... */ static void build_native_exec_bb(dcontext_t *dcontext, build_bb_t *bb) { instr_t *in; opnd_t jmp_tgt; #if defined(X86) && defined(X64) bool reachable = rel32_reachable_from_vmcode(bb->start_pc); #endif DEBUG_DECLARE(bool ok;) /* if we ever protect from simultaneous thread attacks then this will * be a hole -- for now should work, all protected while native until * another thread goes into DR */ /* Create a bb that changes the return address on the app stack such that we * will take control when coming back, and then goes native. * N.B.: we ASSUME we reached this moduled via a call -- * build_basic_block_fragment needs to make sure, since we can't verify here * w/o trying to decode backward from retaddr, and if we're wrong we'll * clobber the stack and never regain control! * We also assume this bb is never reached later through a non-call. */ ASSERT(bb->initialized); ASSERT(bb->app_interp); ASSERT(!bb->record_translation); ASSERT(bb->start_pc != NULL); /* vmlist must start out empty (or N/A). For clients it may have started early. */ ASSERT(bb->vmlist == NULL || !bb->record_vmlist || bb->checked_start_vmarea); if (TEST(FRAG_HAS_TRANSLATION_INFO, bb->flags)) bb->flags &= ~FRAG_HAS_TRANSLATION_INFO; bb->native_exec = true; BBPRINT(bb, IF_DGCDIAG_ELSE(1, 2), "build_native_exec_bb @" PFX "\n", bb->start_pc); DOLOG(2, LOG_INTERP, { dump_mcontext(get_mcontext(dcontext), THREAD, DUMP_NOT_XML); }); if (!bb->checked_start_vmarea) check_new_page_start(dcontext, bb); /* create instrlist after check_new_page_start to avoid memory leak * on unreadable memory * WARNING: do not add any app instructions to this ilist! * If you do you must enable selfmod below. */ bb->ilist = instrlist_create(dcontext); /* FIXME PR 303413: we won't properly translate a fault in our app * stack references here. We mark as our own mangling so we'll at * least return failure from our translate routine. */ instrlist_set_our_mangling(bb->ilist, true); /* get dcontext to xdi, for prot-dcontext, xsi holds upcontext too */ insert_shared_get_dcontext(dcontext, bb->ilist, NULL, true /*save xdi*/); instrlist_append(bb->ilist, instr_create_save_to_dc_via_reg(dcontext, REG_NULL /*default*/, SCRATCH_REG0, SCRATCH_REG0_OFFS)); /* need some cleanup prior to native: turn off asynch, clobber trace, etc. * Now that we have a stack of native retaddrs, we save the app retaddr in C * code. */ if (bb->native_call) { dr_insert_clean_call_ex(dcontext, bb->ilist, NULL, (void *)call_to_native, DR_CLEANCALL_RETURNS_TO_NATIVE, 1, opnd_create_reg(REG_XSP)); } else { if (DYNAMO_OPTION(native_exec_opt)) { insert_return_to_native(dcontext, bb->ilist, NULL, REG_NULL /* default */, SCRATCH_REG0); } else { dr_insert_clean_call_ex(dcontext, bb->ilist, NULL, (void *)return_to_native, DR_CLEANCALL_RETURNS_TO_NATIVE, 0); } } #if defined(X86) && defined(X64) if (!reachable) { /* best to store the target at the end of the bb, to keep it readonly, * but that requires a post-pass to patch its value: since native_exec * is already hacky we just go through TLS and ignore multi-thread selfmod. */ instrlist_append( bb->ilist, INSTR_CREATE_mov_imm(dcontext, opnd_create_reg(SCRATCH_REG0), OPND_CREATE_INTPTR((ptr_int_t)bb->start_pc))); if (X64_CACHE_MODE_DC(dcontext) && !X64_MODE_DC(dcontext) && DYNAMO_OPTION(x86_to_x64_ibl_opt)) { jmp_tgt = opnd_create_reg(REG_R9); } else { jmp_tgt = opnd_create_tls_slot(os_tls_offset(MANGLE_XCX_SPILL_SLOT)); } instrlist_append( bb->ilist, INSTR_CREATE_mov_st(dcontext, jmp_tgt, opnd_create_reg(REG_XAX))); } else #endif { jmp_tgt = opnd_create_pc(bb->start_pc); } instrlist_append(bb->ilist, instr_create_restore_from_dc_via_reg(dcontext, REG_NULL /*default*/, SCRATCH_REG0, SCRATCH_REG0_OFFS)); insert_shared_restore_dcontext_reg(dcontext, bb->ilist, NULL); #ifdef AARCH64 ASSERT_NOT_IMPLEMENTED(false); /* FIXME i#1569 */ #else /* this is the jump to native code */ instrlist_append(bb->ilist, opnd_is_pc(jmp_tgt) ? XINST_CREATE_jump(dcontext, jmp_tgt) : XINST_CREATE_jump_mem(dcontext, jmp_tgt)); #endif /* mark all as do-not-mangle, so selfmod, etc. will leave alone (in absence * of selfmod only really needed for the jmp to native code) */ for (in = instrlist_first(bb->ilist); in != NULL; in = instr_get_next(in)) instr_set_meta(in); /* this is a jump for a dummy exit cti */ instrlist_append(bb->ilist, XINST_CREATE_jump(dcontext, opnd_create_pc(bb->start_pc))); if (DYNAMO_OPTION(shared_bbs) && !TEST(FRAG_TEMP_PRIVATE, bb->flags)) bb->flags |= FRAG_SHARED; /* Can't be coarse-grain since has non-exit cti */ bb->flags &= ~FRAG_COARSE_GRAIN; STATS_INC(coarse_prevent_native_exec); /* We exclude the bb from trace to avoid going native in the process of * building a trace for simplicity. * XXX i#1239: DR needs to be able to unlink native exec gateway bbs for * proper cache consistency and signal handling, in which case we could * use FRAG_MUST_END_TRACE here instead. */ bb->flags |= FRAG_CANNOT_BE_TRACE; /* We support mangling here, though currently we don't need it as we don't * include any app code (although we mark this bb as belonging to the start * pc, so we'll get flushed if this region does), and even if target is * selfmod we're running it natively no matter how it modifies itself. We * only care that transition to target is via a call or call* so we can * clobber the retaddr and regain control, and that no retaddr mangling * happens while native before coming back out. While the former does not * depend on the target at all, unfortunately we cannot verify the latter. */ if (TEST(FRAG_SELFMOD_SANDBOXED, bb->flags)) bb->flags &= ~FRAG_SELFMOD_SANDBOXED; DEBUG_DECLARE(ok =) mangle_bb_ilist(dcontext, bb); ASSERT(ok); #ifdef DEBUG DOLOG(3, LOG_INTERP, { LOG(THREAD, LOG_INTERP, 3, "native_exec_bb @" PFX "\n", bb->start_pc); instrlist_disassemble(dcontext, bb->start_pc, bb->ilist, THREAD); }); #endif } static bool at_native_exec_gateway(dcontext_t *dcontext, app_pc start, bool *is_call _IF_DEBUG(bool xfer_target)) { /* ASSUMPTION: transfer to another module will always be by indirect call * or non-inlined direct call from a fragment that will not be flushed. * For now we will only go native if last_exit was * a call, a true call*, or a PLT-style call,jmp* (and we detect the latter only * if the call is inlined, so if the jmp* table is in a DGC-marked region * or if -no_inline_calls we will miss these: FIXME). * FIXME: what if have PLT-style but no GOT indirection: call,jmp ?!? * * We try to identify funky call* constructions (like * call*,...,jmp* in case 4269) by examining TOS to see whether it's a * retaddr -- we do this if last_exit is a jmp* or is unknown (for the * target_delete ibl path). * * FIXME: we will fail to identify a delay-loaded indirect xfer! * Need to know dynamic link patchup code to look for. * * FIXME: we will fail to take over w/ non-call entrances to a dll, like * NtContinue or direct jmp from DGC. * we could try to take the top-of-stack value and see if it's a retaddr by * decoding the prev instr to see if it's a call. decode backwards may have * issues, and if really want everything will have to do this on every bb, * not just if lastexit is ind xfer. * * We count up easy-to-identify cases we've missed in the DOSTATS below. */ bool native_exec_bb = false; /* We can get here if we start interpreting native modules. */ ASSERT(start != (app_pc)back_from_native && start != (app_pc)native_module_callout && "interpreting return from native module?"); ASSERT(is_call != NULL); *is_call = false; if (DYNAMO_OPTION(native_exec) && !vmvector_empty(native_exec_areas)) { /* do we KNOW that we came from an indirect call? */ if (TEST(LINK_CALL /*includes IND_JMP_PLT*/, dcontext->last_exit->flags) && /* only check direct calls if native_exec_dircalls is on */ (DYNAMO_OPTION(native_exec_dircalls) || LINKSTUB_INDIRECT(dcontext->last_exit->flags))) { STATS_INC(num_native_entrance_checks); /* we do the overlap check last since it's more costly */ if (is_native_pc(start)) { native_exec_bb = true; *is_call = true; DOSTATS({ if (EXIT_IS_CALL(dcontext->last_exit->flags)) { if (LINKSTUB_INDIRECT(dcontext->last_exit->flags)) STATS_INC(num_native_module_entrances_indcall); else STATS_INC(num_native_module_entrances_call); } else STATS_INC(num_native_module_entrances_plt); }); } } /* can we GUESS that we came from an indirect call? */ else if (DYNAMO_OPTION(native_exec_guess_calls) && (/* FIXME: require jmp* be in separate module? */ (LINKSTUB_INDIRECT(dcontext->last_exit->flags) && EXIT_IS_JMP(dcontext->last_exit->flags)) || LINKSTUB_FAKE(dcontext->last_exit))) { /* if unknown last exit, or last exit was jmp*, examine TOS and guess * whether it's a retaddr */ app_pc *tos = (app_pc *)get_mcontext(dcontext)->xsp; STATS_INC(num_native_entrance_TOS_checks); /* vector check cheaper than is_readable syscall, etc. so do it before them, * but after last_exit checks above since overlap is more costly */ if (is_native_pc(start) && is_readable_without_exception((app_pc)tos, sizeof(app_pc))) { enum { MAX_CALL_CONSIDER = 6 /* ignore prefixes */ }; app_pc retaddr = *tos; LOG(THREAD, LOG_INTERP | LOG_VMAREAS, 2, "at native_exec target: checking TOS " PFX " => " PFX " for retaddr\n", tos, retaddr); #ifdef RETURN_AFTER_CALL if (DYNAMO_OPTION(ret_after_call)) { native_exec_bb = is_observed_call_site(dcontext, retaddr); *is_call = true; LOG(THREAD, LOG_INTERP | LOG_VMAREAS, 2, "native_exec: *TOS is %sa call site in ret-after-call table\n", native_exec_bb ? "" : "NOT "); } else { #endif /* try to decode backward -- make sure readable for decoding */ if (is_readable_without_exception(retaddr - MAX_CALL_CONSIDER, MAX_CALL_CONSIDER + MAX_INSTR_LENGTH)) { /* ind calls have variable length and form so we decode * each byte rather than searching for ff and guessing length */ app_pc pc, next_pc; instr_t instr; instr_init(dcontext, &instr); for (pc = retaddr - MAX_CALL_CONSIDER; pc < retaddr; pc++) { LOG(THREAD, LOG_INTERP | LOG_VMAREAS, 3, "native_exec: decoding @" PFX " looking for call\n", pc); instr_reset(dcontext, &instr); next_pc = IF_AARCH64_ELSE(decode_cti_with_ldstex, decode_cti)(dcontext, pc, &instr); STATS_INC(num_native_entrance_TOS_decodes); if (next_pc == retaddr && instr_is_call(&instr)) { native_exec_bb = true; *is_call = true; LOG(THREAD, LOG_INTERP | LOG_VMAREAS, 2, "native_exec: found call @ pre-*TOS " PFX "\n", pc); break; } } instr_free(dcontext, &instr); } #ifdef RETURN_AFTER_CALL } #endif DOSTATS({ if (native_exec_bb) { if (LINKSTUB_FAKE(dcontext->last_exit)) STATS_INC(num_native_module_entrances_TOS_unknown); else STATS_INC(num_native_module_entrances_TOS_jmp); } }); } } /* i#2381: Only now can we check things that might preempt the * "guess" code above. */ /* Is this a return from a non-native module into a native module? */ if (!native_exec_bb && DYNAMO_OPTION(native_exec_retakeover) && LINKSTUB_INDIRECT(dcontext->last_exit->flags) && TEST(LINK_RETURN, dcontext->last_exit->flags)) { if (is_native_pc(start)) { /* XXX: check that this is the return address of a known native * callsite where we took over on a module transition. */ STATS_INC(num_native_module_entrances_ret); native_exec_bb = true; *is_call = false; } } #ifdef UNIX /* Is this the entry point of a native ELF executable? The entry point * (usually _start) cannot return as there is no retaddr. */ else if (!native_exec_bb && DYNAMO_OPTION(native_exec_retakeover) && LINKSTUB_INDIRECT(dcontext->last_exit->flags) && start == get_image_entry()) { if (is_native_pc(start)) { native_exec_bb = true; *is_call = false; } } #endif DOSTATS({ /* did we reach a native dll w/o going through an ind call caught above? */ if (!xfer_target /* else we'll re-check at the target itself */ && !native_exec_bb && is_native_pc(start)) { LOG(THREAD, LOG_INTERP | LOG_VMAREAS, 2, "WARNING: pc " PFX " is on native list but reached bypassing " "gateway!\n", start); STATS_INC(num_native_entrance_miss); /* do-once since once get into dll past gateway may xfer * through a bunch of lastexit-null or indjmp to same dll */ ASSERT_CURIOSITY_ONCE(false && "inside native_exec dll"); } }); } return native_exec_bb; } /* Use when calling build_bb_ilist with for_cache = true. * Must hold bb_building_lock. */ static inline void init_interp_build_bb(dcontext_t *dcontext, build_bb_t *bb, app_pc start, uint initial_flags, bool for_trace, instrlist_t **unmangled_ilist) { ASSERT_OWN_MUTEX(USE_BB_BUILDING_LOCK() && !TEST(FRAG_TEMP_PRIVATE, initial_flags), &bb_building_lock); /* We need to set up for abort prior to native exec and other checks * that can crash */ ASSERT(dcontext->bb_build_info == NULL); /* This won't make us be nested b/c for bb.for_cache caller is supposed * to set this up */ dcontext->bb_build_info = (void *)bb; init_build_bb( bb, start, true /*real interp*/, true /*for cache*/, true /*mangle*/, false /* translation: set below for clients */, INVALID_FILE, initial_flags | (INTERNAL_OPTION(store_translations) ? FRAG_HAS_TRANSLATION_INFO : 0), NULL /*no overlap*/); if (!TEST(FRAG_TEMP_PRIVATE, initial_flags)) bb->has_bb_building_lock = true; /* We avoid races where there is no hook when we start building a * bb (and hence we don't record translation or do full decode) yet * a hook when we're ready to call one by storing whether there is a * hook at translation/decode decision time: now. */ if (dr_bb_hook_exists()) { /* i#805: Don't instrument code on the null instru list. * Because the module load event is now on 1st exec, we need to trigger * it now so the client can adjust the null instru list: */ check_new_page_start(dcontext, bb); bb->checked_start_vmarea = true; if (!os_module_get_flag(bb->start_pc, MODULE_NULL_INSTRUMENT)) bb->pass_to_client = true; } /* PR 299808: even if no bb hook, for a trace hook we need to * record translation and do full decode. It's racy to check * dr_trace_hook_exists() here so we rely on trace building having * set unmangled_ilist. */ if (bb->pass_to_client || unmangled_ilist != NULL) { /* case 10009/214444: For client interface builds, store the translation. * by default. This ensures clients can get the correct app address * of any instruction. We also rely on this for allowing the client * to return DR_EMIT_STORE_TRANSLATIONS and setting the * FRAG_HAS_TRANSLATION_INFO flag after decoding the app code. * * FIXME: xref case 10070/214505. Currently this means that all * instructions are fully decoded for client interface builds. */ bb->record_translation = true; /* PR 200409: If a bb hook exists, we always do a full decode. * Note that we currently do this anyway to get * translation fields, but once we fix case 10070 it * won't be that way. * We do not let the client turn this off (the runtime * option is not dynamic, and off by default anyway), as we * do not export level-handling instr_t routines like *_expand * for walking instrlists and instr_decode(). */ bb->full_decode = !INTERNAL_OPTION(fast_client_decode); /* PR 299808: we give client chance to re-add instrumentation */ bb->for_trace = for_trace; } /* we need to clone the ilist pre-mangling */ bb->unmangled_ilist = unmangled_ilist; } static inline void exit_interp_build_bb(dcontext_t *dcontext, build_bb_t *bb) { ASSERT(dcontext->bb_build_info == (void *)bb); /* Caller's responsibility to clean up since bb.for_cache */ dcontext->bb_build_info = NULL; /* free the instrlist_t elements */ instrlist_clear_and_destroy(dcontext, bb->ilist); } /* Interprets the application's instructions until the end of a basic * block is found, and then creates a fragment for the basic block. * DOES NOT look in the hashtable to see if such a fragment already exists! */ fragment_t * build_basic_block_fragment(dcontext_t *dcontext, app_pc start, uint initial_flags, bool link, bool visible, bool for_trace, instrlist_t **unmangled_ilist) { fragment_t *f; build_bb_t bb; dr_where_am_i_t wherewasi = dcontext->whereami; bool image_entry; KSTART(bb_building); dcontext->whereami = DR_WHERE_INTERP; /* Neither thin_client nor hotp_only should be building any bbs. */ ASSERT(!RUNNING_WITHOUT_CODE_CACHE()); /* ASSUMPTION: image entry is reached via indirect transfer and * so will be the start of a bb */ image_entry = check_for_image_entry(start); init_interp_build_bb(dcontext, &bb, start, initial_flags, for_trace, unmangled_ilist); if (at_native_exec_gateway(dcontext, start, &bb.native_call _IF_DEBUG(false /*not xfer tgt*/))) { DODEBUG({ report_native_module(dcontext, bb.start_pc); }); /* PR 232617 - build_native_exec_bb doesn't support setting translation * info, but it also doesn't pass the built bb to the client (it * contains no app code) so we don't need it. */ bb.record_translation = false; build_native_exec_bb(dcontext, &bb); } else { build_bb_ilist(dcontext, &bb); if (dcontext->bb_build_info == NULL) { /* going native */ f = NULL; goto build_basic_block_fragment_done; } if (bb.native_exec) { /* change bb to be a native_exec gateway */ bool is_call = bb.native_call; LOG(THREAD, LOG_INTERP, 2, "replacing built bb with native_exec bb\n"); instrlist_clear_and_destroy(dcontext, bb.ilist); vm_area_destroy_list(dcontext, bb.vmlist); dcontext->bb_build_info = NULL; init_interp_build_bb(dcontext, &bb, start, initial_flags, for_trace, unmangled_ilist); /* PR 232617 - build_native_exec_bb doesn't support setting * translation info, but it also doesn't pass the built bb to the * client (it contains no app code) so we don't need it. */ bb.record_translation = false; bb.native_call = is_call; build_native_exec_bb(dcontext, &bb); } } /* case 9652: we do not want to persist the image entry point, so we keep * it fine-grained */ if (image_entry) bb.flags &= ~FRAG_COARSE_GRAIN; if (DYNAMO_OPTION(opt_jit) && visible && is_jit_managed_area(bb.start_pc)) { ASSERT(bb.overlap_info == NULL || bb.overlap_info->contiguous); jitopt_add_dgc_bb(bb.start_pc, bb.end_pc, TEST(FRAG_IS_TRACE_HEAD, bb.flags)); } /* emit fragment into fcache */ KSTART(bb_emit); f = emit_fragment_ex(dcontext, start, bb.ilist, bb.flags, bb.vmlist, link, visible); KSTOP(bb_emit); #ifdef CUSTOM_TRACES_RET_REMOVAL f->num_calls = dcontext->num_calls; f->num_rets = dcontext->num_rets; #endif #ifdef DGC_DIAGNOSTICS if ((f->flags & FRAG_DYNGEN)) { LOG(THREAD, LOG_INTERP, 1, "new bb is DGC:\n"); DOLOG(1, LOG_INTERP, { disassemble_app_bb(dcontext, start, THREAD); }); DOLOG(3, LOG_INTERP, { disassemble_fragment(dcontext, f, false); }); } #endif DOLOG(2, LOG_INTERP, { disassemble_fragment(dcontext, f, d_r_stats->loglevel <= 3); }); DOLOG(4, LOG_INTERP, { if (TEST(FRAG_SELFMOD_SANDBOXED, f->flags)) { LOG(THREAD, LOG_INTERP, 4, "\nXXXX sandboxed fragment! original code:\n"); disassemble_app_bb(dcontext, f->tag, THREAD); LOG(THREAD, LOG_INTERP, 4, "code cache code:\n"); disassemble_fragment(dcontext, f, false); } }); if (INTERNAL_OPTION(bbdump_tags)) { disassemble_fragment_header(dcontext, f, bbdump_file); } #ifdef INTERNAL DODEBUG({ if (INTERNAL_OPTION(stress_recreate_pc)) { /* verify recreation */ stress_test_recreate(dcontext, f, bb.ilist); } }); #endif exit_interp_build_bb(dcontext, &bb); build_basic_block_fragment_done: dcontext->whereami = wherewasi; KSTOP(bb_building); return f; } /* Builds an instrlist_t as though building a bb from pretend_pc, but decodes * from pc. * Use recreate_fragment_ilist() for building an instrlist_t for a fragment. * If check_vm_area is false, Does NOT call check_thread_vm_area()! * Make sure you know it will terminate at the right spot. It does * check selfmod and native_exec for elision, but otherwise will * follow ubrs to the limit. Currently used for * record_translation_info() (case 3559). * If vmlist!=NULL and check_vm_area, returns the vmlist, which the * caller must free by calling vm_area_destroy_list. */ instrlist_t * recreate_bb_ilist(dcontext_t *dcontext, byte *pc, byte *pretend_pc, app_pc stop_pc, uint flags, uint *res_flags OUT, uint *res_exit_type OUT, bool check_vm_area, bool mangle, void **vmlist_out OUT, bool call_client, bool for_trace) { build_bb_t bb; /* don't know full range -- just do simple check now */ if (!is_readable_without_exception(pc, 4)) { LOG(THREAD, LOG_INTERP, 3, "recreate_bb_ilist: cannot read memory at " PFX "\n", pc); return NULL; } LOG(THREAD, LOG_INTERP, 3, "\nbuilding bb instrlist now *********************\n"); init_build_bb(&bb, pc, false /*not interp*/, false /*not for cache*/, mangle, true /*translation*/, INVALID_FILE, flags, NULL /*no overlap*/); /* We support a stop pc to ensure selfmod matches how it was originally built, * w/o having to include the next instr which might have triggered the bb * termination but not been included in the bb (i#1441). * It only applies to full_decode. */ bb.stop_pc = stop_pc; bb.check_vm_area = check_vm_area; if (check_vm_area && vmlist_out != NULL) bb.record_vmlist = true; if (check_vm_area && !bb.record_vmlist) bb.record_vmlist = true; /* for xl8 region checks */ /* PR 214962: we call bb hook again, unless the client told us * DR_EMIT_STORE_TRANSLATIONS, in which case we shouldn't come here, * except for traces (see below): */ bb.pass_to_client = (DYNAMO_OPTION(code_api) && call_client && /* i#843: This flag cannot be changed dynamically, so * its current value should match the value used at * ilist building time. Alternatively, we could store * bb->pass_to_client in the fragment. */ !os_module_get_flag(pc, MODULE_NULL_INSTRUMENT)); /* PR 299808: we call bb hook again when translating a trace that * didn't have DR_EMIT_STORE_TRANSLATIONS on itself (or on any * for_trace bb if there was no trace hook). */ bb.for_trace = for_trace; /* instrument_basic_block, called by build_bb_ilist, verifies that all * non-meta instrs have translation fields */ if (pretend_pc != pc) bb.pretend_pc = pretend_pc; build_bb_ilist(dcontext, &bb); LOG(THREAD, LOG_INTERP, 3, "\ndone building bb instrlist *********************\n\n"); if (res_flags != NULL) *res_flags = bb.flags; if (res_exit_type != NULL) *res_exit_type = bb.exit_type; if (check_vm_area && vmlist_out != NULL) *vmlist_out = bb.vmlist; else if (bb.record_vmlist) vm_area_destroy_list(dcontext, bb.vmlist); return bb.ilist; } /* Re-creates an ilist of the fragment that currently contains the * passed-in code cache pc, also returns the fragment. * * Exactly one of pc and (f_res or *f_res) must be NULL: * If pc==NULL, assumes that *f_res is the fragment to use; * else, looks up the fragment, allocating it if necessary. * If f_res!=NULL, the fragment is returned and whether it was allocated * is returned in the alloc_res param. * If f_res==NULL, if the fragment was allocated it is freed here. * * NOTE : does not add prefix instructions to the created ilist, if we change * this to add them be sure to check recreate_app_* for compatibility (for ex. * adding them and setting their translation to pc would break current * implementation, also setting translation to NULL would trigger an assert) * * Returns NULL if unable to recreate the fragment ilist (fragment not found * or fragment is pending deletion and app memory might have changed). * In that case f_res is still pointed at the fragment if it was found, and * alloc is valid. * * For proper synchronization : * If caller is the dcontext's owner then needs to be couldbelinking, otherwise * the dcontext's owner should be suspended and the callers should own the * thread_initexit_lock */ instrlist_t * recreate_fragment_ilist(dcontext_t *dcontext, byte *pc, /*IN/OUT*/ fragment_t **f_res, /*OUT*/ bool *alloc_res, bool mangle, bool call_client) { fragment_t *f; uint flags = 0; instrlist_t *ilist; bool alloc = false, ok; monitor_data_t md = { 0, }; dr_isa_mode_t old_mode = DEFAULT_ISA_MODE; /* check synchronization, we need to make sure no one flushes the * fragment we just looked up while we are recreating it, if it's the * caller's dcontext then just need to be couldbelinking, otherwise need * the thread_initexit_lock since then we are looking up in someone else's * table (the dcontext's owning thread would also need to be suspended) */ ASSERT((dcontext != GLOBAL_DCONTEXT && d_r_get_thread_id() == dcontext->owning_thread && is_couldbelinking(dcontext)) || (ASSERT_OWN_MUTEX(true, &thread_initexit_lock), true)); STATS_INC(num_recreated_fragments); if (pc == NULL) { ASSERT(f_res != NULL && *f_res != NULL); f = *f_res; } else { /* Ensure callers don't give us both valid f and valid pc */ ASSERT(f_res == NULL || *f_res == NULL); LOG(THREAD, LOG_INTERP, 3, "recreate_fragment_ilist: looking up pc " PFX "\n", pc); f = fragment_pclookup_with_linkstubs(dcontext, pc, &alloc); LOG(THREAD, LOG_INTERP, 3, "\tfound F%d\n", f == NULL ? -1 : f->id); if (f_res != NULL) *f_res = f; /* ref case 3559, others, we won't be able to reliably recreate if * target is pending flush, original memory might no longer be there or * the memory might have changed. caller should use the stored * translation info instead. */ if (f == NULL || TEST(FRAG_WAS_DELETED, f->flags)) { ASSERT(f != NULL || !alloc); /* alloc shouldn't be set if no f */ ilist = NULL; goto recreate_fragment_done; } } /* Recreate in same mode as original fragment */ ok = dr_set_isa_mode(dcontext, FRAG_ISA_MODE(f->flags), &old_mode); ASSERT(ok); if ((f->flags & FRAG_IS_TRACE) == 0) { /* easy case: just a bb */ ilist = recreate_bb_ilist(dcontext, (byte *)f->tag, (byte *)f->tag, NULL /*default stop*/, 0 /*no pre flags*/, &flags, NULL, true /*check vm area*/, mangle, NULL, call_client, false /*not for_trace*/); ASSERT(ilist != NULL); if (ilist == NULL) /* a race */ goto recreate_fragment_done; if (PAD_FRAGMENT_JMPS(f->flags)) nop_pad_ilist(dcontext, f, ilist, false /* set translation */); goto recreate_fragment_done; } else { /* build trace up one bb at a time */ instrlist_t *bb; byte *apc; trace_only_t *t = TRACE_FIELDS(f); uint i; instr_t *last; bool mangle_at_end = mangle_trace_at_end(); if (mangle_at_end) { /* we need an md for mangle_trace */ md.trace_tag = f->tag; /* be sure we ask for translation fields */ md.trace_flags = f->flags | FRAG_HAS_TRANSLATION_INFO; md.num_blks = t->num_bbs; md.blk_info = (trace_bb_build_t *)HEAP_ARRAY_ALLOC( dcontext, trace_bb_build_t, md.num_blks, ACCT_TRACE, true); md.pass_to_client = true; } ilist = instrlist_create(dcontext); STATS_INC(num_recreated_traces); ASSERT(t->bbs != NULL); for (i = 0; i < t->num_bbs; i++) { void *vmlist = NULL; apc = (byte *)t->bbs[i].tag; bb = recreate_bb_ilist( dcontext, apc, apc, NULL /*default stop*/, 0 /*no pre flags*/, &flags, &md.final_exit_flags, true /*check vm area*/, !mangle_at_end, (mangle_at_end ? &vmlist : NULL), call_client, true /*for_trace*/); ASSERT(bb != NULL); if (bb == NULL) { instrlist_clear_and_destroy(dcontext, ilist); vm_area_destroy_list(dcontext, vmlist); ilist = NULL; goto recreate_fragment_done; } if (mangle_at_end) md.blk_info[i].info = t->bbs[i]; last = instrlist_last(bb); ASSERT(last != NULL); if (mangle_at_end) { md.blk_info[i].vmlist = vmlist; md.blk_info[i].final_cti = instr_is_cti(instrlist_last(bb)); } /* PR 299808: we need to duplicate what we did when we built the trace. * While if there's no client trace hook we could mangle and fixup as we * go, for simplicity we mangle at the end either way (in either case our * code here is not exactly what we did when we made it anyway) * PR 333597: we can't use mangle_trace if we have elision on. */ if (mangle && !mangle_at_end) { /* To duplicate the trace-building logic: * - call fixup_last_cti() * - retarget the ibl routine just like extend_trace() does */ app_pc target = (last != NULL) ? opnd_get_pc(instr_get_target(last)) : NULL; /* FIXME: is it always safe */ /* convert a basic block IBL, and retarget it to IBL_TRACE* */ if (target != NULL && is_indirect_branch_lookup_routine(dcontext, target)) { target = get_alternate_ibl_routine(dcontext, target, f->flags); ASSERT(target != NULL); LOG(THREAD, LOG_MONITOR, 3, "recreate_fragment_ilist: replacing ibl_routine to target=" PFX "\n", target); instr_set_target(last, opnd_create_pc(target)); instr_set_our_mangling(last, true); /* undone by target set */ } if (DYNAMO_OPTION(pad_jmps) && !INTERNAL_OPTION(pad_jmps_shift_bb)) { /* FIXME - hack, but pad_jmps_shift_bb will be on by * default. Synchronize changes here with recreate_fragment_ilist. * This hack is protected by asserts in nop_pad_ilist() (that * we never add nops to a bb if -pad_jmps_shift_bb) and in * extend_trace_pad_bytes (that we only add bbs to traces). */ /* FIXME - on linux the signal fence exit can trigger the * protective assert in nop_pad_ilist() */ remove_nops_from_ilist(dcontext, bb _IF_DEBUG(true)); } if (instrlist_last(ilist) != NULL) { fixup_last_cti(dcontext, ilist, (app_pc)apc, flags, f->flags, NULL, NULL, true /* record translation */, NULL, NULL, NULL); } } instrlist_append(ilist, instrlist_first(bb)); instrlist_init(bb); /* to clear fields to make destroy happy */ instrlist_destroy(dcontext, bb); } /* XXX i#5062 In the future this call should be placed inside mangle_trace() */ IF_AARCH64(fixup_indirect_trace_exit(dcontext, ilist)); /* PR 214962: re-apply client changes, this time storing translation * info for modified instrs */ if (call_client) /* else it's decode_trace() who is not really recreating */ instrument_trace(dcontext, f->tag, ilist, true); /* instrument_trace checks that all non-meta instrs have translation fields */ if (mangle) { if (mangle_at_end) { if (!mangle_trace(dcontext, ilist, &md)) { instrlist_clear_and_destroy(dcontext, ilist); ilist = NULL; goto recreate_fragment_done; } } /* else we mangled one bb at a time up above */ #ifdef INTERNAL /* we only optimize traces */ if (dynamo_options.optimize) { /* re-apply all optimizations to ilist * assumption: all optimizations are deterministic and stateless, * so we can exactly replicate their results */ LOG(THREAD_GET, LOG_INTERP, 2, "\tre-applying optimizations to F%d\n", f->id); # ifdef SIDELINE if (dynamo_options.sideline) { if (!TEST(FRAG_DO_NOT_SIDELINE, f->flags)) optimize_trace(dcontext, f->tag, ilist); /* else, never optimized */ } else # endif optimize_trace(dcontext, f->tag, ilist); } #endif /* FIXME: case 4718 append_trace_speculate_last_ibl(true) * should be called as well */ if (PAD_FRAGMENT_JMPS(f->flags)) nop_pad_ilist(dcontext, f, ilist, false /* set translation */); } } recreate_fragment_done: if (md.blk_info != NULL) { uint i; for (i = 0; i < md.num_blks; i++) { vm_area_destroy_list(dcontext, md.blk_info[i].vmlist); md.blk_info[i].vmlist = NULL; } HEAP_ARRAY_FREE(dcontext, md.blk_info, trace_bb_build_t, md.num_blks, ACCT_TRACE, true); } if (alloc_res != NULL) *alloc_res = alloc; if (f_res == NULL && alloc) fragment_free(dcontext, f); ok = dr_set_isa_mode(dcontext, old_mode, NULL); ASSERT(ok); return ilist; } /*** TRACE BUILDING ROUTINES *****************************************************/ static void process_nops_for_trace(dcontext_t *dcontext, instrlist_t *ilist, uint flags _IF_DEBUG(bool recreating)) { if (PAD_FRAGMENT_JMPS(flags) && !INTERNAL_OPTION(pad_jmps_shift_bb)) { /* FIXME - hack, but pad_jmps_shift_bb will be on by * default. Synchronize changes here with recreate_fragment_ilist. * This hack is protected by asserts in nop_pad_ilist() (that * we never add nops to a bb if -pad_jmps_shift_bb) and in * extend_trace_pad_bytes (that we only add bbs to traces). */ /* FIXME - on linux the signal fence exit can trigger the * protective assert in nop_pad_ilist() */ remove_nops_from_ilist(dcontext, ilist _IF_DEBUG(recreating)); } } /* Combines instrlist_preinsert to ilist and the size calculation of the addition */ static inline int tracelist_add(dcontext_t *dcontext, instrlist_t *ilist, instr_t *where, instr_t *inst) { /* when we emit the trace we're going to call instr_length() on all instrs * anyway, and we'll re-use any memory allocated here for an encoding */ int size; #if defined(X86) && defined(X64) if (!X64_CACHE_MODE_DC(dcontext)) { instr_set_x86_mode(inst, true /*x86*/); instr_shrink_to_32_bits(inst); } #endif size = instr_length(dcontext, inst); instrlist_preinsert(ilist, where, inst); return size; } /* FIXME i#1668, i#2974: NYI on ARM/AArch64 */ #ifdef X86 /* Combines instrlist_postinsert to ilist and the size calculation of the addition */ static inline int tracelist_add_after(dcontext_t *dcontext, instrlist_t *ilist, instr_t *where, instr_t *inst) { /* when we emit the trace we're going to call instr_length() on all instrs * anyway, and we'll re-use any memory allocated here for an encoding */ int size; # ifdef X64 if (!X64_CACHE_MODE_DC(dcontext)) { instr_set_x86_mode(inst, true /*x86*/); instr_shrink_to_32_bits(inst); } # endif size = instr_length(dcontext, inst); instrlist_postinsert(ilist, where, inst); return size; } #endif /* X86 */ #ifdef HASHTABLE_STATISTICS /* increments a given counter - assuming XCX/R2 is dead */ int insert_increment_stat_counter(dcontext_t *dcontext, instrlist_t *trace, instr_t *next, uint *counter_address) { int added_size = 0; /* incrementing a branch-type specific thread private counter */ opnd_t private_branchtype_counter = OPND_CREATE_ABSMEM(counter_address, OPSZ_4); /* using LEA to avoid clobbering eflags in a simple load-increment-store */ /*>>> movl counter, %ecx */ /*>>> lea 1(%ecx), %ecx */ /*>>> movl %ecx, counter */ /* x64: the counter is still 32 bits */ added_size += tracelist_add(dcontext, trace, next, XINST_CREATE_load(dcontext, opnd_create_reg(SCRATCH_REG2), private_branchtype_counter)); added_size += tracelist_add( dcontext, trace, next, XINST_CREATE_add(dcontext, opnd_create_reg(SCRATCH_REG2), OPND_CREATE_INT8(1))); added_size += tracelist_add(dcontext, trace, next, XINST_CREATE_store(dcontext, private_branchtype_counter, opnd_create_reg(SCRATCH_REG2))); return added_size; } #endif /* HASHTABLE_STATISTICS */ /* inserts proper instruction(s) to restore XCX spilled on indirect branch mangling * assumes target instrlist is a trace! * returns size to be added to trace */ static inline int insert_restore_spilled_xcx(dcontext_t *dcontext, instrlist_t *trace, instr_t *next) { int added_size = 0; if (DYNAMO_OPTION(private_ib_in_tls)) { #ifdef X86 if (X64_CACHE_MODE_DC(dcontext) && !X64_MODE_DC(dcontext) && IF_X64_ELSE(DYNAMO_OPTION(x86_to_x64_ibl_opt), false)) { added_size += tracelist_add(dcontext, trace, next, INSTR_CREATE_mov_ld(dcontext, opnd_create_reg(REG_XCX), opnd_create_reg(REG_R9))); } else #endif { added_size += tracelist_add( dcontext, trace, next, XINST_CREATE_load( dcontext, opnd_create_reg(SCRATCH_REG2), opnd_create_tls_slot(os_tls_offset(MANGLE_XCX_SPILL_SLOT)))); } } else { /* We need to restore XCX from TLS for shared fragments, but from * mcontext for private fragments, and all traces are private */ added_size += tracelist_add(dcontext, trace, next, instr_create_restore_from_dcontext( dcontext, SCRATCH_REG2, SCRATCH_REG2_OFFS)); } return added_size; } bool instr_is_trace_cmp(dcontext_t *dcontext, instr_t *inst) { if (!instr_is_our_mangling(inst)) return false; #ifdef X86 return # ifdef X64 instr_get_opcode(inst) == OP_mov_imm || /* mov %rax -> xbx-tls-spill-slot */ instr_get_opcode(inst) == OP_mov_st || instr_get_opcode(inst) == OP_lahf || instr_get_opcode(inst) == OP_seto || instr_get_opcode(inst) == OP_cmp || instr_get_opcode(inst) == OP_jnz || instr_get_opcode(inst) == OP_add || instr_get_opcode(inst) == OP_sahf # else instr_get_opcode(inst) == OP_lea || instr_get_opcode(inst) == OP_jecxz || instr_get_opcode(inst) == OP_jmp # endif ; #elif defined(AARCH64) return instr_get_opcode(inst) == OP_movz || instr_get_opcode(inst) == OP_movk || instr_get_opcode(inst) == OP_eor || instr_get_opcode(inst) == OP_cbnz; #elif defined(ARM) /* FIXME i#1668: NYI on ARM */ ASSERT_NOT_IMPLEMENTED(DYNAMO_OPTION(disable_traces)); return false; #endif } /* 32-bit only: inserts a comparison to speculative_tag with no side effect and * if value is matched continue target is assumed to be immediately * after targeter (which must be < 127 bytes away). * returns size to be added to trace */ static int insert_transparent_comparison(dcontext_t *dcontext, instrlist_t *trace, instr_t *targeter, /* exit CTI */ app_pc speculative_tag) { int added_size = 0; #ifdef X86 instr_t *jecxz; instr_t *continue_label = INSTR_CREATE_label(dcontext); /* instead of: * cmp ecx,const * we use: * lea -const(ecx) -> ecx * jecxz continue * lea const(ecx) -> ecx * jmp exit # usual targeter for stay on trace comparison * continue: # if match, we target post-targeter * * we have to use the landing pad b/c we don't know whether the * stub will be <128 away */ /* lea requires OPSZ_lea operand */ added_size += tracelist_add( dcontext, trace, targeter, INSTR_CREATE_lea(dcontext, opnd_create_reg(REG_ECX), opnd_create_base_disp(REG_ECX, REG_NULL, 0, -((int)(ptr_int_t)speculative_tag), OPSZ_lea))); jecxz = INSTR_CREATE_jecxz(dcontext, opnd_create_instr(continue_label)); /* do not treat jecxz as exit cti! */ instr_set_meta(jecxz); added_size += tracelist_add(dcontext, trace, targeter, jecxz); /* need to recover address in ecx */ IF_X64(ASSERT_NOT_IMPLEMENTED(!X64_MODE_DC(dcontext))); added_size += tracelist_add(dcontext, trace, targeter, INSTR_CREATE_lea(dcontext, opnd_create_reg(REG_ECX), opnd_create_base_disp( REG_ECX, REG_NULL, 0, ((int)(ptr_int_t)speculative_tag), OPSZ_lea))); added_size += tracelist_add_after(dcontext, trace, targeter, continue_label); #elif defined(ARM) /* FIXME i#1551: NYI on ARM */ ASSERT_NOT_IMPLEMENTED(false); #endif return added_size; } #if defined(X86) && defined(X64) static int mangle_x64_ib_in_trace(dcontext_t *dcontext, instrlist_t *trace, instr_t *targeter, app_pc next_tag) { int added_size = 0; if (X64_MODE_DC(dcontext) || !DYNAMO_OPTION(x86_to_x64_ibl_opt)) { added_size += tracelist_add( dcontext, trace, targeter, INSTR_CREATE_mov_st( dcontext, opnd_create_tls_slot(os_tls_offset(PREFIX_XAX_SPILL_SLOT)), opnd_create_reg(REG_XAX))); added_size += tracelist_add(dcontext, trace, targeter, INSTR_CREATE_mov_imm(dcontext, opnd_create_reg(REG_XAX), OPND_CREATE_INTPTR((ptr_int_t)next_tag))); } else { ASSERT(X64_CACHE_MODE_DC(dcontext)); added_size += tracelist_add(dcontext, trace, targeter, INSTR_CREATE_mov_ld(dcontext, opnd_create_reg(REG_R8), opnd_create_reg(REG_XAX))); added_size += tracelist_add(dcontext, trace, targeter, INSTR_CREATE_mov_imm(dcontext, opnd_create_reg(REG_R10), OPND_CREATE_INTPTR((ptr_int_t)next_tag))); } /* saving in the trace and restoring in ibl means that * -unsafe_ignore_eflags_{trace,ibl} must be equivalent */ if (!INTERNAL_OPTION(unsafe_ignore_eflags_trace)) { if (X64_MODE_DC(dcontext) || !DYNAMO_OPTION(x86_to_x64_ibl_opt)) { added_size += tracelist_add( dcontext, trace, targeter, INSTR_CREATE_mov_st( dcontext, opnd_create_tls_slot(os_tls_offset(INDIRECT_STUB_SPILL_SLOT)), opnd_create_reg(REG_XAX))); } /* FIXME: share w/ insert_save_eflags() */ added_size += tracelist_add(dcontext, trace, targeter, INSTR_CREATE_lahf(dcontext)); if (!INTERNAL_OPTION(unsafe_ignore_overflow)) { /* OF needs saving */ /* Move OF flags into the OF flag spill slot. */ added_size += tracelist_add( dcontext, trace, targeter, INSTR_CREATE_setcc(dcontext, OP_seto, opnd_create_reg(REG_AL))); } if (X64_MODE_DC(dcontext) || !DYNAMO_OPTION(x86_to_x64_ibl_opt)) { added_size += tracelist_add( dcontext, trace, targeter, INSTR_CREATE_cmp( dcontext, opnd_create_reg(REG_XCX), opnd_create_tls_slot(os_tls_offset(INDIRECT_STUB_SPILL_SLOT)))); } else { added_size += tracelist_add(dcontext, trace, targeter, INSTR_CREATE_cmp(dcontext, opnd_create_reg(REG_XCX), opnd_create_reg(REG_R10))); } } else { added_size += tracelist_add( dcontext, trace, targeter, INSTR_CREATE_cmp(dcontext, opnd_create_reg(REG_XCX), (X64_MODE_DC(dcontext) || !DYNAMO_OPTION(x86_to_x64_ibl_opt)) ? opnd_create_reg(REG_XAX) : opnd_create_reg(REG_R10))); } /* change jmp into jne to trace cmp entry of ibl routine (special entry * that is after the eflags save) */ instr_set_opcode(targeter, OP_jnz); added_size++; /* jcc is 6 bytes, jmp is 5 bytes */ ASSERT(opnd_is_pc(instr_get_target(targeter))); instr_set_target(targeter, opnd_create_pc(get_trace_cmp_entry( dcontext, opnd_get_pc(instr_get_target(targeter))))); /* since the target gets lost we need to OR in this flag */ instr_exit_branch_set_type(targeter, instr_exit_branch_type(targeter) | INSTR_TRACE_CMP_EXIT); return added_size; } #endif #ifdef AARCH64 /* Prior to indirect branch trace mangling, we check previous byte blocks * before each indirect branch if they were mangled properly. * An indirect branch: * br jump_target_reg * is mangled into (see mangle_indirect_jump in mangle.c): * str IBL_TARGET_REG, TLS_REG2_SLOT * mov IBL_TARGET_REG, jump_target_reg * b ibl_routine or indirect_stub * This function is used by mangle_indirect_branch_in_trace; * it removes the two mangled instructions and returns the jump_target_reg id. * * This function is an optimisation in that we can avoid the spill of * IBL_TARGET_REG as we know that the actual target is always in a register * (or the stolen register slot, see below) on AArch64 and we can compare this * value in the register directly with the actual target. * And we delay the loading of the target into IBL_TARGET_REG * (done in fixup_indirect_trace_exit) until we are on the miss path. * * However, there is a special case where there isn't a str/mov being patched * rather there is an str/ldr which could happen when the jump target is stored * in the stolen register. For example: * * .... * blr stolen_reg -> %x30 * b ibl_routine * * is mangled into * * ... * str tgt_reg, TLS_REG2_SLOT * ldr tgt_reg, TLS_REG_STOLEN_SLOT * b ibl_routine * * This means that we should not remove the str/ldr, rather we need to compare the * trace_next_exit with tgt_reg directly and remember to restore the value of tgt_reg * in the case when the branch is not taken. * */ static reg_id_t check_patched_ibl(dcontext_t *dcontext, instrlist_t *trace, instr_t *targeter, int *added_size, bool *tgt_in_stolen_reg) { instr_t *prev = instr_get_prev(targeter); for (prev = instr_get_prev_expanded(dcontext, trace, targeter); prev; prev = instr_get_prev(prev)) { instr_t *prev_prev = instr_get_prev(prev); if (prev_prev == NULL) break; /* we expect * prev_prev str IBL_TARGET_REG, TLS_REG2_SLOT * prev mov IBL_TARGET_REG, jump_target_reg */ if (instr_get_opcode(prev_prev) == OP_str && instr_get_opcode(prev) == OP_orr && opnd_get_reg(instr_get_src(prev_prev, 0)) == IBL_TARGET_REG && opnd_get_base(instr_get_dst(prev_prev, 0)) == dr_reg_stolen && opnd_get_reg(instr_get_dst(prev, 0)) == IBL_TARGET_REG) { reg_id_t jp_tg_reg = opnd_get_reg(instr_get_src(prev, 1)); instrlist_remove(trace, prev_prev); instr_destroy(dcontext, prev_prev); instrlist_remove(trace, prev); instr_destroy(dcontext, prev); LOG(THREAD, LOG_INTERP, 4, "found and removed str/mov\n"); *added_size -= 2 * AARCH64_INSTR_SIZE; return jp_tg_reg; /* Here we expect * prev_prev str IBL_TARGET_REG, TLS_REG2_SLOT * prev ldr IBL_TARGET_REG, TLS_REG_STOLEN_SLOT */ } else if (instr_get_opcode(prev_prev) == OP_str && instr_get_opcode(prev) == OP_ldr && opnd_get_reg(instr_get_src(prev_prev, 0)) == IBL_TARGET_REG && opnd_get_base(instr_get_src(prev, 0)) == dr_reg_stolen && opnd_get_reg(instr_get_dst(prev, 0)) == IBL_TARGET_REG) { *tgt_in_stolen_reg = true; LOG(THREAD, LOG_INTERP, 4, "jump target is in stolen register slot\n"); return IBL_TARGET_REG; } } return DR_REG_NULL; } /* For AArch64 we have a special case if we cannot remove all code after * the direct branch, which is mangled by cbz/cbnz stolen register. * For example: * cbz x28, target * would be mangled (see mangle_cbr_stolen_reg() in aarchxx/mangle.c) into: * str x0, [x28] * ldr x0, [x28, #32] * cbnz x0, fall <- meta instr, not treated as exit cti * ldr x0, [x28] * b target <- delete after * fall: * ldr x0, [x28] * b fall_target * ... * If we delete all code after "b target", then the "fall" path would * be lost. Therefore we need to append the fall path at the end of * the trace as a fake exit stub. Swapping them might be dangerous since * a stub trace may be created on both paths. * * XXX i#5062 This special case is not needed when we elimiate decoding from code cache */ static bool instr_is_cbr_stolen(instr_t *instr) { if (!instr) return false; else { instr_get_opcode(instr); return instr->opcode == OP_cbz || instr->opcode == OP_cbnz || instr->opcode == OP_tbz || instr->opcode == OP_tbnz; } } static bool instr_is_load_tls(instr_t *instr) { if (!instr || !instr_raw_bits_valid(instr)) return false; else { return instr_get_opcode(instr) == OP_ldr && opnd_get_base(instr_get_src(instr, 0)) == dr_reg_stolen; } } static instr_t * fixup_cbr_on_stolen_reg(dcontext_t *dcontext, instrlist_t *trace, instr_t *targeter) { /* We check prior to the targeter whether there is a pattern such as * cbz/cbnz ... * ldr reg, [x28, #SLOT] * Otherwise, just return the previous instruction. */ instr_t *prev = instr_get_prev_expanded(dcontext, trace, targeter); if (!instr_is_load_tls(prev)) return prev; instr_t *prev_prev = instr_get_prev_expanded(dcontext, trace, prev); if (!instr_is_cbr_stolen(prev_prev)) return prev; /* Now we confirm that this cbr stolen_reg was properly mangled. */ instr_t *next = instr_get_next_expanded(dcontext, trace, targeter); if (!next) return prev; /* Next instruction must be a LDR TLS slot. */ ASSERT_CURIOSITY(instr_is_load_tls(next)); instr_t *next_next = instr_get_next_expanded(dcontext, trace, next); if (!next_next) return prev; /* Next next instruction must be direct branch. */ ASSERT_CURIOSITY(instr_is_ubr(next_next)); /* Set the cbz/cbnz target to "fall" path. */ instr_set_target(prev_prev, instr_get_target(next_next)); /* Then we can safely remove the "fall" path. */ return prev; } #endif /* Mangles an indirect branch in a trace where a basic block with tag "tag" * is being added as the next block beyond the indirect branch. * Returns the size of instructions added to trace. */ static int mangle_indirect_branch_in_trace(dcontext_t *dcontext, instrlist_t *trace, instr_t *targeter, app_pc next_tag, uint next_flags, instr_t **delete_after /*OUT*/, instr_t *end_instr) { int added_size = 0; instr_t *next = instr_get_next(targeter); /* all indirect branches should be ubrs */ ASSERT(instr_is_ubr(targeter)); /* expecting basic blocks only */ ASSERT((end_instr != NULL && targeter == end_instr) || targeter == instrlist_last(trace)); ASSERT(delete_after != NULL); *delete_after = (next == NULL || (end_instr != NULL && targeter == end_instr)) ? NULL : instr_get_prev(next); STATS_INC(trace_ib_cmp); #if defined(X86) /* Change jump to indirect_branch_lookup to a conditional jump * based on indirect target not equaling next block in trace * * the bb has already done: * spill xcx to xcx-tls-spill-slot * mov curtarget, xcx * <any other side effects of ind branch, like ret xsp adjust> * * and we now want to accomplish: * cmp ecx,const * * on 32-bit we use: * lea -const(ecx) -> ecx * jecxz continue * lea const(ecx) -> ecx * jmp exit # usual targeter for stay on trace comparison * continue: # if match, we target post-targeter * restore ecx * we have to use the landing pad b/c we don't know whether the * stub will be <128 away * * on 64-bit we use (PR 245832): * mov xax, xax-tls-spill-slot * mov $staytarget, xax * if !INTERNAL_OPTION(unsafe_ignore_eflags_{trace,ibl}) * mov xax, xbx-tls-spill-slot * lahf * seto al * cmp xcx, xbx-tls-spill-slot * else * cmp xcx, xax * jne exit * if xcx live: * mov xcx-tls-spill-slot, xcx * if flags live && unsafe options not on: * add 7f, al * sahf * if xax live: * mov xax-tls-spill-slot, xax */ # ifdef CUSTOM_TRACES_RET_REMOVAL IF_X64(ASSERT_NOT_IMPLEMENTED(false)); /* try to remove ret * FIXME: also handle ret imm => prev instr is add */ inst = instr_get_prev(targeter); if (dcontext->call_depth >= 0 && instr_raw_bits_valid(inst)) { byte *b = inst->bytes + inst->length - 1; /* 0x40538115 89 0d ec 68 06 40 mov %ecx -> 0x400668ec 0x4053811b 59 pop %esp (%esp) -> %ecx %esp 0x4053811c 83 c4 04 add $0x04 %esp -> %esp */ LOG(THREAD, LOG_MONITOR, 4, "ret removal: *b=0x%x, prev=" PFX ", dcontext=" PFX ", 0x%x\n", *b, *((int *)(b - 4)), dcontext, XCX_OFFSET); if ((*b == 0x59 && *((int *)(b - 4)) == ((uint)dcontext) + XCX_OFFSET) || (*(b - 3) == 0x59 && *((int *)(b - 7)) == ((uint)dcontext) + XCX_OFFSET && *(b - 2) == 0x83 && *(b - 1) == 0xc4)) { uint esp_add; /* already added calls & rets to call depth * if not negative, the call for this ret is earlier in this trace! */ LOG(THREAD, LOG_MONITOR, 4, "fixup_last_cti: removing ret!\n"); /* delete save ecx and pop */ if (*b == 0x59) { instr_set_raw_bits(inst, inst->bytes, inst->length - 7); esp_add = 4; } else { /* delete add too */ instr_set_raw_bits(inst, inst->bytes, inst->length - 10); esp_add = 4 + (uint)(*b); LOG(THREAD, LOG_MONITOR, 4, "*b=0x%x, esp_add=%d\n", *b, esp_add); } # ifdef DEBUG num_rets_removed++; # endif removed_ret = true; added_size += tracelist_add(dcontext, trace, targeter, INSTR_CREATE_lea(dcontext, opnd_create_reg(REG_ESP), opnd_create_base_disp(REG_ESP, REG_NULL, 0, esp_add, OPSZ_lea))); } } if (removed_ret) { *delete_after = instr_get_prev(targeter); return added_size; } # endif /* CUSTOM_TRACES_RET_REMOVAL */ # ifdef X64 if (X64_CACHE_MODE_DC(dcontext)) { added_size += mangle_x64_ib_in_trace(dcontext, trace, targeter, next_tag); } else { # endif if (!INTERNAL_OPTION(unsafe_ignore_eflags_trace)) { /* if equal follow to the next instruction after the exit CTI */ added_size += insert_transparent_comparison(dcontext, trace, targeter, next_tag); /* leave jmp as it is, a jmp to exit stub (thence to ind br * lookup) */ } else { /* assume eflags don't need to be saved across ind branches, * so go ahead and use cmp, jne */ /* FIXME: no way to cmp w/ 64-bit immed */ IF_X64(ASSERT_NOT_IMPLEMENTED(!X64_MODE_DC(dcontext))); added_size += tracelist_add( dcontext, trace, targeter, INSTR_CREATE_cmp(dcontext, opnd_create_reg(REG_ECX), OPND_CREATE_INT32((int)(ptr_int_t)next_tag))); /* Change jmp into jne indirect_branch_lookup */ /* CHECK: is that also going to exit stub */ instr_set_opcode(targeter, OP_jnz); added_size++; /* jcc is 6 bytes, jmp is 5 bytes */ } # ifdef X64 } # endif /* X64 */ /* PR 214962: our spill restoration needs this whole sequence marked mangle */ instr_set_our_mangling(targeter, true); LOG(THREAD, LOG_MONITOR, 3, "fixup_last_cti: added cmp vs. " PFX " for ind br\n", next_tag); # ifdef HASHTABLE_STATISTICS /* If we do stay on the trace, increment a counter using dead XCX */ if (INTERNAL_OPTION(stay_on_trace_stats)) { ibl_type_t ibl_type; /* FIXME: see if can test the instr flags instead */ DEBUG_DECLARE(bool ok =) get_ibl_routine_type(dcontext, opnd_get_pc(instr_get_target(targeter)), &ibl_type); ASSERT(ok); added_size += insert_increment_stat_counter( dcontext, trace, next, &get_ibl_per_type_statistics(dcontext, ibl_type.branch_type) ->ib_stay_on_trace_stat); } # endif /* HASHTABLE_STATISTICS */ /* If we do stay on the trace, must restore xcx * TODO optimization: check if xcx is live or not in next bb */ added_size += insert_restore_spilled_xcx(dcontext, trace, next); # ifdef X64 if (X64_CACHE_MODE_DC(dcontext)) { LOG(THREAD, LOG_INTERP, 4, "next_flags for post-ibl-cmp: 0x%x\n", next_flags); if (!TEST(FRAG_WRITES_EFLAGS_6, next_flags) && !INTERNAL_OPTION(unsafe_ignore_eflags_trace)) { if (!TEST(FRAG_WRITES_EFLAGS_OF, next_flags) && /* OF was saved */ !INTERNAL_OPTION(unsafe_ignore_overflow)) { /* restore OF using add that overflows if OF was on when we did seto */ added_size += tracelist_add(dcontext, trace, next, INSTR_CREATE_add(dcontext, opnd_create_reg(REG_AL), OPND_CREATE_INT8(0x7f))); } added_size += tracelist_add(dcontext, trace, next, INSTR_CREATE_sahf(dcontext)); } else STATS_INC(trace_ib_no_flag_restore); /* TODO optimization: check if xax is live or not in next bb */ if (X64_MODE_DC(dcontext) || !DYNAMO_OPTION(x86_to_x64_ibl_opt)) { added_size += tracelist_add( dcontext, trace, next, INSTR_CREATE_mov_ld( dcontext, opnd_create_reg(REG_XAX), opnd_create_tls_slot(os_tls_offset(PREFIX_XAX_SPILL_SLOT)))); } else { added_size += tracelist_add(dcontext, trace, next, INSTR_CREATE_mov_ld(dcontext, opnd_create_reg(REG_XAX), opnd_create_reg(REG_R8))); } } # endif #elif defined(AARCH64) instr_t *instr; reg_id_t jump_target_reg; reg_id_t scratch; bool tgt_in_stolen_reg; /* Mangle jump to indirect branch lookup routine, * based on indirect target not being equal to next block in trace. * Original ibl lookup: * str tgt_reg, TLS_REG2_SLOT * mov tgt_reg, jump_target * b ibl_routine * Now we rewrite it into: * str x0, TLS_REG0_SLOT * mov x0, #trace_next_target * eor x0, x0, jump_target * cbnz x0, trace_exit (ibl routine) * ldr x0, TLS_REG0_SLOT */ /* Check and remove previous two patched instructions if we have. */ tgt_in_stolen_reg = false; jump_target_reg = check_patched_ibl(dcontext, trace, targeter, &added_size, &tgt_in_stolen_reg); if (jump_target_reg == DR_REG_NULL) { ASSERT_MESSAGE(2, "Failed to get branch target register in creating trace", false); return added_size; } LOG(THREAD, LOG_MONITOR, 4, "fixup_last_cti: jump target reg is %s\n", reg_names[jump_target_reg]); /* Choose any scratch register except the target reg. */ scratch = (jump_target_reg == DR_REG_X0) ? DR_REG_X1 : DR_REG_X0; /* str scratch, TLS_REG0_SLOT */ added_size += tracelist_add(dcontext, trace, next, instr_create_save_to_tls(dcontext, scratch, TLS_REG0_SLOT)); /* mov scratch, #trace_next_target */ instr_t *first = NULL; instr_t *end = NULL; instrlist_insert_mov_immed_ptrsz(dcontext, (ptr_int_t)next_tag, opnd_create_reg(scratch), trace, next, &first, &end); /* Get the acutal number of mov imm instructions added. */ instr = first; while (instr != end) { added_size += AARCH64_INSTR_SIZE; instr = instr_get_next(instr); } added_size += AARCH64_INSTR_SIZE; /* eor scratch, scratch, jump_target */ added_size += tracelist_add(dcontext, trace, next, INSTR_CREATE_eor(dcontext, opnd_create_reg(scratch), opnd_create_reg(jump_target_reg))); /* cbnz scratch, trace_exit * branch to original ibl lookup routine */ instr = INSTR_CREATE_cbnz(dcontext, instr_get_target(targeter), opnd_create_reg(scratch)); /* Set the exit type from the targeter. */ instr_exit_branch_set_type(instr, instr_exit_branch_type(targeter)); added_size += tracelist_add(dcontext, trace, next, instr); /* If we do stay on the trace, restore x0 and x1. */ /* ldr scratch, TLS_REG0_SLOT */ ASSERT(TLS_REG0_SLOT != IBL_TARGET_SLOT); added_size += tracelist_add(dcontext, trace, next, instr_create_restore_from_tls(dcontext, scratch, TLS_REG0_SLOT)); if (tgt_in_stolen_reg) { /* we need to restore app's x2 in case the branch to trace_exit is not taken. * This is not needed in the str/mov case as we removed the instruction to * spill the value of IBL_TARGET_REG (str tgt_reg, TLS_REG2_SLOT) * * ldr x2 TLS_REG2_SLOT */ added_size += tracelist_add( dcontext, trace, next, instr_create_restore_from_tls(dcontext, IBL_TARGET_REG, IBL_TARGET_SLOT)); } /* Remove the branch. */ instrlist_remove(trace, targeter); instr_destroy(dcontext, targeter); added_size -= AARCH64_INSTR_SIZE; #elif defined(ARM) /* FIXME i#1551: NYI on ARM */ ASSERT_NOT_IMPLEMENTED(false); #endif /* X86/ARM */ return added_size; } /* This routine handles the mangling of the cti at the end of the * previous block when adding a new block (f) to the trace fragment. * If prev_l is not NULL, matches the ordinal of prev_l to the nth * exit cti in the trace instrlist_t. * * If prev_l is NULL: WARNING: this routine assumes that the previous * block can only have a single indirect branch -- otherwise there is * no way to determine which indirect exit targeted the new block! No * assumptions are made about direct exits -- we can walk through them * all to find the one that targeted the new block. * * Returns an upper bound on the size added to the trace with inserted * instructions. * If we change this to add a substantial # of instrs, should update * TRACE_CTI_MANGLE_SIZE_UPPER_BOUND (assert at bottom should notify us) * * If you want to re-add the ability to add the front end of a trace, * revive the now-removed CUSTOM_TRACES_ADD_TRACE define from the attic. */ static int fixup_last_cti(dcontext_t *dcontext, instrlist_t *trace, app_pc next_tag, uint next_flags, uint trace_flags, fragment_t *prev_f, linkstub_t *prev_l, bool record_translation, uint *num_exits_deleted /*OUT*/, /* If non-NULL, only looks inside trace between these two */ instr_t *start_instr, instr_t *end_instr) { app_pc target_tag; instr_t *inst, *targeter = NULL; /* at end of routine we will delete all instrs after this one: */ instr_t *delete_after = NULL; bool is_indirect = false; /* Added size for transformations done here. * Use tracelist_add to automate adding inserted instr sizes. */ int added_size = 0; uint exits_deleted = 0; /* count exit stubs to get the ordinal of the exit that targeted us * start at prev_l, and count up extraneous exits and blks until end */ uint nth_exit = 0, cur_exit; #ifdef CUSTOM_TRACES_RET_REMOVAL bool removed_ret = false; #endif bool have_ordinal = false; if (prev_l != NULL && prev_l == get_deleted_linkstub(dcontext)) { int last_ordinal = get_last_linkstub_ordinal(dcontext); if (last_ordinal != -1) { nth_exit = last_ordinal; have_ordinal = true; } } if (!have_ordinal && prev_l != NULL && !LINKSTUB_FAKE(prev_l)) { linkstub_t *stub = FRAGMENT_EXIT_STUBS(prev_f); while (stub != prev_l) stub = LINKSTUB_NEXT_EXIT(stub); /* if prev_l is cbr followed by ubr, we'll get 1 for ubr, * but we want 0, so we count prev_l itself, then decrement */ stub = LINKSTUB_NEXT_EXIT(stub); while (stub != NULL) { nth_exit++; stub = LINKSTUB_NEXT_EXIT(stub); } } /* else, we assume it's the final exit */ LOG(THREAD, LOG_MONITOR, 4, "fixup_last_cti: looking for %d-th exit cti from bottom\n", nth_exit); if (start_instr != NULL) { ASSERT(end_instr != NULL); } else { start_instr = instrlist_first(trace); end_instr = instrlist_last(trace); } start_instr = instr_get_prev(start_instr); /* get open-ended bound */ cur_exit = nth_exit; /* now match the ordinal to the instrs. * we don't have any way to find boundary with previous-previous block * to make sure we didn't go backwards too far -- does it matter? */ for (inst = end_instr; inst != NULL && inst != start_instr; inst = instr_get_prev(inst)) { if (instr_is_exit_cti(inst)) { if (cur_exit == 0) { ibl_type_t ibl_type; /* exit cti is guaranteed to have pc target */ target_tag = opnd_get_pc(instr_get_target(inst)); is_indirect = get_ibl_routine_type(dcontext, target_tag, &ibl_type); if (is_indirect) { /* this should be a trace exit stub therefore it cannot be IBL_BB* */ ASSERT(IS_IBL_TRACE(ibl_type.source_fragment_type)); targeter = inst; break; } else { if (prev_l != NULL) { /* direct jmp, better point to us */ ASSERT(target_tag == next_tag); targeter = inst; break; } else { /* need to search for targeting jmp */ DOLOG(4, LOG_MONITOR, { d_r_loginst(dcontext, 4, inst, "exit==targeter?"); }); LOG(THREAD, LOG_MONITOR, 4, "target_tag = " PFX ", next_tag = " PFX "\n", target_tag, next_tag); if (target_tag == next_tag) { targeter = inst; break; } } } } else if (prev_l != NULL) { LOG(THREAD, LOG_MONITOR, 4, "counting backwards: %d == target_tag = " PFX "\n", cur_exit, opnd_get_pc(instr_get_target(inst))); cur_exit--; } } /* is exit cti */ } ASSERT(targeter != NULL); if (record_translation) instrlist_set_translation_target(trace, instr_get_translation(targeter)); instrlist_set_our_mangling(trace, true); /* PR 267260 */ DOLOG(4, LOG_MONITOR, { d_r_loginst(dcontext, 4, targeter, "\ttargeter"); }); if (is_indirect) { added_size += mangle_indirect_branch_in_trace( dcontext, trace, targeter, next_tag, next_flags, &delete_after, end_instr); } else { /* direct jump or conditional branch */ instr_t *next = targeter->next; if (instr_is_cbr(targeter)) { LOG(THREAD, LOG_MONITOR, 4, "fixup_last_cti: inverted logic of cbr\n"); if (next != NULL && instr_is_ubr(next)) { /* cbr followed by ubr: if cbr got us here, reverse cbr and * remove ubr */ instr_invert_cbr(targeter); instr_set_target(targeter, instr_get_target(next)); ASSERT(next == end_instr); delete_after = targeter; LOG(THREAD, LOG_MONITOR, 4, "\tremoved ubr following cbr\n"); } else { ASSERT_NOT_REACHED(); } } else if (instr_is_ubr(targeter)) { /* remove unnecessary ubr at end of block */ #ifdef AARCH64 delete_after = fixup_cbr_on_stolen_reg(dcontext, trace, targeter); #else delete_after = instr_get_prev(targeter); #endif if (delete_after != NULL) { LOG(THREAD, LOG_MONITOR, 4, "fixup_last_cti: removed ubr\n"); } } else ASSERT_NOT_REACHED(); } /* remove all instrs after this cti -- but what if internal * control flow jumps ahead and then comes back? * too expensive to check for such all the time. * XXX: what to do? * * XXX: rather than adding entire trace on and then chopping off where * we exited, why not add after we know where to stop? */ if (delete_after != NULL) { ASSERT(delete_after != end_instr); delete_after = instr_get_next(delete_after); while (delete_after != NULL) { inst = delete_after; if (delete_after == end_instr) delete_after = NULL; else delete_after = instr_get_next(delete_after); if (instr_is_exit_cti(inst)) { /* assumption: passing in cache target to exit_stub_size works * just as well as linkstub_t target, since only cares whether * targeting ibl */ app_pc target = opnd_get_pc(instr_get_target(inst)); /* we already added all the stub size differences to the trace, * so we subtract the trace size of the stub here */ added_size -= local_exit_stub_size(dcontext, target, trace_flags); exits_deleted++; } else if (instr_opcode_valid(inst) && instr_is_cti(inst)) { LOG(THREAD, LOG_MONITOR, 3, "WARNING: deleting non-exit cti in unused tail of frag added to " "trace\n"); } d_r_loginst(dcontext, 4, inst, "\tdeleting"); instrlist_remove(trace, inst); added_size -= instr_length(dcontext, inst); instr_destroy(dcontext, inst); } } if (num_exits_deleted != NULL) *num_exits_deleted = exits_deleted; if (record_translation) instrlist_set_translation_target(trace, NULL); instrlist_set_our_mangling(trace, false); /* PR 267260 */ #if defined(X86) && defined(X64) DOCHECK(1, { if (FRAG_IS_32(trace_flags)) { instr_t *in; /* in case we missed any in tracelist_add() */ for (in = instrlist_first(trace); in != NULL; in = instr_get_next(in)) { if (instr_is_our_mangling(in)) ASSERT(instr_get_x86_mode(in)); } } }); #endif ASSERT(added_size < TRACE_CTI_MANGLE_SIZE_UPPER_BOUND); return added_size; } /* Add a speculative counter on last IBL exit * Returns additional size to add to trace estimate. */ int append_trace_speculate_last_ibl(dcontext_t *dcontext, instrlist_t *trace, app_pc speculate_next_tag, bool record_translation) { /* unlike fixup_last_cti() here we are about to go directly to the IBL routine */ /* spill XCX in a scratch slot - note always using TLS */ int added_size = 0; ibl_type_t ibl_type; instr_t *inst = instrlist_last(trace); /* currently only relevant to last CTI */ instr_t *where = inst; /* preinsert before last CTI */ instr_t *next = instr_get_next(inst); DEBUG_DECLARE(bool ok;) ASSERT(speculate_next_tag != NULL); ASSERT(inst != NULL); ASSERT(instr_is_exit_cti(inst)); /* FIXME: see if can test the instr flags instead */ DEBUG_DECLARE(ok =) get_ibl_routine_type(dcontext, opnd_get_pc(instr_get_target(inst)), &ibl_type); ASSERT(ok); if (record_translation) instrlist_set_translation_target(trace, instr_get_translation(inst)); instrlist_set_our_mangling(trace, true); /* PR 267260 */ STATS_INC(num_traces_end_at_ibl_speculative_link); #ifdef HASHTABLE_STATISTICS DOSTATS({ if (INTERNAL_OPTION(speculate_last_exit_stats)) { int tls_stat_scratch_slot = os_tls_offset(HTABLE_STATS_SPILL_SLOT); added_size += tracelist_add( dcontext, trace, where, XINST_CREATE_store(dcontext, opnd_create_tls_slot(tls_stat_scratch_slot), opnd_create_reg(SCRATCH_REG2))); added_size += insert_increment_stat_counter( dcontext, trace, where, &get_ibl_per_type_statistics(dcontext, ibl_type.branch_type) ->ib_trace_last_ibl_exit); added_size += tracelist_add( dcontext, trace, where, XINST_CREATE_load(dcontext, opnd_create_reg(SCRATCH_REG2), opnd_create_tls_slot(tls_stat_scratch_slot))); } }); #endif /* preinsert comparison before exit CTI, but increment of success * statistics after it */ /* we need to compare to speculate_next_tag now */ /* XCX holds value to match */ /* should use similar eflags-clobbering scheme to inline cmp */ IF_X64(ASSERT_NOT_IMPLEMENTED(false)); /* * 8d 89 76 9b bf ff lea -tag(%ecx) -> %ecx * e3 0b jecxz continue * 8d 89 8a 64 40 00 lea tag(%ecx) -> %ecx * e9 17 00 00 00 jmp <exit stub 1: IBL> * * continue: * <increment stats> * # see FIXME whether to go to prefix or do here * <restore app ecx> * e9 cc aa dd 00 jmp speculate_next_tag * */ /* leave jmp as it is, a jmp to exit stub (thence to ind br lookup) */ added_size += insert_transparent_comparison(dcontext, trace, where, speculate_next_tag); #ifdef HASHTABLE_STATISTICS DOSTATS({ reg_id_t reg = IF_X86_ELSE(REG_XCX, DR_REG_R2); if (INTERNAL_OPTION(speculate_last_exit_stats)) { int tls_stat_scratch_slot = os_tls_offset(HTABLE_STATS_SPILL_SLOT); /* XCX already saved */ added_size += insert_increment_stat_counter( dcontext, trace, next, &get_ibl_per_type_statistics(dcontext, ibl_type.branch_type) ->ib_trace_last_ibl_speculate_success); /* restore XCX to app IB target*/ added_size += tracelist_add( dcontext, trace, next, XINST_CREATE_load(dcontext, opnd_create_reg(reg), opnd_create_tls_slot(tls_stat_scratch_slot))); } }); #endif /* adding a new CTI for speculative target that is a pseudo * direct exit. Although we could have used the indirect stub * to be the unlinked path, with a new CTI way we can unlink a * speculated fragment without affecting any other targets * reached by the IBL. Also in general we could decide to add * multiple speculative comparisons and to chain them we'd * need new CTIs for them. */ /* Ensure all register state is properly preserved on both linked * and unlinked paths - currently only XCX is in use. * * * Preferably we should be targeting prefix of target to * save some space for recovering XCX from hot path. We'd * restore XCX in the exit stub when unlinked. * So it would act like a direct CTI when linked and like indirect * when unlinked. It could just be an unlinked indirect stub, if * we haven't modified any other registers or flags. * * For simplicity, we currently restore XCX here and use a plain * direct exit stub that goes to target start_pc instead of * prefixes. * * FIXME: (case 5085) the problem with the current scheme is that * when we exit unlinked the source will be marked as a DIRECT * exit - therefore no security policies will be enforced. * * FIXME: (case 4718) should add speculated target to current list * in case of RCT policy that needs to be invalidated if target is * flushed */ /* must restore xcx to app value, FIXME: see above for doing this in prefix+stub */ added_size += insert_restore_spilled_xcx(dcontext, trace, next); /* add a new direct exit stub */ added_size += tracelist_add(dcontext, trace, next, XINST_CREATE_jump(dcontext, opnd_create_pc(speculate_next_tag))); LOG(THREAD, LOG_INTERP, 3, "append_trace_speculate_last_ibl: added cmp vs. " PFX " for ind br\n", speculate_next_tag); if (record_translation) instrlist_set_translation_target(trace, NULL); instrlist_set_our_mangling(trace, false); /* PR 267260 */ return added_size; } #ifdef HASHTABLE_STATISTICS /* Add a counter on last IBL exit * if speculate_next_tag is not NULL then check case 4817's possible success */ /* FIXME: remove this routine once append_trace_speculate_last_ibl() * currently useful only to see statistics without side effects of * adding exit stub */ int append_ib_trace_last_ibl_exit_stat(dcontext_t *dcontext, instrlist_t *trace, app_pc speculate_next_tag) { /* unlike fixup_last_cti() here we are about to go directly to the IBL routine */ /* spill XCX in a scratch slot - note always using TLS */ int tls_stat_scratch_slot = os_tls_offset(HTABLE_STATS_SPILL_SLOT); int added_size = 0; ibl_type_t ibl_type; instr_t *inst = instrlist_last(trace); /* currently only relevant to last CTI */ instr_t *where = inst; /* preinsert before exit CTI */ reg_id_t reg = IF_X86_ELSE(REG_XCX, DR_REG_R2); DEBUG_DECLARE(bool ok;) /* should use similar eflags-clobbering scheme to inline cmp */ IF_X64(ASSERT_NOT_IMPLEMENTED(false)); ASSERT(inst != NULL); ASSERT(instr_is_exit_cti(inst)); /* FIXME: see if can test the instr flags instead */ ok = get_ibl_routine_type(dcontext, opnd_get_pc(instr_get_target(inst)), &ibl_type); ASSERT(ok); added_size += tracelist_add( dcontext, trace, where, XINST_CREATE_store(dcontext, opnd_create_tls_slot(tls_stat_scratch_slot), opnd_create_reg(reg))); added_size += insert_increment_stat_counter( dcontext, trace, where, &get_ibl_per_type_statistics(dcontext, ibl_type.branch_type) ->ib_trace_last_ibl_exit); added_size += tracelist_add(dcontext, trace, where, XINST_CREATE_load(dcontext, opnd_create_reg(reg), opnd_create_tls_slot(tls_stat_scratch_slot))); if (speculate_next_tag != NULL) { instr_t *next = instr_get_next(inst); /* preinsert comparison before exit CTI, but increment goes after it */ /* we need to compare to speculate_next_tag now - just like * fixup_last_cti() would do later. */ /* ECX holds value to match here */ /* leave jmp as it is, a jmp to exit stub (thence to ind br lookup) */ /* continue: * increment success counter * jmp targeter * * FIXME: now the last instruction is no longer the exit_cti - see if that * breaks any assumptions, using a short jump to see if anyone erroneously * uses this */ added_size += insert_transparent_comparison(dcontext, trace, where, speculate_next_tag); /* we'll kill again although ECX restored unnecessarily by comparison routine */ added_size += insert_increment_stat_counter( dcontext, trace, next, &get_ibl_per_type_statistics(dcontext, ibl_type.branch_type) ->ib_trace_last_ibl_speculate_success); /* restore ECX */ added_size += tracelist_add(dcontext, trace, next, XINST_CREATE_load(dcontext, opnd_create_reg(reg), opnd_create_tls_slot(tls_stat_scratch_slot))); /* jmp where */ added_size += tracelist_add(dcontext, trace, next, IF_X86_ELSE(INSTR_CREATE_jmp_short, XINST_CREATE_jump)( dcontext, opnd_create_instr(where))); } return added_size; } #endif /* HASHTABLE_STATISTICS */ /* Add the fragment f to the end of the trace instrlist_t kept in dcontext * * Note that recreate_fragment_ilist() is making assumptions about its operation * synchronize changes * * Returns the size change in the trace from mangling the previous block * (assumes the caller has already calculated the size from adding the new block) */ uint extend_trace(dcontext_t *dcontext, fragment_t *f, linkstub_t *prev_l) { monitor_data_t *md = (monitor_data_t *)dcontext->monitor_field; fragment_t *prev_f = NULL; instrlist_t *trace = &(md->trace); instrlist_t *ilist; uint size; uint prev_mangle_size = 0; uint num_exits_deleted = 0; uint new_exits_dir = 0, new_exits_indir = 0; #ifdef X64 ASSERT((!!FRAG_IS_32(md->trace_flags) == !X64_MODE_DC(dcontext)) || (!FRAG_IS_32(md->trace_flags) && !X64_MODE_DC(dcontext) && DYNAMO_OPTION(x86_to_x64))); #endif STATS_INC(num_traces_extended); /* if you want to re-add the ability to add traces, revive * CUSTOM_TRACES_ADD_TRACE from the attic */ ASSERT(!TEST(FRAG_IS_TRACE, f->flags)); /* expecting block fragments */ if (prev_l != NULL) { ASSERT(!LINKSTUB_FAKE(prev_l) || /* we track the ordinal of the del linkstub so it's ok */ prev_l == get_deleted_linkstub(dcontext)); prev_f = linkstub_fragment(dcontext, prev_l); LOG(THREAD, LOG_MONITOR, 4, "prev_l = owned by F%d, branch pc " PFX "\n", prev_f->id, EXIT_CTI_PC(prev_f, prev_l)); } else { LOG(THREAD, LOG_MONITOR, 4, "prev_l is NULL\n"); } /* insert code to optimize last branch based on new fragment */ if (instrlist_last(trace) != NULL) { prev_mangle_size = fixup_last_cti(dcontext, trace, f->tag, f->flags, md->trace_flags, prev_f, prev_l, false, &num_exits_deleted, NULL, NULL); } #ifdef CUSTOM_TRACES_RET_REMOVAL /* add now, want fixup to operate on depth before adding new blk */ dcontext->call_depth += f->num_calls; dcontext->call_depth -= f->num_rets; #endif LOG(THREAD, LOG_MONITOR, 4, "\tadding block %d == " PFX "\n", md->num_blks, f->tag); size = md->trace_buf_size - md->trace_buf_top; LOG(THREAD, LOG_MONITOR, 4, "decoding F%d into trace buf @" PFX " + 0x%x = " PFX "\n", f->id, md->trace_buf, md->trace_buf_top, md->trace_buf + md->trace_buf_top); /* FIXME: PR 307388: if md->pass_to_client, much of this is a waste of time as * we're going to re-mangle and re-fixup after passing our unmangled list to the * client. We do want to keep the size estimate, which requires having the last * cti at least, so for now we keep all the work. Of course the size estimate is * less valuable when the client may add a ton of instrumentation. */ /* decode_fragment will convert f's ibl routines into those appropriate for * our trace, whether f and the trace are shared or private */ ilist = decode_fragment(dcontext, f, md->trace_buf + md->trace_buf_top, &size, md->trace_flags, &new_exits_dir, &new_exits_indir); md->blk_info[md->num_blks].info.tag = f->tag; #if defined(RETURN_AFTER_CALL) || defined(RCT_IND_BRANCH) if (md->num_blks > 0) md->blk_info[md->num_blks - 1].info.num_exits -= num_exits_deleted; md->blk_info[md->num_blks].info.num_exits = new_exits_dir + new_exits_indir; #endif md->num_blks++; /* We need to remove any nops we added for -pad_jmps (we don't expect there * to be any in a bb if -pad_jmps_shift_bb) to avoid screwing up * fixup_last_cti etc. */ process_nops_for_trace(dcontext, ilist, f->flags _IF_DEBUG(false /*!recreating*/)); DOLOG(5, LOG_MONITOR, { LOG(THREAD, LOG_MONITOR, 5, "post-trace-ibl-fixup, ilist is:\n"); instrlist_disassemble(dcontext, f->tag, ilist, THREAD); }); ASSERT(!instrlist_get_our_mangling(ilist)); instrlist_append(trace, instrlist_first(ilist)); instrlist_init(ilist); /* clear fields so destroy won't kill instrs on trace list */ instrlist_destroy(dcontext, ilist); md->trace_buf_top += size; ASSERT(md->trace_buf_top < md->trace_buf_size); LOG(THREAD, LOG_MONITOR, 4, "post-extend_trace, trace buf + 0x%x => " PFX "\n", md->trace_buf_top, md->trace_buf); DOLOG(4, LOG_MONITOR, { LOG(THREAD, LOG_MONITOR, 4, "\nafter extending trace:\n"); instrlist_disassemble(dcontext, md->trace_tag, trace, THREAD); }); return prev_mangle_size; } /* If branch_type is 0, sets it to the type of a ubr */ static instr_t * create_exit_jmp(dcontext_t *dcontext, app_pc target, app_pc translation, uint branch_type) { instr_t *jmp = XINST_CREATE_jump(dcontext, opnd_create_pc(target)); instr_set_translation(jmp, translation); if (branch_type == 0) instr_exit_branch_set_type(jmp, instr_branch_type(jmp)); else instr_exit_branch_set_type(jmp, branch_type); instr_set_our_mangling(jmp, true); return jmp; } /* Given an ilist with no mangling or stitching together, this routine does those * things. This is used both for clients and for recreating traces * for state translation. * It assumes the ilist abides by client rules: single-mbr bbs, no * changes in source app code. Else, it returns false. * Elision is supported. * * Our docs disallow removal of an entire block, changing inter-block ctis, and * changing the ordering of the blocks, which is what allows us to correctly * mangle the inter-block ctis here. * * Reads the following fields from md: * - trace_tag * - trace_flags * - num_blks * - blk_info * - final_exit_flags */ bool mangle_trace(dcontext_t *dcontext, instrlist_t *ilist, monitor_data_t *md) { instr_t *inst, *next_inst, *start_instr, *jmp; uint blk, num_exits_deleted; app_pc fallthrough = NULL; bool found_syscall = false, found_int = false; /* We don't assert that mangle_trace_at_end() is true b/c the client * can unregister its bb and trace hooks if it really wants to, * though we discourage it. */ ASSERT(md->pass_to_client); LOG(THREAD, LOG_MONITOR, 2, "mangle_trace " PFX "\n", md->trace_tag); DOLOG(4, LOG_INTERP, { LOG(THREAD, LOG_INTERP, 4, "ilist passed to mangle_trace:\n"); instrlist_disassemble(dcontext, md->trace_tag, ilist, THREAD); }); /* We make 3 passes. * 1st walk: find bb boundaries */ blk = 0; for (inst = instrlist_first(ilist); inst != NULL; inst = next_inst) { app_pc xl8 = instr_get_translation(inst); next_inst = instr_get_next(inst); if (instr_is_meta(inst)) continue; DOLOG(5, LOG_INTERP, { LOG(THREAD, LOG_MONITOR, 4, "transl " PFX " ", xl8); d_r_loginst(dcontext, 4, inst, "considering non-meta"); }); /* Skip blocks that don't end in ctis (except final) */ while (blk < md->num_blks - 1 && !md->blk_info[blk].final_cti) { LOG(THREAD, LOG_MONITOR, 4, "skipping fall-through bb #%d\n", blk); md->blk_info[blk].end_instr = NULL; blk++; } /* Ensure non-ignorable syscall/int2b terminates trace */ if (md->pass_to_client && !client_check_syscall(ilist, inst, &found_syscall, &found_int)) return false; /* Clients should not add new source code regions, which would mess us up * here, as well as mess up our cache consistency (both page prot and * selfmod). */ if (md->pass_to_client && (!vm_list_overlaps(dcontext, md->blk_info[blk].vmlist, xl8, xl8 + 1) && !(instr_is_ubr(inst) && opnd_is_pc(instr_get_target(inst)) && xl8 == opnd_get_pc(instr_get_target(inst)))) IF_WINDOWS(&&!vmvector_overlap(landing_pad_areas, md->blk_info[blk].info.tag, md->blk_info[blk].info.tag + 1))) { LOG(THREAD, LOG_MONITOR, 2, "trace error: out-of-bounds transl " PFX " vs block w/ start " PFX "\n", xl8, md->blk_info[blk].info.tag); CLIENT_ASSERT(false, "trace's app sources (instr_set_translation() targets) " "must remain within original bounds"); return false; } /* in case no exit ctis in last block, find last non-meta fall-through */ if (blk == md->num_blks - 1) { /* Do not call instr_length() on this inst: use length * of translation! (i#509) */ fallthrough = decode_next_pc(dcontext, xl8); } /* PR 299808: identify bb boundaries. We can't go by translations alone, as * ubrs can point at their targets and theoretically the entire trace could * be ubrs: so we have to go by exits, and limit what the client can do. We * can assume that each bb should not violate the bb callback rules (PR * 215217): if has cbr or mbr, that must end bb. If it has a call, that * could be elided; if not, its target should match the start of the next * block. We also want to * impose the can't-be-trace rules (PR 215219), which are not documented for * bbs: if more than one exit cti or if code beyond last exit cti then can't * be in a trace. We can soften a little and allow extra ubrs if they do not * target the subsequent block. FIXME: we could have stricter translation * reqts for ubrs: make them point at corresponding app ubr (but what if * really correspond to app cbr?): then can handle code past exit ubr. */ if (instr_will_be_exit_cti(inst) && ((!instr_is_ubr(inst) && !instr_is_near_call_direct(inst)) || (inst == instrlist_last(ilist) || (blk + 1 < md->num_blks && /* client is disallowed from changing bb exits and sequencing in trace * hook; if they change in bb for_trace, will be reflected here. */ opnd_get_pc(instr_get_target(inst)) == md->blk_info[blk + 1].info.tag)))) { DOLOG(4, LOG_INTERP, { d_r_loginst(dcontext, 4, inst, "end of bb"); }); /* Add jump that fixup_last_cti expects */ if (!instr_is_ubr(inst) IF_X86(|| instr_get_opcode(inst) == OP_jmp_far)) { app_pc target; if (instr_is_mbr(inst) IF_X86(|| instr_get_opcode(inst) == OP_jmp_far)) { target = get_ibl_routine( dcontext, get_ibl_entry_type(instr_branch_type(inst)), DEFAULT_IBL_TRACE(), get_ibl_branch_type(inst)); } else if (instr_is_cbr(inst)) { /* Do not call instr_length() on this inst: use length * of translation! (i#509) */ target = decode_next_pc(dcontext, xl8); } else { target = opnd_get_pc(instr_get_target(inst)); } ASSERT(target != NULL); jmp = create_exit_jmp(dcontext, target, xl8, instr_branch_type(inst)); instrlist_postinsert(ilist, inst, jmp); /* we're now done w/ vmlist: switch to end instr. * d_r_mangle() shouldn't remove the exit cti. */ vm_area_destroy_list(dcontext, md->blk_info[blk].vmlist); md->blk_info[blk].vmlist = NULL; md->blk_info[blk].end_instr = jmp; } else md->blk_info[blk].end_instr = inst; blk++; DOLOG(4, LOG_INTERP, { if (blk < md->num_blks) { LOG(THREAD, LOG_MONITOR, 4, "starting next bb " PFX "\n", md->blk_info[blk].info.tag); } }); if (blk >= md->num_blks && next_inst != NULL) { CLIENT_ASSERT(false, "unsupported trace modification: too many exits"); return false; } } #if defined(RETURN_AFTER_CALL) || defined(RCT_IND_BRANCH) /* PR 306761: we need to re-calculate md->blk_info[blk].info.num_exits, * and then adjust after fixup_last_cti. */ if (instr_will_be_exit_cti(inst)) md->blk_info[blk].info.num_exits++; #endif } if (blk < md->num_blks) { ASSERT(!instr_is_ubr(instrlist_last(ilist))); if (blk + 1 < md->num_blks) { CLIENT_ASSERT(false, "unsupported trace modification: too few exits"); return false; } /* must have been no final exit cti: add final fall-through jmp */ jmp = create_exit_jmp(dcontext, fallthrough, fallthrough, 0); /* FIXME PR 307284: support client modifying, replacing, or adding * syscalls and ints: need to re-analyze. Then we wouldn't * need the md->final_exit_flags field anymore. * For now we disallow. */ if (found_syscall || found_int) { instr_exit_branch_set_type(jmp, md->final_exit_flags); #ifdef WINDOWS /* For INSTR_SHARED_SYSCALL, we set it pre-mangling, and it * survives to here if the instr is not clobbered, * and does not come from md->final_exit_flags */ if (TEST(INSTR_SHARED_SYSCALL, instrlist_last(ilist)->flags)) { instr_set_target(jmp, opnd_create_pc(shared_syscall_routine(dcontext))); instr_set_our_mangling(jmp, true); /* undone by target set */ } /* FIXME: test for linux too, but allowing ignorable syscalls */ if (!TESTANY(LINK_NI_SYSCALL_ALL IF_WINDOWS(| LINK_CALLBACK_RETURN), md->final_exit_flags) && !TEST(INSTR_SHARED_SYSCALL, instrlist_last(ilist)->flags)) { CLIENT_ASSERT(false, "client modified or added a syscall or int: unsupported"); return false; } #endif } instrlist_append(ilist, jmp); md->blk_info[blk].end_instr = jmp; } else { CLIENT_ASSERT((!found_syscall && !found_int) /* On linux we allow ignorable syscalls in middle. * FIXME PR 307284: see notes above. */ IF_UNIX(|| !TEST(LINK_NI_SYSCALL, md->final_exit_flags)), "client changed exit target where unsupported\n" "check if trace ends in a syscall or int"); } ASSERT(instr_is_ubr(instrlist_last(ilist))); if (found_syscall) md->trace_flags |= FRAG_HAS_SYSCALL; else md->trace_flags &= ~FRAG_HAS_SYSCALL; /* 2nd walk: mangle */ DOLOG(4, LOG_INTERP, { LOG(THREAD, LOG_INTERP, 4, "trace ilist before mangling:\n"); instrlist_disassemble(dcontext, md->trace_tag, ilist, THREAD); }); /* We do not need to remove nops since we never emitted */ d_r_mangle(dcontext, ilist, &md->trace_flags, true /*mangle calls*/, /* we're post-client so we don't need translations unless storing */ TEST(FRAG_HAS_TRANSLATION_INFO, md->trace_flags)); DOLOG(4, LOG_INTERP, { LOG(THREAD, LOG_INTERP, 4, "trace ilist after mangling:\n"); instrlist_disassemble(dcontext, md->trace_tag, ilist, THREAD); }); /* 3rd walk: stitch together delineated bbs */ for (blk = 0; blk < md->num_blks && md->blk_info[blk].end_instr == NULL; blk++) ; /* nothing */ start_instr = instrlist_first(ilist); for (inst = instrlist_first(ilist); inst != NULL; inst = next_inst) { next_inst = instr_get_next(inst); if (inst == md->blk_info[blk].end_instr) { /* Chain exit to point to next bb */ if (blk + 1 < md->num_blks) { /* We must do proper analysis so that state translation matches * created traces in whether eflags are restored post-cmp */ uint next_flags = forward_eflags_analysis(dcontext, ilist, instr_get_next(inst)); next_flags = instr_eflags_to_fragment_eflags(next_flags); LOG(THREAD, LOG_INTERP, 4, "next_flags for fixup_last_cti: 0x%x\n", next_flags); fixup_last_cti(dcontext, ilist, md->blk_info[blk + 1].info.tag, next_flags, md->trace_flags, NULL, NULL, TEST(FRAG_HAS_TRANSLATION_INFO, md->trace_flags), &num_exits_deleted, /* Only walk ilist between these instrs */ start_instr, inst); #if defined(RETURN_AFTER_CALL) || defined(RCT_IND_BRANCH) md->blk_info[blk].info.num_exits -= num_exits_deleted; #endif } blk++; /* skip fall-throughs */ while (blk < md->num_blks && md->blk_info[blk].end_instr == NULL) blk++; if (blk >= md->num_blks && next_inst != NULL) { CLIENT_ASSERT(false, "unsupported trace modification: exits modified"); return false; } start_instr = next_inst; } } if (blk < md->num_blks) { CLIENT_ASSERT(false, "unsupported trace modification: cannot find all exits"); return false; } return true; } /**************************************************************************** * UTILITIES */ /* Converts instr_t EFLAGS_ flags to corresponding fragment_t FRAG_ flags, * assuming that the instr_t flags correspond to the start of the fragment_t. * Assumes instr_eflags has already accounted for predication. */ uint instr_eflags_to_fragment_eflags(uint instr_eflags) { uint frag_eflags = 0; #ifdef X86 if (instr_eflags == EFLAGS_WRITE_OF) { /* this fragment writes OF before reading it * May still read other flags before writing them. */ frag_eflags |= FRAG_WRITES_EFLAGS_OF; return frag_eflags; } #endif if (instr_eflags == EFLAGS_WRITE_ARITH) { /* fragment writes all 6 prior to reading */ frag_eflags |= FRAG_WRITES_EFLAGS_ARITH; #ifdef X86 frag_eflags |= FRAG_WRITES_EFLAGS_OF; #endif } return frag_eflags; } /* Returns one of these flags, defined in instr.h: * EFLAGS_WRITE_ARITH = writes all arith flags before reading any * EFLAGS_WRITE_OF = writes OF before reading it (x86-only) * EFLAGS_READ_ARITH = reads some of arith flags before writing * EFLAGS_READ_OF = reads OF before writing OF (x86-only) * 0 = no information before 1st cti */ uint forward_eflags_analysis(dcontext_t *dcontext, instrlist_t *ilist, instr_t *instr) { instr_t *in; uint eflags_6 = 0; /* holds flags written so far (in read slots) */ int eflags_result = 0; for (in = instr; in != NULL; in = instr_get_next_expanded(dcontext, ilist, in)) { if (!instr_valid(in) || instr_is_cti(in)) { /* give up */ break; } if (eflags_result != EFLAGS_WRITE_ARITH IF_X86(&&eflags_result != EFLAGS_READ_OF)) eflags_result = eflags_analysis(in, eflags_result, &eflags_6); DOLOG(4, LOG_INTERP, { d_r_loginst(dcontext, 4, in, "forward_eflags_analysis"); LOG(THREAD, LOG_INTERP, 4, "\tinstr %x => %x\n", instr_get_eflags(in, DR_QUERY_DEFAULT), eflags_result); }); } return eflags_result; } /* This translates f's code into an instrlist_t and returns it. * If buf is NULL: * The Instrs returned point into f's raw bits, so encode them * before you delete f! * Else, f's raw bits are copied into buf, and *bufsz is modified to * contain the total bytes copied * FIXME: should have release build checks and not just asserts where * we rely on caller to have big-enough buffer? * If target_flags differ from f->flags in sharing and/or in trace-ness, * converts ibl and tls usage in f to match the desired target_flags. * FIXME: converting from private to shared tls is not yet * implemented: we rely on -private_ib_in_tls for adding normal * private bbs to shared traces, and disallow any extensive mangling * (native_exec, selfmod) from becoming shared traces. * The caller is responsible for destroying the instrlist and its instrs. * If the fragment ends in an elided jmp, a new jmp instr is created, though * its bits field is NULL, allowing the caller to set it to do-not-emit if * trying to exactly duplicate or calculate the size, though most callers * will want to emit that jmp. See decode_fragment_exact(). */ static void instr_set_raw_bits_trace_buf(instr_t *instr, byte *buf_writable_addr, uint length) { /* The trace buffer is a writable address, so we need to translate to an * executable address for pointing at bits. */ instr_set_raw_bits(instr, vmcode_get_executable_addr(buf_writable_addr), length); } /* We want to avoid low-loglevel disassembly when we're in the middle of disassembly */ #define DF_LOGLEVEL(dc) (((dc) != GLOBAL_DCONTEXT && (dc)->in_opnd_disassemble) ? 6U : 4U) instrlist_t * decode_fragment(dcontext_t *dcontext, fragment_t *f, byte *buf, /*IN/OUT*/ uint *bufsz, uint target_flags, /*OUT*/ uint *dir_exits, /*OUT*/ uint *indir_exits) { linkstub_t *l; cache_pc start_pc, stop_pc, pc, prev_pc = NULL, raw_start_pc; instr_t *instr, *cti = NULL, *raw_instr; instrlist_t *ilist = instrlist_create(dcontext); byte *top_buf = NULL, *cur_buf = NULL; app_pc target_tag; uint num_bytes, offset; uint num_dir = 0, num_indir = 0; bool tls_to_dc; bool shared_to_private = TEST(FRAG_SHARED, f->flags) && !TEST(FRAG_SHARED, target_flags); #ifdef WINDOWS /* The fragment could contain an ignorable sysenter instruction if * the following conditions are satisfied. */ bool possible_ignorable_sysenter = DYNAMO_OPTION(ignore_syscalls) && (get_syscall_method() == SYSCALL_METHOD_SYSENTER) && TEST(FRAG_HAS_SYSCALL, f->flags); #endif instrlist_t intra_ctis; coarse_info_t *info = NULL; bool coarse_elided_ubrs = false; dr_isa_mode_t old_mode; /* for decoding and get_ibl routines we need the dcontext mode set */ bool ok = dr_set_isa_mode(dcontext, FRAG_ISA_MODE(f->flags), &old_mode); /* i#1494: Decoding a code fragment from code cache, decode_fragment * may mess up the 32-bit/64-bit mode in -x86_to_x64 because 32-bit * application code is encoded as 64-bit code fragments into the code cache. * Thus we currently do not support using decode_fragment with -x86_to_x64, * including trace and coarse_units (coarse-grain code cache management) */ IF_X86_64(ASSERT(!DYNAMO_OPTION(x86_to_x64))); instrlist_init(&intra_ctis); /* Now we need to go through f and make cti's for each of its exit cti's and * non-exit cti's with off-fragment targets that need to be re-pc-relativized. * The rest of the instructions can be lumped into raw instructions. */ start_pc = FCACHE_ENTRY_PC(f); pc = start_pc; raw_start_pc = start_pc; if (buf != NULL) { cur_buf = buf; top_buf = cur_buf; ASSERT(bufsz != NULL); } /* Handle code after last exit but before stubs by allowing l to be NULL. * Handle coarse-grain fake fragment_t by discovering exits as we go, with * l being NULL the whole time. */ if (TEST(FRAG_FAKE, f->flags)) { ASSERT(TEST(FRAG_COARSE_GRAIN, f->flags)); info = get_fragment_coarse_info(f); ASSERT(info != NULL); coarse_elided_ubrs = (info->persisted && TEST(PERSCACHE_ELIDED_UBR, info->flags)) || (!info->persisted && DYNAMO_OPTION(coarse_freeze_elide_ubr)); /* Assumption: coarse-grain fragments have no ctis w/ off-fragment targets * that are not exit ctis */ l = NULL; } else l = FRAGMENT_EXIT_STUBS(f); while (true) { uint l_flags; cti = NULL; if (l != NULL) { stop_pc = EXIT_CTI_PC(f, l); } else if (TEST(FRAG_FAKE, f->flags)) { /* we don't know the size of f */ stop_pc = (cache_pc)UNIVERSAL_REGION_END; } else { /* fake fragment_t, or code between last exit but before stubs or padding */ stop_pc = fragment_body_end_pc(dcontext, f); if (PAD_FRAGMENT_JMPS(f->flags) && stop_pc != raw_start_pc) { /* We need to adjust stop_pc to account for any padding, only * way any code could get here is via client interface, * and there really is no nice way to distinguish it * from any padding we added. * PR 213005: we do not support decode_fragment() for bbs * that have code added beyond the last exit cti (we turn * off FRAG_COARSE_GRAIN and set FRAG_CANNOT_BE_TRACE). * Sanity check, make sure it at least looks like there is no * code here */ ASSERT(IS_SET_TO_DEBUG(raw_start_pc, stop_pc - raw_start_pc)); stop_pc = raw_start_pc; } } IF_X64(ASSERT(TEST(FRAG_FAKE, f->flags) /* no copy made */ || CHECK_TRUNCATE_TYPE_uint((stop_pc - raw_start_pc)))); num_bytes = (uint)(stop_pc - raw_start_pc); LOG(THREAD, LOG_MONITOR, DF_LOGLEVEL(dcontext), "decoding fragment from " PFX " to " PFX "\n", raw_start_pc, stop_pc); if (num_bytes > 0) { if (buf != NULL) { if (TEST(FRAG_FAKE, f->flags)) { /* we don't know the size of f, so we copy later, though * we do point instrs into buf before we copy! */ } else { /* first copy entire sequence up to exit cti into buf * so we don't have to copy it in pieces if we find cti's, if we don't * find any we want one giant piece anyway */ ASSERT(cur_buf + num_bytes < buf + *bufsz); memcpy(cur_buf, raw_start_pc, num_bytes); top_buf = cur_buf + num_bytes; LOG(THREAD, LOG_MONITOR, DF_LOGLEVEL(dcontext), "decode_fragment: copied " PFX "-" PFX " to " PFX "-" PFX "\n", raw_start_pc, raw_start_pc + num_bytes, cur_buf, cur_buf + num_bytes); /* cur_buf is incremented later -- it always points to start * of raw bytes for next-to-add-to-ilist instr, while * top_buf points to top of copied-to-buf data */ } } else { /* point at bits in code cache */ cur_buf = raw_start_pc; } /* now, we can't make a single raw instr for all that, there may * be calls with off-fragment targets in there that need to be * re-pc-relativized (instrumentation, etc. insert calls), or * we may not even know where the exit ctis are (coarse-grain fragments), * so walk through (original bytes!) and decode, looking for cti's */ instr = instr_create(dcontext); pc = raw_start_pc; /* do we have to translate the store of xcx from tls to dcontext? * be careful -- there can be private bbs w/ indirect branches, so * must see if this is a shared fragment we're adding */ tls_to_dc = (shared_to_private && !DYNAMO_OPTION(private_ib_in_tls) && /* if l==NULL (coarse src) we'll check for xcx every time */ (l == NULL || LINKSTUB_INDIRECT(l->flags))); do { #ifdef WINDOWS cache_pc prev_decode_pc = prev_pc; /* store the address of the * previous decode, the instr * before the one 'pc' * currently points to *before* * the call to decode() just * below */ #endif /* For frozen coarse fragments, ubr eliding forces us to check * every instr for a potential next fragment start. This is * expensive so users are advised to decode from app code if * possible (case 9325 -- need exact re-mangle + re-instrument), * though -coarse_pclookup_table helps. */ if (info != NULL && info->frozen && coarse_elided_ubrs && pc != start_pc) { /* case 6532: check for ib stubs as we elide the jmp there too */ bool stop = false; if (coarse_is_indirect_stub(pc)) { stop = true; LOG(THREAD, LOG_MONITOR, DF_LOGLEVEL(dcontext) - 1, "\thit ib stub @" PFX "\n", pc); } else { app_pc tag = fragment_coarse_entry_pclookup(dcontext, info, pc); if (tag != NULL) { stop = true; LOG(THREAD, LOG_MONITOR, DF_LOGLEVEL(dcontext) - 1, "\thit frozen tgt: " PFX "." PFX "\n", tag, pc); } } if (stop) { /* Add the ubr ourselves */ ASSERT(cti == NULL); cti = XINST_CREATE_jump(dcontext, opnd_create_pc(pc)); /* It's up to the caller to decide whether to mark this * as do-not-emit or not */ /* Process as an exit cti */ stop_pc = pc; pc = stop_pc; break; } } instr_reset(dcontext, instr); prev_pc = pc; pc = IF_AARCH64_ELSE(decode_cti_with_ldstex, decode_cti)(dcontext, pc, instr); DOLOG(DF_LOGLEVEL(dcontext), LOG_INTERP, { disassemble_with_info(dcontext, prev_pc, THREAD, true, true); }); #ifdef WINDOWS /* Perform fixups for ignorable syscalls on XP & 2003. */ if (possible_ignorable_sysenter && instr_opcode_valid(instr) && instr_is_syscall(instr)) { /* We want to find the instr preceding the sysenter and have * it point to the post-sysenter instr in the trace, rather than * remain pointing to the post-sysenter instr in the BB. */ instr_t *sysenter_prev; instr_t *sysenter_post; ASSERT(prev_decode_pc != NULL); LOG(THREAD, LOG_MONITOR, DF_LOGLEVEL(dcontext), "decode_fragment: sysenter found @" PFX "\n", instr_get_raw_bits(instr)); /* create single raw instr for instructions up to the * sysenter EXCEPT for the immediately preceding instruction */ offset = (int)(prev_decode_pc - raw_start_pc); ASSERT(offset > 0); raw_instr = instr_create(dcontext); /* point to buffer bits */ instr_set_raw_bits_trace_buf(raw_instr, cur_buf, offset); instrlist_append(ilist, raw_instr); cur_buf += offset; /* Get the "mov" instr just before the sysenter. We know that * it's there because mangle put it there, so we can safely * decode at prev_decode_pc. */ sysenter_prev = instr_create(dcontext); decode(dcontext, prev_decode_pc, sysenter_prev); ASSERT(instr_valid(instr) && instr_is_mov_imm_to_tos(sysenter_prev)); instrlist_append(ilist, sysenter_prev); cur_buf += instr_length(dcontext, sysenter_prev); /* Append the sysenter. */ instr_set_raw_bits_trace_buf(instr, cur_buf, (int)(pc - prev_pc)); instrlist_append(ilist, instr); instr_set_meta(instr); /* skip current instr -- the sysenter */ cur_buf += (int)(pc - prev_pc); /* Decode the next instr -- the one after the sysenter. */ sysenter_post = instr_create(dcontext); prev_decode_pc = pc; prev_pc = pc; pc = decode(dcontext, pc, sysenter_post); if (DYNAMO_OPTION(ignore_syscalls_follow_sysenter)) ASSERT(!instr_is_cti(sysenter_post)); raw_start_pc = pc; /* skip the post-sysenter instr */ cur_buf += (int)(pc - prev_pc); instrlist_append(ilist, sysenter_post); /* Point the pre-sysenter mov to the post-sysenter instr. */ instr_set_src(sysenter_prev, 0, opnd_create_instr(sysenter_post)); instr_set_meta(sysenter_prev); instr_set_meta(sysenter_post); DOLOG(DF_LOGLEVEL(dcontext), LOG_INTERP, { LOG(THREAD, LOG_INTERP, DF_LOGLEVEL(dcontext), "Post-sysenter -- F%d (" PFX ") into:\n", f->id, f->tag); instrlist_disassemble(dcontext, f->tag, ilist, THREAD); }); /* Set all local state so that we can fall-thru and correctly * process the post-sysenter instruction. Point instr to the * already decoded instruction, sysenter_post. At this point, * pc and raw_start_pc point to just after sysenter_post, * prev_pc points to sysenter_post, prev_decode_pc points to * the sysenter itself, and cur_buf points to post_sysenter. */ instr = sysenter_post; } #endif /* look for a cti with an off-fragment target */ if (instr_opcode_valid(instr) && instr_is_cti(instr)) { bool separate_cti = false; bool re_relativize = false; bool intra_target = true; DOLOG(DF_LOGLEVEL(dcontext), LOG_MONITOR, { d_r_loginst(dcontext, 4, instr, "decode_fragment: found non-exit cti"); }); if (TEST(FRAG_FAKE, f->flags)) { /* Case 8711: we don't know the size so we can't even * distinguish off-fragment from intra-fragment targets. * Thus we have to assume that any cti is an exit cti, and * make all fragments for which that is not true into * fine-grained. * Except that we want to support intra-fragment ctis for * clients (i#665), so we use some heuristics. */ if (instr_is_cti_short_rewrite(instr, prev_pc)) { /* Pull in the two short jmps for a "short-rewrite" instr. * We must do this before asking whether it's an * intra-fragment so we don't just look at the * first part of the sequence. */ pc = remangle_short_rewrite(dcontext, instr, prev_pc, 0 /*same target*/); } if (!coarse_cti_is_intra_fragment(dcontext, info, instr, start_pc)) { /* Process this cti as an exit cti. FIXME: we will then * re-copy the raw bytes from this cti to the end of the * fragment at the top of the next loop iter, but for * coarse-grain bbs that should be just one instr for cbr bbs * or none for others, so not worth doing anything about. */ DOLOG(DF_LOGLEVEL(dcontext), LOG_MONITOR, { d_r_loginst(dcontext, DF_LOGLEVEL(dcontext), instr, "\tcoarse exit cti"); }); intra_target = false; stop_pc = prev_pc; pc = stop_pc; break; } else { /* we'll make it to intra_target if() below */ DOLOG(DF_LOGLEVEL(dcontext), LOG_MONITOR, { d_r_loginst(dcontext, DF_LOGLEVEL(dcontext), instr, "\tcoarse intra-fragment cti"); }); } } else if (instr_is_return(instr) || !opnd_is_near_pc(instr_get_target(instr))) { /* just leave it undecoded */ intra_target = false; } else if (instr_is_cti_short_rewrite(instr, prev_pc)) { /* Cti-short should only occur as exit ctis, which are * separated out unless we're decoding a fake fragment. We * include this case for future use, as otherwise we'll * decode just the short cti and think it is an * intra-fragment cti. */ ASSERT_NOT_REACHED(); separate_cti = true; re_relativize = true; intra_target = false; } else if (opnd_get_pc(instr_get_target(instr)) < start_pc || opnd_get_pc(instr_get_target(instr)) > start_pc + f->size) { separate_cti = true; re_relativize = true; intra_target = false; DOLOG(DF_LOGLEVEL(dcontext), LOG_MONITOR, { d_r_loginst(dcontext, 4, instr, "\tcti has off-fragment target"); }); } if (intra_target) { /* intra-fragment target: we'll change its target operand * from pc to instr_t in second pass, so remember it here */ instr_t *clone = instr_clone(dcontext, instr); /* HACK: use note field! */ instr_set_note(clone, (void *)instr); /* we leave the clone pointing at valid original raw bits */ instrlist_append(&intra_ctis, clone); /* intra-fragment target */ DOLOG(DF_LOGLEVEL(dcontext), LOG_MONITOR, { d_r_loginst(dcontext, 4, instr, "\tcti has intra-fragment target"); }); /* since the resulting instrlist could be manipulated, * we need to change the target operand from pc to instr_t. * that requires having this instr separated out now so * our clone-in-note-field hack above works. */ separate_cti = true; re_relativize = false; } if (separate_cti) { /* create single raw instr for instructions up to the cti */ offset = (int)(prev_pc - raw_start_pc); if (offset > 0) { raw_instr = instr_create(dcontext); /* point to buffer bits */ instr_set_raw_bits_trace_buf(raw_instr, cur_buf, offset); instrlist_append(ilist, raw_instr); cur_buf += offset; raw_start_pc = prev_pc; } /* now append cti, indicating that relative target must be * re-encoded, and that it is not an exit cti */ instr_set_meta(instr); if (re_relativize) instr_set_raw_bits_valid(instr, false); else if (!instr_is_cti_short_rewrite(instr, NULL)) { instr_set_raw_bits_trace_buf(instr, cur_buf, (int)(pc - prev_pc)); } instrlist_append(ilist, instr); /* include buf for off-fragment cti, to simplify assert below */ cur_buf += (int)(pc - prev_pc); raw_start_pc = pc; /* create new instr for future fast decodes */ instr = instr_create(dcontext); } } /* is cti */ /* instr_is_tls_xcx_spill won't upgrade from level 1 */ else if (tls_to_dc && instr_is_tls_xcx_spill(instr)) { /* shouldn't get here for x64, where everything uses tls */ IF_X64(ASSERT_NOT_IMPLEMENTED(false)); LOG(THREAD, LOG_MONITOR, DF_LOGLEVEL(dcontext), "mangling xcx save from tls to dcontext\n"); /* create single raw instr for instructions up to the xcx save */ offset = (int)(prev_pc - raw_start_pc); if (offset > 0) { raw_instr = instr_create(dcontext); /* point to buffer bits */ instr_set_raw_bits_trace_buf(raw_instr, cur_buf, offset); instrlist_append(ilist, raw_instr); cur_buf += offset; raw_start_pc = prev_pc; } /* now append our new xcx save */ instrlist_append(ilist, instr_create_save_to_dcontext( dcontext, IF_X86_ELSE(REG_XCX, DR_REG_R2), IF_X86_ELSE(XCX_OFFSET, R2_OFFSET))); /* make sure skip current instr */ cur_buf += (int)(pc - prev_pc); raw_start_pc = pc; } #if defined(X86) && defined(X64) else if (instr_has_rel_addr_reference(instr)) { /* We need to re-relativize, which is done automatically only for * level 1 instrs (PR 251479), and only when raw bits point to * their original location. We assume that all the if statements * above end up creating a high-level instr, so a cti w/ a * rip-rel operand is already covered. */ /* create single raw instr for instructions up to this one */ offset = (int)(prev_pc - raw_start_pc); if (offset > 0) { raw_instr = instr_create(dcontext); /* point to buffer bits */ instr_set_raw_bits_trace_buf(raw_instr, cur_buf, offset); instrlist_append(ilist, raw_instr); cur_buf += offset; raw_start_pc = prev_pc; } /* should be valid right now since pointing at original bits */ ASSERT(instr_rip_rel_valid(instr)); if (buf != NULL) { /* re-relativize into the new buffer */ DEBUG_DECLARE(byte *nxt =) instr_encode_to_copy(dcontext, instr, cur_buf, vmcode_get_executable_addr(cur_buf)); instr_set_raw_bits_trace_buf(instr, vmcode_get_executable_addr(cur_buf), (int)(pc - prev_pc)); instr_set_rip_rel_valid(instr, true); ASSERT(nxt != NULL); } instrlist_append(ilist, instr); cur_buf += (int)(pc - prev_pc); raw_start_pc = pc; /* create new instr for future fast decodes */ instr = instr_create(dcontext); } #endif } while (pc < stop_pc); DODEBUG({ if (pc != stop_pc) { LOG(THREAD, LOG_MONITOR, DF_LOGLEVEL(dcontext), "PC " PFX ", stop_pc " PFX "\n", pc, stop_pc); } }); ASSERT(pc == stop_pc); cache_pc next_pc = pc; if (l != NULL && TEST(LINK_PADDED, l->flags) && instr_is_nop(instr)) { /* Throw away our padding nop. */ LOG(THREAD, LOG_MONITOR, DF_LOGLEVEL(dcontext) - 1, "%s: removing padding nop @" PFX "\n", __FUNCTION__, prev_pc); pc = prev_pc; if (buf != NULL) top_buf -= instr_length(dcontext, instr); } /* create single raw instr for rest of instructions up to exit cti */ if (pc > raw_start_pc) { instr_reset(dcontext, instr); /* point to buffer bits */ offset = (int)(pc - raw_start_pc); if (offset > 0) { instr_set_raw_bits_trace_buf(instr, cur_buf, offset); instrlist_append(ilist, instr); cur_buf += offset; } if (buf != NULL && TEST(FRAG_FAKE, f->flags)) { /* Now that we know the size we can copy into buf. * We have been incrementing cur_buf all along, though * we didn't have contents there. */ ASSERT(top_buf < cur_buf); IF_X64(ASSERT(CHECK_TRUNCATE_TYPE_uint((cur_buf - top_buf)))); num_bytes = (uint)(cur_buf - top_buf); ASSERT(cur_buf + num_bytes < buf + *bufsz); memcpy(cur_buf, raw_start_pc, num_bytes); top_buf = cur_buf + num_bytes; LOG(THREAD, LOG_MONITOR, DF_LOGLEVEL(dcontext), "decode_fragment: copied " PFX "-" PFX " to " PFX "-" PFX "\n", raw_start_pc, raw_start_pc + num_bytes, cur_buf, cur_buf + num_bytes); } ASSERT(buf == NULL || cur_buf == top_buf); } else { /* will reach here if had a processed instr (off-fragment target, etc.) * immediately prior to exit cti, so now don't need instr -- an * example (in absence of clients) is trampoline to interception code */ instr_destroy(dcontext, instr); } pc = next_pc; } if (l == NULL && !TEST(FRAG_FAKE, f->flags)) break; /* decode the exit branch */ if (cti != NULL) { /* already created */ instr = cti; ASSERT(info != NULL && info->frozen && instr_is_ubr(instr)); raw_start_pc = pc; } else { instr = instr_create(dcontext); raw_start_pc = decode(dcontext, stop_pc, instr); ASSERT(raw_start_pc != NULL); /* our own code! */ /* pc now points into fragment! */ } ASSERT(instr_is_ubr(instr) || instr_is_cbr(instr)); /* replace fcache target with target_tag and add to fragment */ if (l == NULL) { app_pc instr_tgt; /* Ensure we get proper target for short cti sequence */ if (instr_is_cti_short_rewrite(instr, stop_pc)) remangle_short_rewrite(dcontext, instr, stop_pc, 0 /*same target*/); instr_tgt = opnd_get_pc(instr_get_target(instr)); ASSERT(TEST(FRAG_COARSE_GRAIN, f->flags)); if (cti == NULL && coarse_is_entrance_stub(instr_tgt)) { target_tag = entrance_stub_target_tag(instr_tgt, info); l_flags = LINK_DIRECT; /* FIXME; try to get LINK_JMP vs LINK_CALL vs fall-through? */ LOG(THREAD, LOG_MONITOR, DF_LOGLEVEL(dcontext) - 1, "\tstub tgt: " PFX " => " PFX "\n", instr_tgt, target_tag); } else if (instr_tgt == raw_start_pc /*target next instr*/ /* could optimize by not checking for stub if * coarse_elided_ubrs but we need to know whether ALL * ubrs were elided, which we don't know as normally * entire-bb-ubrs are not elided (case 9677). * plus now that we elide jmp-to-ib-stub we must check. */ && coarse_is_indirect_stub(instr_tgt)) { ibl_type_t ibl_type; DEBUG_DECLARE(bool is_ibl;) target_tag = coarse_indirect_stub_jmp_target(instr_tgt); l_flags = LINK_INDIRECT; DEBUG_DECLARE(is_ibl =) get_ibl_routine_type_ex(dcontext, target_tag, &ibl_type _IF_X86_64(NULL)); ASSERT(is_ibl); l_flags |= ibltype_to_linktype(ibl_type.branch_type); LOG(THREAD, LOG_MONITOR, DF_LOGLEVEL(dcontext) - 1, "\tind stub tgt: " PFX " => " PFX "\n", instr_tgt, target_tag); } else { target_tag = fragment_coarse_entry_pclookup(dcontext, info, instr_tgt); /* Only frozen units don't jump through stubs */ ASSERT(info != NULL && info->frozen); ASSERT(target_tag != NULL); l_flags = LINK_DIRECT; LOG(THREAD, LOG_MONITOR, DF_LOGLEVEL(dcontext) - 1, "\tfrozen tgt: " PFX "." PFX "\n", target_tag, instr_tgt); } } else { target_tag = EXIT_TARGET_TAG(dcontext, f, l); l_flags = l->flags; } if (LINKSTUB_DIRECT(l_flags)) num_dir++; else num_indir++; ASSERT(target_tag != NULL); if (instr_is_cti_short_rewrite(instr, stop_pc)) { raw_start_pc = remangle_short_rewrite(dcontext, instr, stop_pc, target_tag); } else { app_pc new_target = target_tag; /* don't point to fcache bits */ instr_set_raw_bits_valid(instr, false); LOG(THREAD, LOG_MONITOR, DF_LOGLEVEL(dcontext) - 1, "decode_fragment exit_cti: pc=" PFX " l->target_tag=" PFX " l->flags=0x%x\n", stop_pc, target_tag, l_flags); /* need to propagate exit branch type flags, * instr_t flag copied from old fragment linkstub * TODO: when ibl targets are different this won't be necessary */ instr_exit_branch_set_type(instr, linkstub_propagatable_flags(l_flags)); /* convert to proper ibl */ if (is_indirect_branch_lookup_routine(dcontext, target_tag)) { DEBUG_DECLARE(app_pc old_target = new_target;) new_target = get_alternate_ibl_routine(dcontext, target_tag, target_flags); ASSERT(new_target != NULL); /* for stats on traces, we assume if target_flags contains * FRAG_IS_TRACE then we are extending a trace */ DODEBUG({ LOG(THREAD, LOG_MONITOR, DF_LOGLEVEL(dcontext) - 1, "%s: %s ibl_routine " PFX " with %s_target=" PFX "\n", TEST(FRAG_IS_TRACE, target_flags) ? "extend_trace" : "decode_fragment", new_target == old_target ? "maintaining" : "replacing", old_target, new_target == old_target ? "old" : "new", new_target); STATS_INC(num_traces_ibl_extended); }); #ifdef WINDOWS DOSTATS({ if (TEST(FRAG_IS_TRACE, target_flags) && old_target == shared_syscall_routine(dcontext)) STATS_INC(num_traces_shared_syscall_extended); }); #endif } instr_set_target(instr, opnd_create_pc(new_target)); if (instr_is_cti_short(instr)) { /* make sure non-mangled short ctis, which are generated by * us and never left there from apps, are not marked as exit ctis */ instr_set_meta(instr); } } instrlist_append(ilist, instr); if (TEST(FRAG_FAKE, f->flags)) { /* Assumption: coarse-grain bbs have 1 ind exit or 2 direct, * and no code beyond the last exit! Of course frozen bbs * can have their final jmp elided, which we handle above. */ if (instr_is_ubr(instr)) { break; } } if (l != NULL) /* if NULL keep going: discovering exits as we go */ l = LINKSTUB_NEXT_EXIT(l); } /* end while(true) loop through exit stubs */ /* now fix up intra-trace cti targets */ if (instrlist_first(&intra_ctis) != NULL) { /* We have to undo all of our level 0 blocks by expanding. * Any instrs that need re-relativization should already be * separate, so this should not affect rip-rel instrs. */ int offs = 0; for (instr = instrlist_first_expanded(dcontext, ilist); instr != NULL; instr = instr_get_next_expanded(dcontext, ilist, instr)) { for (cti = instrlist_first(&intra_ctis); cti != NULL; cti = instr_get_next(cti)) { /* The clone we put in intra_ctis has raw bits equal to the * original bits, so its target will be in original fragment body. * We can't rely on the raw bits of the new instrs (since the * non-level-0 ones may have allocated raw bits) so we * calculate a running offset as we go. */ if (opnd_get_pc(instr_get_target(cti)) - start_pc == offs) { /* cti targets this instr */ instr_t *real_cti = (instr_t *)instr_get_note(cti); /* PR 333691: do not preserve raw bits of real_cti, since * instrlist may change (e.g., inserted nops). Must re-encode * once instrlist is finalized. */ instr_set_target(real_cti, opnd_create_instr(instr)); DOLOG(DF_LOGLEVEL(dcontext), LOG_MONITOR, { d_r_loginst(dcontext, 4, real_cti, "\tre-set intra-fragment target"); }); break; } } offs += instr_length(dcontext, instr); } } instrlist_clear(dcontext, &intra_ctis); DOLOG(DF_LOGLEVEL(dcontext), LOG_INTERP, { LOG(THREAD, LOG_INTERP, DF_LOGLEVEL(dcontext), "Decoded F%d (" PFX "." PFX ") into:\n", f->id, f->tag, FCACHE_ENTRY_PC(f)); instrlist_disassemble(dcontext, f->tag, ilist, THREAD); }); ok = dr_set_isa_mode(dcontext, old_mode, NULL); ASSERT(ok); if (dir_exits != NULL) *dir_exits = num_dir; if (indir_exits != NULL) *indir_exits = num_indir; if (buf != NULL) { IF_X64(ASSERT(CHECK_TRUNCATE_TYPE_uint((top_buf - buf)))); *bufsz = (uint)(top_buf - buf); } return ilist; } #undef DF_LOGLEVEL /* Just like decode_fragment() but marks any instrs missing in the cache * as do-not-emit */ instrlist_t * decode_fragment_exact(dcontext_t *dcontext, fragment_t *f, byte *buf, /*IN/OUT*/ uint *bufsz, uint target_flags, /*OUT*/ uint *dir_exits, /*OUT*/ uint *indir_exits) { instrlist_t *ilist = decode_fragment(dcontext, f, buf, bufsz, target_flags, dir_exits, indir_exits); /* If the final jmp was elided we do NOT want to count it in the size! */ if (instr_get_raw_bits(instrlist_last(ilist)) == NULL) { instr_set_ok_to_emit(instrlist_last(ilist), false); } return ilist; } /* Makes a new copy of fragment f * If replace is true, * removes f from the fcache and adds the new copy in its place * Else * creates f as an invisible fragment (caller is responsible for linking * the new fragment!) */ fragment_t * copy_fragment(dcontext_t *dcontext, fragment_t *f, bool replace) { instrlist_t *trace = instrlist_create(dcontext); instr_t *instr; uint *trace_buf; int trace_buf_top; /* index of next free location in trace_buf */ linkstub_t *l; byte *p; cache_pc start_pc; int num_bytes; fragment_t *new_f; void *vmlist = NULL; app_pc target_tag; DEBUG_DECLARE(bool ok;) trace_buf = heap_alloc(dcontext, f->size * 2 HEAPACCT(ACCT_FRAGMENT)); start_pc = FCACHE_ENTRY_PC(f); trace_buf_top = 0; p = ((byte *)trace_buf) + trace_buf_top; IF_X64(ASSERT_NOT_IMPLEMENTED(false)); /* must re-relativize when copying! */ for (l = FRAGMENT_EXIT_STUBS(f); l; l = LINKSTUB_NEXT_EXIT(l)) { /* Copy the instruction bytes up to (but not including) the first * control-transfer instruction. ***WARNING*** This code assumes * that the first link stub corresponds to the first exit branch * in the body. */ IF_X64(ASSERT(CHECK_TRUNCATE_TYPE_uint((EXIT_CTI_PC(f, l) - start_pc)))); num_bytes = (uint)(EXIT_CTI_PC(f, l) - start_pc); if (num_bytes > 0) { memcpy(p, (byte *)start_pc, num_bytes); trace_buf_top += num_bytes; start_pc += num_bytes; /* build a mongo instruction corresponding to the copied instructions */ instr = instr_create(dcontext); instr_set_raw_bits(instr, p, num_bytes); instrlist_append(trace, instr); } /* decode the exit branch */ instr = instr_create(dcontext); p = decode(dcontext, (byte *)EXIT_CTI_PC(f, l), instr); ASSERT(p != NULL); /* our own code! */ /* p now points into fragment! */ ASSERT(instr_is_ubr(instr) || instr_is_cbr(instr)); /* Replace cache_pc target with target_tag and add to trace. For * an indirect branch, the target_tag is zero. */ target_tag = EXIT_TARGET_TAG(dcontext, f, l); ASSERT(target_tag); if (instr_is_cti_short_rewrite(instr, EXIT_CTI_PC(f, l))) { p = remangle_short_rewrite(dcontext, instr, EXIT_CTI_PC(f, l), target_tag); } else { /* no short ctis that aren't mangled should be exit ctis */ ASSERT(!instr_is_cti_short(instr)); instr_set_target(instr, opnd_create_pc(target_tag)); } instrlist_append(trace, instr); start_pc += (p - (byte *)EXIT_CTI_PC(f, l)); } /* emit as invisible fragment */ /* We don't support shared fragments, where vm_area_add_to_list can fail */ ASSERT_NOT_IMPLEMENTED(!TEST(FRAG_SHARED, f->flags)); DEBUG_DECLARE(ok =) vm_area_add_to_list(dcontext, f->tag, &vmlist, f->flags, f, false /*no locks*/); ASSERT(ok); /* should never fail for private fragments */ new_f = emit_invisible_fragment(dcontext, f->tag, trace, f->flags, vmlist); if (replace) { /* link and replace old fragment */ shift_links_to_new_fragment(dcontext, f, new_f); fragment_replace(dcontext, f, new_f); } else { /* caller is responsible for linking new fragment */ } ASSERT(new_f->flags == f->flags); fragment_copy_data_fields(dcontext, f, new_f); #ifdef DEBUG if (d_r_stats->loglevel > 1) { LOG(THREAD, LOG_ALL, 2, "Copying F%d to F%d\n", f->id, new_f->id); disassemble_fragment(dcontext, f, d_r_stats->loglevel < 3); disassemble_fragment(dcontext, new_f, d_r_stats->loglevel < 3); } #endif /* DEBUG */ heap_free(dcontext, trace_buf, f->size * 2 HEAPACCT(ACCT_FRAGMENT)); /* free the instrlist_t elements */ instrlist_clear_and_destroy(dcontext, trace); if (replace) { fragment_delete(dcontext, f, FRAGDEL_NO_OUTPUT | FRAGDEL_NO_UNLINK | FRAGDEL_NO_HTABLE); STATS_INC(num_fragments_deleted_copy_and_replace); } return new_f; } /* Used when the code cache is enlarged by copying to a larger space, * and all of the relative ctis that target outside the cache need * to be shifted. Additionally, sysenter-related patching for ignore-syscalls * on XP/2003 is performed here, as the absolute code cache address pushed * onto the stack must be updated. * Assumption: old code cache has been copied to TOP of new cache, so to * detect for ctis targeting outside of old cache can look at new cache * start plus old cache size. */ void shift_ctis_in_fragment(dcontext_t *dcontext, fragment_t *f, ssize_t shift, cache_pc fcache_start, cache_pc fcache_end, size_t old_size) { cache_pc pc, prev_pc = NULL; cache_pc start_pc = FCACHE_ENTRY_PC(f); cache_pc stop_pc = fragment_stubs_end_pc(f); /* get what would have been end of cache if just shifted not resized */ cache_pc fcache_old_end = fcache_start + old_size; #ifdef WINDOWS /* The fragment could contain an ignorable sysenter instruction if * the following conditions are satisfied. */ bool possible_ignorable_sysenter = DYNAMO_OPTION(ignore_syscalls) && (get_syscall_method() == SYSCALL_METHOD_SYSENTER) && /* FIXME Traces don't have FRAG_HAS_SYSCALL set so we can't filter on * that flag for all fragments. */ (TEST(FRAG_HAS_SYSCALL, f->flags) || TEST(FRAG_IS_TRACE, f->flags)); #endif instr_t instr; instr_init(dcontext, &instr); pc = start_pc; while (pc < stop_pc) { #ifdef WINDOWS cache_pc prev_decode_pc = prev_pc; /* store the address of the * previous decode, the instr * before the one 'pc' * currently points to *before* * the call to decode_cti() just * below */ #endif prev_pc = pc; instr_reset(dcontext, &instr); pc = (cache_pc)decode_cti(dcontext, (byte *)pc, &instr); #ifdef WINDOWS /* Perform fixups for sysenter instrs when ignorable syscalls is used on * XP & 2003. These are not cache-external fixups, but it's convenient & * efficient to perform them here since decode_cti() is called on every * instruction, allowing identification of sysenters without additional * decoding. */ if (possible_ignorable_sysenter && instr_opcode_valid(&instr) && instr_is_syscall(&instr)) { cache_pc next_pc; app_pc target; DEBUG_DECLARE(app_pc old_target;) DEBUG_DECLARE(cache_pc encode_nxt;) /* Peek up to find the "mov $post-sysenter -> (%xsp)" */ instr_reset(dcontext, &instr); next_pc = decode(dcontext, prev_decode_pc, &instr); ASSERT(next_pc == prev_pc); LOG(THREAD, LOG_MONITOR, 4, "shift_ctis_in_fragment: pre-sysenter mov found @" PFX "\n", instr_get_raw_bits(&instr)); ASSERT(instr_is_mov_imm_to_tos(&instr)); target = instr_get_raw_bits(&instr) + instr_length(dcontext, &instr) + (pc - prev_pc); DODEBUG(old_target = (app_pc)opnd_get_immed_int(instr_get_src(&instr, 0));); /* PR 253943: we don't support sysenter in x64 */ IF_X64(ASSERT_NOT_IMPLEMENTED(false)); /* can't have 8-byte imm-to-mem */ instr_set_src(&instr, 0, opnd_create_immed_int((ptr_int_t)target, OPSZ_4)); ASSERT(old_target + shift == target); LOG(THREAD, LOG_MONITOR, 4, "shift_ctis_in_fragment: pre-sysenter mov now pts to @" PFX "\n", target); DEBUG_DECLARE(encode_nxt =) instr_encode_to_copy(dcontext, &instr, vmcode_get_writable_addr(prev_decode_pc), prev_decode_pc); /* must not change size! */ ASSERT(encode_nxt != NULL && vmcode_get_executable_addr(encode_nxt) == next_pc); } /* The following 'if' won't get executed since a sysenter isn't * a CTI instr, so we don't need an else. We do need to take care * that any 'else' clauses are added after the 'if' won't trigger * on a sysenter either. */ #endif /* look for a pc-relative cti (including exit ctis) w/ out-of-cache * target (anything in-cache is fine, the whole cache was moved) */ if (instr_is_cti(&instr) && /* only ret, ret_far, and iret don't have targets, and * we really shouldn't see them, except possibly if they * are inserted through instrumentation, so go ahead and * check num srcs */ instr_num_srcs(&instr) > 0 && opnd_is_near_pc(instr_get_target(&instr))) { app_pc target = opnd_get_pc(instr_get_target(&instr)); if (target < fcache_start || target > fcache_old_end) { DEBUG_DECLARE(byte * nxt_pc;) /* re-encode instr w/ new pc-relative target */ instr_set_raw_bits_valid(&instr, false); instr_set_target(&instr, opnd_create_pc(target - shift)); DEBUG_DECLARE(nxt_pc =) instr_encode_to_copy(dcontext, &instr, vmcode_get_writable_addr(prev_pc), prev_pc); /* must not change size! */ ASSERT(nxt_pc != NULL && vmcode_get_executable_addr(nxt_pc) == pc); #ifdef DEBUG if ((d_r_stats->logmask & LOG_CACHE) != 0) { d_r_loginst( dcontext, 5, &instr, "shift_ctis_in_fragment: found cti w/ out-of-cache target"); } #endif } } } instr_free(dcontext, &instr); } #ifdef PROFILE_RDTSC /* Add profile call to front of the trace in dc * Must call finalize_profile_call and pass it the fragment_t* * once the trace is turned into a fragment to fix up a few profile * call instructions. */ void add_profile_call(dcontext_t *dcontext) { monitor_data_t *md = (monitor_data_t *)dcontext->monitor_field; instrlist_t *trace = &(md->trace); byte *p = ((byte *)md->trace_buf) + md->trace_buf_top; instr_t *instr; uint num_bytes = profile_call_size(); ASSERT(num_bytes + md->trace_buf_top < md->trace_buf_size); insert_profile_call((cache_pc)p); /* use one giant BINARY instruction to hold everything, * to keep dynamo from interpreting the cti instructions as real ones */ instr = instr_create(dcontext); instr_set_raw_bits(instr, p, num_bytes); instrlist_prepend(trace, instr); md->trace_buf_top += num_bytes; } #endif /* emulates the effects of the instruction at pc with the state in mcontext * limited right now to only mov instructions * returns NULL if failed or not yet implemented, else returns the pc of the next instr. */ app_pc d_r_emulate(dcontext_t *dcontext, app_pc pc, priv_mcontext_t *mc) { instr_t instr; app_pc next_pc = NULL; uint opc; instr_init(dcontext, &instr); next_pc = decode(dcontext, pc, &instr); if (!instr_valid(&instr)) { next_pc = NULL; goto emulate_failure; } DOLOG(2, LOG_INTERP, { d_r_loginst(dcontext, 2, &instr, "emulating"); }); opc = instr_get_opcode(&instr); if (opc == OP_store) { opnd_t src = instr_get_src(&instr, 0); opnd_t dst = instr_get_dst(&instr, 0); reg_t *target; reg_t val; uint sz = opnd_size_in_bytes(opnd_get_size(dst)); ASSERT(opnd_is_memory_reference(dst)); if (sz != 4 IF_X64(&&sz != 8)) { next_pc = NULL; goto emulate_failure; } target = (reg_t *)opnd_compute_address_priv(dst, mc); if (opnd_is_reg(src)) { val = reg_get_value_priv(opnd_get_reg(src), mc); } else if (opnd_is_immed_int(src)) { val = (reg_t)opnd_get_immed_int(src); } else { next_pc = NULL; goto emulate_failure; } DOCHECK(1, { uint prot = 0; ASSERT(get_memory_info((app_pc)target, NULL, NULL, &prot)); ASSERT(TEST(MEMPROT_WRITE, prot)); }); LOG(THREAD, LOG_INTERP, 2, "\temulating store by writing " PFX " to " PFX "\n", val, target); if (sz == 4) *((int *)target) = (int)val; #ifdef X64 else if (sz == 8) *target = val; #endif } else if (opc == IF_X86_ELSE(OP_inc, OP_add) || opc == IF_X86_ELSE(OP_dec, OP_sub)) { opnd_t src = instr_get_src(&instr, 0); reg_t *target; uint sz = opnd_size_in_bytes(opnd_get_size(src)); if (sz != 4 IF_X64(&&sz != 8)) { next_pc = NULL; goto emulate_failure; } /* FIXME: handle changing register value */ ASSERT(opnd_is_memory_reference(src)); /* FIXME: change these to take in priv_mcontext_t* ? */ target = (reg_t *)opnd_compute_address_priv(src, mc); DOCHECK(1, { uint prot = 0; ASSERT(get_memory_info((app_pc)target, NULL, NULL, &prot)); ASSERT(TEST(MEMPROT_WRITE, prot)); }); LOG(THREAD, LOG_INTERP, 2, "\temulating %s to " PFX "\n", opc == IF_X86_ELSE(OP_inc, OP_add) ? "inc" : "dec", target); if (sz == 4) { if (opc == IF_X86_ELSE(OP_inc, OP_add)) (*((int *)target))++; else (*((int *)target))--; } #ifdef X64 else if (sz == 8) { if (opc == IF_X86_ELSE(OP_inc, OP_add)) (*target)++; else (*target)--; } #endif } emulate_failure: instr_free(dcontext, &instr); return next_pc; } #ifdef AARCH64 /* Emit addtional code to fix up indirect trace exit for AArch64. * For each indirect branch in trace we have the following code: * str x0, TLS_REG0_SLOT * mov x0, #trace_next_target * eor x0, x0, jump_target * cbnz x0, trace_exit (ibl_routine) * ldr x0, TLS_REG0_SLOT * For the trace_exit (ibl_routine), it needs to conform to the * protocol specified in emit_indirect_branch_lookup in * aarch64/emit_utils.c. * The ibl routine requires: * x2: contains indirect branch target * TLS_REG2_SLOT: contains app's x2 * Therefore we need to add addtional spill instructions * before we actually jump to the ibl routine. * We want the indirect hit path to have minimum instructions * and also conform to the protocol of ibl routine * Therefore we append the restore at the end of the trace * after the backward jump to trace head. * For example, the code will be fixed to: * eor x0, x0, jump_target * cbnz x0, trace_exit_label * ... * b trace_head * trace_exit_label: * ldr x0, TLS_REG0_SLOT * str x2, TLS_REG2_SLOT * mov x2, jump_target * b ibl_routine * * XXX i#2974 This way of having a trace_exit_label at the end of a trace * breaks the linear requirement which is assumed by a lot of code, including * translation. Currently recreation of instruction list is fixed by including * a special call to this function. We might need to consider add special * support in translate.c or use an alternative linear control flow. * */ int fixup_indirect_trace_exit(dcontext_t *dcontext, instrlist_t *trace) { instr_t *instr, *prev, *branch; instr_t *trace_exit_label; app_pc target = 0; app_pc ind_target = 0; app_pc instr_trans; reg_id_t scratch; reg_id_t jump_target_reg = DR_REG_NULL; uint indirect_type = 0; int added_size = 0; trace_exit_label = NULL; /* We record the original trace end */ instr_t *trace_end = instrlist_last(trace); LOG(THREAD, LOG_MONITOR, 4, "fixup the indirect trace exit\n"); /* It is possible that we have multiple indirect trace exits to fix up * when more than one basic blocks are added as the trace. * And so we iterate over the entire trace to look for indirect exits. */ for (instr = instrlist_first(trace); instr != trace_end; instr = instr_get_next(instr)) { if (instr_is_exit_cti(instr)) { target = instr_get_branch_target_pc(instr); /* Check for indirect exit. */ if (is_indirect_branch_lookup_routine(dcontext, (cache_pc)target)) { /* This branch must be a cbnz, or the last_cti was not fixed up. */ ASSERT(instr->opcode == OP_cbnz); trace_exit_label = INSTR_CREATE_label(dcontext); ind_target = target; /* Modify the target of the cbnz. */ instr_set_target(instr, opnd_create_instr(trace_exit_label)); indirect_type = instr_exit_branch_type(instr); /* unset exit type */ instr->flags &= ~EXIT_CTI_TYPES; instr_set_our_mangling(instr, true); /* Retrieve jump target reg from the xor instruction. */ prev = instr_get_prev(instr); ASSERT(prev->opcode == OP_eor); ASSERT(instr_num_srcs(prev) == 4 && opnd_is_reg(instr_get_src(prev, 1))); jump_target_reg = opnd_get_reg(instr_get_src(prev, 1)); ASSERT(ind_target && jump_target_reg != DR_REG_NULL); /* Choose any scratch register except the target reg. */ scratch = (jump_target_reg == DR_REG_X0) ? DR_REG_X1 : DR_REG_X0; /* Add the trace exit label. */ instrlist_append(trace, trace_exit_label); instr_trans = instr_get_translation(instr); /* ldr x0, TLS_REG0_SLOT */ instrlist_append(trace, INSTR_XL8(instr_create_restore_from_tls( dcontext, scratch, TLS_REG0_SLOT), instr_trans)); added_size += AARCH64_INSTR_SIZE; /* if x2 alerady contains the jump_target, then there is no need to store * it away and load value of jump target into it */ if (jump_target_reg != IBL_TARGET_REG) { /* str x2, TLS_REG2_SLOT */ instrlist_append( trace, INSTR_XL8(instr_create_save_to_tls(dcontext, IBL_TARGET_REG, TLS_REG2_SLOT), instr_trans)); added_size += AARCH64_INSTR_SIZE; /* mov IBL_TARGET_REG, jump_target */ ASSERT(jump_target_reg != DR_REG_NULL); instrlist_append( trace, INSTR_XL8(XINST_CREATE_move(dcontext, opnd_create_reg(IBL_TARGET_REG), opnd_create_reg(jump_target_reg)), instr_trans)); added_size += AARCH64_INSTR_SIZE; } /* b ibl_target */ branch = XINST_CREATE_jump(dcontext, opnd_create_pc(ind_target)); instr_exit_branch_set_type(branch, indirect_type); instr_set_translation(branch, instr_trans); instrlist_append(trace, branch); added_size += AARCH64_INSTR_SIZE; } } else if ((instr->opcode == OP_cbz || instr->opcode == OP_cbnz || instr->opcode == OP_tbz || instr->opcode == OP_tbnz) && instr_is_load_tls(instr_get_next(instr))) { /* Don't invoke the decoder; * only mangled instruction (by mangle_cbr_stolen_reg) reached here. */ instr_t *next = instr_get_next(instr); /* Get the actual target of the cbz/cbnz. */ opnd_t fall_target = instr_get_target(instr); /* Create new label. */ trace_exit_label = INSTR_CREATE_label(dcontext); instr_set_target(instr, opnd_create_instr(trace_exit_label)); /* Insert restore at end of trace. */ instrlist_append(trace, trace_exit_label); instr_trans = instr_get_translation(instr); /* ldr cbz_reg, TLS_REG0_SLOT */ reg_id_t mangled_reg = ((*(uint *)next->bytes) & 31) + DR_REG_START_GPR; instrlist_append(trace, INSTR_XL8(instr_create_restore_from_tls( dcontext, mangled_reg, TLS_REG0_SLOT), instr_trans)); added_size += AARCH64_INSTR_SIZE; /* b fall_target */ branch = XINST_CREATE_jump(dcontext, fall_target); instr_set_translation(branch, instr_trans); instrlist_append(trace, branch); added_size += AARCH64_INSTR_SIZE; /* Because of the jump, a new stub was created. * and it is possible that this jump is leaving the fragment * in which case we should not increase the size of the fragment */ if (instr_is_exit_cti(branch)) { added_size += DIRECT_EXIT_STUB_SIZE(0); } } } return added_size; } #endif
1
24,692
So the 32-bit tests on the new kernel hit this case? Won't they fail in debug build?
DynamoRIO-dynamorio
c
@@ -46,7 +46,9 @@ public class HTMLTestResults { private final HTMLSuiteResult suite; private static final String HEADER = "<html>\n" + - "<head><style type='text/css'>\n" + + "<head>\n"+ + "<meta charset=\"UTF-8\">\n"+ + "<style type='text/css'>\n" + "body, table {\n" + " font-family: Verdana, Arial, sans-serif;\n" + " font-size: 12;\n" +
1
// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package org.openqa.selenium.server.htmlrunner; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.net.URLDecoder; import java.text.MessageFormat; import java.util.Collection; import java.util.LinkedList; import java.util.List; /** * A data model class for the results of the Selenium HTMLRunner (aka TestRunner, FITRunner) * * @author Darren Cotterill * @author Ajit George */ public class HTMLTestResults { private final String result; private final String totalTime; private final String numTestTotal; private final String numTestPasses; private final String numTestFailures; private final String numCommandPasses; private final String numCommandFailures; private final String numCommandErrors; private final String seleniumVersion; private final String seleniumRevision; private final String log; private final HTMLSuiteResult suite; private static final String HEADER = "<html>\n" + "<head><style type='text/css'>\n" + "body, table {\n" + " font-family: Verdana, Arial, sans-serif;\n" + " font-size: 12;\n" + "}\n" + "\n" + "table {\n" + " border-collapse: collapse;\n" + " border: 1px solid #ccc;\n" + "}\n" + "\n" + "th, td {\n" + " padding-left: 0.3em;\n" + " padding-right: 0.3em;\n" + "}\n" + "\n" + "a {\n" + " text-decoration: none;\n" + "}\n" + "\n" + ".title {\n" + " font-style: italic;\n" + "}\n" + "\n" + ".selected {\n" + " background-color: #ffffcc;\n" + "}\n" + "\n" + ".status_done {\n" + " background-color: #eeffee;\n" + "}\n" + "\n" + ".status_passed {\n" + " background-color: #ccffcc;\n" + "}\n" + "\n" + ".status_failed {\n" + " background-color: #ffcccc;\n" + "}\n" + "\n" + ".breakpoint {\n" + " background-color: #cccccc;\n" + " border: 1px solid black;\n" + "}\n" + "</style><title>Test suite results</title></head>\n" + "<body>\n<h1>Test suite results </h1>"; private static final String SUMMARY_HTML = "\n\n<table>\n" + "<tr>\n<td>result:</td>\n<td>{0}</td>\n</tr>\n" + "<tr>\n<td>totalTime:</td>\n<td>{1}</td>\n</tr>\n" + "<tr>\n<td>numTestTotal:</td>\n<td>{2}</td>\n</tr>\n" + "<tr>\n<td>numTestPasses:</td>\n<td>{3}</td>\n</tr>\n" + "<tr>\n<td>numTestFailures:</td>\n<td>{4}</td>\n</tr>\n" + "<tr>\n<td>numCommandPasses:</td>\n<td>{5}</td>\n</tr>\n" + "<tr>\n<td>numCommandFailures:</td>\n<td>{6}</td>\n</tr>\n" + "<tr>\n<td>numCommandErrors:</td>\n<td>{7}</td>\n</tr>\n" + "<tr>\n<td>Selenium Version:</td>\n<td>{8}</td>\n</tr>\n" + "<tr>\n<td>Selenium Revision:</td>\n<td>{9}</td>\n</tr>\n" + "<tr>\n<td>{10}</td>\n<td>&nbsp;</td>\n</tr>\n</table>"; private static final String SUITE_HTML = "<tr>\n<td><a name=\"testresult{0}\">{1}</a><br/>{2}</td>\n<td>&nbsp;</td>\n</tr>"; private final List<String> testTables; public HTMLTestResults(String postedSeleniumVersion, String postedSeleniumRevision, String postedResult, String postedTotalTime, String postedNumTestTotal, String postedNumTestPasses, String postedNumTestFailures, String postedNumCommandPasses, String postedNumCommandFailures, String postedNumCommandErrors, String postedSuite, List<String> postedTestTables, String postedLog) { result = postedResult; numCommandFailures = postedNumCommandFailures; numCommandErrors = postedNumCommandErrors; suite = new HTMLSuiteResult(postedSuite); totalTime = postedTotalTime; numTestTotal = postedNumTestTotal; numTestPasses = postedNumTestPasses; numTestFailures = postedNumTestFailures; numCommandPasses = postedNumCommandPasses; testTables = postedTestTables; seleniumVersion = postedSeleniumVersion; seleniumRevision = postedSeleniumRevision; log = postedLog; } public String getResult() { return result; } public String getNumCommandErrors() { return numCommandErrors; } public String getNumCommandFailures() { return numCommandFailures; } public String getNumCommandPasses() { return numCommandPasses; } public String getNumTestFailures() { return numTestFailures; } public String getNumTestPasses() { return numTestPasses; } public Collection getTestTables() { return testTables; } public String getTotalTime() { return totalTime; } public int getNumTotalTests() { return Integer.parseInt(numTestPasses) + Integer.parseInt(numTestFailures); } public void write(Writer out) throws IOException { out.write(HEADER); out.write(MessageFormat.format(SUMMARY_HTML, result, totalTime, numTestTotal, numTestPasses, numTestFailures, numCommandPasses, numCommandFailures, numCommandErrors, seleniumVersion, seleniumRevision, suite.getUpdatedSuite())); out.write("<table>"); for (int i = 0; i < testTables.size(); i++) { String table = testTables.get(i).replace("\u00a0", "&nbsp;"); out.write(MessageFormat.format(SUITE_HTML, i, suite.getHref(i), table)); } out.write("</table><pre>\n"); if (log != null) { out.write(quoteCharacters(log)); } out.write("</pre></body></html>"); out.flush(); } public static String quoteCharacters(String s) { StringBuffer result = null; for (int i = 0, max = s.length(), delta = 0; i < max; i++) { char c = s.charAt(i); String replacement = null; if (c == '&') { replacement = "&amp;"; } else if (c == '<') { replacement = "&lt;"; } else if (c == '>') { replacement = "&gt;"; } else if (c == '"') { replacement = "&quot;"; } else if (c == '\'') { replacement = "&apos;"; } if (replacement != null) { if (result == null) { result = new StringBuffer(s); } result.replace(i + delta, i + delta + 1, replacement); delta += (replacement.length() - 1); } } if (result == null) { return s; } return result.toString(); } class UrlDecoder { public String decode(String string) { try { return URLDecoder.decode(string, System.getProperty("file.encoding")); } catch (UnsupportedEncodingException e) { return string; } } public List decodeListOfStrings(List list) { List<String> decodedList = new LinkedList<String>(); for (Object o : list) { decodedList.add(decode((String) o)); } return decodedList; } } }
1
13,139
Is there a recommended quote style for attributes? I see single and double here, double further down.
SeleniumHQ-selenium
rb
@@ -5,12 +5,14 @@ module RSpec::Core # with information about a particular event of interest. module Notifications - # The `CountNotification` represents notifications sent by the formatter - # which a single numerical count attribute. Currently used to notify - # formatters of the expected number of examples. + # The `StartNotification` represents a notification sent by the reporter + # when the suite is started. It contains the expected amount of examples + # to be executed, and the load time of RSpec. # # @attr count [Fixnum] the number counted - CountNotification = Struct.new(:count) + # @attr load_time [Float] the number of seconds taken to boot RSpec + # and load the spec files + StartNotification = Struct.new(:count, :load_time) # The `ExampleNotification` represents notifications sent by the reporter # which contain information about the current (or soon to be) example.
1
RSpec::Support.require_rspec_core "formatters/helpers" module RSpec::Core # Notifications are value objects passed to formatters to provide them # with information about a particular event of interest. module Notifications # The `CountNotification` represents notifications sent by the formatter # which a single numerical count attribute. Currently used to notify # formatters of the expected number of examples. # # @attr count [Fixnum] the number counted CountNotification = Struct.new(:count) # The `ExampleNotification` represents notifications sent by the reporter # which contain information about the current (or soon to be) example. # It is used by formatters to access information about that example. # # @example # def example_started(notification) # puts "Hey I started #{notification.example.description}" # end # # @attr example [RSpec::Core::Example] the current example ExampleNotification = Struct.new(:example) # The `FailedExampleNotification` extends `ExampleNotification` with # things useful for failed specs. # # @example # def example_failed(notification) # puts "Hey I failed :(" # puts "Here's my stack trace" # puts notification.exception.backtrace.join("\n") # end # # @attr [RSpec::Core::Example] example the current example # @see ExampleNotification class FailedExampleNotification < ExampleNotification # Returns the examples failure # # @return [Exception] The example failure def exception example.execution_result.exception end end # The `GroupNotification` represents notifications sent by the reporter which # contain information about the currently running (or soon to be) example group # It is used by formatters to access information about that group. # # @example # def example_group_started(notification) # puts "Hey I started #{notification.group.description}" # end # @attr group [RSpec::Core::ExampleGroup] the current group GroupNotification = Struct.new(:group) # The `MessageNotification` encapsulates generic messages that the reporter # sends to formatters. # # @attr message [String] the message MessageNotification = Struct.new(:message) # The `SeedNotification` holds the seed used to randomize examples and # wether that seed has been used or not. # # @attr seed [Fixnum] the seed used to randomize ordering # @attr used [Boolean] wether the seed has been used or not SeedNotification = Struct.new(:seed, :used) do # @api # @return [Boolean] has the seed been used? def seed_used? !!used end private :used end # The `SummaryNotification` holds information about the results of running # a test suite. It is used by formatters to provide information at the end # of the test run. # # @attr duration [Float] the time taken (in seconds) to run the suite # @attr example_count [Fixnum] the number of examples run # @attr failure_count [Fixnum] the number of failed examples # @attr pending_count [Fixnum] the number of pending examples class SummaryNotification < Struct.new(:duration, :example_count, :failure_count, :pending_count) include Formatters::Helpers # @api # @return [String] A line summarising the results of the spec run. def summary_line summary = pluralize(example_count, "example") summary << ", " << pluralize(failure_count, "failure") summary << ", #{pending_count} pending" if pending_count > 0 summary end # @api public # # Wraps the summary line with colors based on the configured # colors for failure, pending, and success. Defaults to red, # yellow, green accordingly. # # @param colorizer [#wrap] An object which supports wrapping text with # specific colors. # @return [String] A colorized summary line. def colorize_with(colorizer) if failure_count > 0 colorizer.wrap(summary_line, RSpec.configuration.failure_color) elsif pending_count > 0 colorizer.wrap(summary_line, RSpec.configuration.pending_color) else colorizer.wrap(summary_line, RSpec.configuration.success_color) end end end # The `DeprecationNotification` is issued by the reporter when a deprecated # part of RSpec is encountered. It represents information about the deprecated # call site. # # @attr message [String] A custom message about the deprecation # @attr deprecated [String] A custom message about the deprecation (alias of message) # @attr replacement [String] An optional replacement for the deprecation # @attr call_site [String] An optional call site from which the deprecation was issued DeprecationNotification = Struct.new(:deprecated, :message, :replacement, :call_site) do private_class_method :new # @api # Convenience way to initialize the notification def self.from_hash(data) new data[:deprecated], data[:message], data[:replacement], data[:call_site] end end # `NullNotification` represents a placeholder value for notifications that # currently require no information, but we may wish to extend in future. class NullNotification end end end
1
12,286
The description of `load_time` here is different from the description below..is that intentional?
rspec-rspec-core
rb
@@ -1547,6 +1547,10 @@ import 'programStyles'; return '<span class="cardImageIcon material-icons book"></span>'; case 'Folder': return '<span class="cardImageIcon material-icons folder"></span>'; + case 'BoxSet': + return '<span class="cardImageIcon material-icons collections"></span>'; + case 'Playlist': + return '<span class="cardImageIcon material-icons queue_music"></span>'; } if (options && options.defaultCardImageIcon) {
1
/* eslint-disable indent */ /** * Module for building cards from item data. * @module components/cardBuilder/cardBuilder */ import datetime from 'datetime'; import imageLoader from 'imageLoader'; import connectionManager from 'connectionManager'; import itemHelper from 'itemHelper'; import focusManager from 'focusManager'; import indicators from 'indicators'; import globalize from 'globalize'; import layoutManager from 'layoutManager'; import dom from 'dom'; import browser from 'browser'; import playbackManager from 'playbackManager'; import itemShortcuts from 'itemShortcuts'; import imageHelper from 'scripts/imagehelper'; import 'css!./card'; import 'paper-icon-button-light'; import 'programStyles'; const enableFocusTransform = !browser.slow && !browser.edge; /** * Generate the HTML markup for cards for a set of items. * @param items - The items used to generate cards. * @param options - The options of the cards. * @returns {string} The HTML markup for the cards. */ export function getCardsHtml(items, options) { if (arguments.length === 1) { options = arguments[0]; items = options.items; } return buildCardsHtmlInternal(items, options); } /** * Computes the number of posters per row. * @param {string} shape - Shape of the cards. * @param {number} screenWidth - Width of the screen. * @param {boolean} isOrientationLandscape - Flag for the orientation of the screen. * @returns {number} Number of cards per row for an itemsContainer. */ function getPostersPerRow(shape, screenWidth, isOrientationLandscape) { switch (shape) { case 'portrait': if (layoutManager.tv) { return 100 / 16.66666667; } if (screenWidth >= 2200) { return 100 / 10; } if (screenWidth >= 1920) { return 100 / 11.1111111111; } if (screenWidth >= 1600) { return 100 / 12.5; } if (screenWidth >= 1400) { return 100 / 14.28571428571; } if (screenWidth >= 1200) { return 100 / 16.66666667; } if (screenWidth >= 800) { return 5; } if (screenWidth >= 700) { return 4; } if (screenWidth >= 500) { return 100 / 33.33333333; } return 100 / 33.33333333; case 'square': if (layoutManager.tv) { return 100 / 16.66666667; } if (screenWidth >= 2200) { return 100 / 10; } if (screenWidth >= 1920) { return 100 / 11.1111111111; } if (screenWidth >= 1600) { return 100 / 12.5; } if (screenWidth >= 1400) { return 100 / 14.28571428571; } if (screenWidth >= 1200) { return 100 / 16.66666667; } if (screenWidth >= 800) { return 5; } if (screenWidth >= 700) { return 4; } if (screenWidth >= 500) { return 100 / 33.33333333; } return 2; case 'banner': if (screenWidth >= 2200) { return 100 / 25; } if (screenWidth >= 1200) { return 100 / 33.33333333; } if (screenWidth >= 800) { return 2; } return 1; case 'backdrop': if (layoutManager.tv) { return 100 / 25; } if (screenWidth >= 2500) { return 6; } if (screenWidth >= 1600) { return 5; } if (screenWidth >= 1200) { return 4; } if (screenWidth >= 770) { return 3; } if (screenWidth >= 420) { return 2; } return 1; case 'smallBackdrop': if (screenWidth >= 1600) { return 100 / 12.5; } if (screenWidth >= 1400) { return 100 / 14.2857142857; } if (screenWidth >= 1200) { return 100 / 16.666666666666666666; } if (screenWidth >= 1000) { return 5; } if (screenWidth >= 800) { return 4; } if (screenWidth >= 500) { return 100 / 33.33333333; } return 2; case 'overflowSmallBackdrop': if (layoutManager.tv) { return 100 / 18.9; } if (isOrientationLandscape) { if (screenWidth >= 800) { return 100 / 15.5; } return 100 / 23.3; } else { if (screenWidth >= 540) { return 100 / 30; } return 100 / 72; } case 'overflowPortrait': if (layoutManager.tv) { return 100 / 15.5; } if (isOrientationLandscape) { if (screenWidth >= 1700) { return 100 / 11.6; } return 100 / 15.5; } else { if (screenWidth >= 1400) { return 100 / 15; } if (screenWidth >= 1200) { return 100 / 18; } if (screenWidth >= 760) { return 100 / 23; } if (screenWidth >= 400) { return 100 / 31.5; } return 100 / 42; } case 'overflowSquare': if (layoutManager.tv) { return 100 / 15.5; } if (isOrientationLandscape) { if (screenWidth >= 1700) { return 100 / 11.6; } return 100 / 15.5; } else { if (screenWidth >= 1400) { return 100 / 15; } if (screenWidth >= 1200) { return 100 / 18; } if (screenWidth >= 760) { return 100 / 23; } if (screenWidth >= 540) { return 100 / 31.5; } return 100 / 42; } case 'overflowBackdrop': if (layoutManager.tv) { return 100 / 23.3; } if (isOrientationLandscape) { if (screenWidth >= 1700) { return 100 / 18.5; } return 100 / 23.3; } else { if (screenWidth >= 1800) { return 100 / 23.5; } if (screenWidth >= 1400) { return 100 / 30; } if (screenWidth >= 760) { return 100 / 40; } if (screenWidth >= 640) { return 100 / 56; } return 100 / 72; } default: return 4; } } /** * Checks if the window is resizable. * @param {number} windowWidth - Width of the device's screen. * @returns {boolean} - Result of the check. */ function isResizable(windowWidth) { const screen = window.screen; if (screen) { const screenWidth = screen.availWidth; if ((screenWidth - windowWidth) > 20) { return true; } } return false; } /** * Gets the width of a card's image according to the shape and amount of cards per row. * @param {string} shape - Shape of the card. * @param {number} screenWidth - Width of the screen. * @param {boolean} isOrientationLandscape - Flag for the orientation of the screen. * @returns {number} Width of the image for a card. */ function getImageWidth(shape, screenWidth, isOrientationLandscape) { const imagesPerRow = getPostersPerRow(shape, screenWidth, isOrientationLandscape); return Math.round(screenWidth / imagesPerRow) * 2; } /** * Normalizes the options for a card. * @param {Object} items - A set of items. * @param {Object} options - Options for handling the items. */ function setCardData(items, options) { options.shape = options.shape || 'auto'; const primaryImageAspectRatio = imageLoader.getPrimaryImageAspectRatio(items); if (['auto', 'autohome', 'autooverflow', 'autoVertical'].includes(options.shape)) { const requestedShape = options.shape; options.shape = null; if (primaryImageAspectRatio) { if (primaryImageAspectRatio >= 3) { options.shape = 'banner'; options.coverImage = true; } else if (primaryImageAspectRatio >= 1.33) { options.shape = requestedShape === 'autooverflow' ? 'overflowBackdrop' : 'backdrop'; } else if (primaryImageAspectRatio > 0.71) { options.shape = requestedShape === 'autooverflow' ? 'overflowSquare' : 'square'; } else { options.shape = requestedShape === 'autooverflow' ? 'overflowPortrait' : 'portrait'; } } if (!options.shape) { options.shape = options.defaultShape || (requestedShape === 'autooverflow' ? 'overflowSquare' : 'square'); } } if (options.preferThumb === 'auto') { options.preferThumb = options.shape === 'backdrop' || options.shape === 'overflowBackdrop'; } options.uiAspect = getDesiredAspect(options.shape); options.primaryImageAspectRatio = primaryImageAspectRatio; if (!options.width && options.widths) { options.width = options.widths[options.shape]; } if (options.rows && typeof (options.rows) !== 'number') { options.rows = options.rows[options.shape]; } if (!options.width) { let screenWidth = dom.getWindowSize().innerWidth; const screenHeight = dom.getWindowSize().innerHeight; if (isResizable(screenWidth)) { const roundScreenTo = 100; screenWidth = Math.floor(screenWidth / roundScreenTo) * roundScreenTo; } options.width = getImageWidth(options.shape, screenWidth, screenWidth > (screenHeight * 1.3)); } } /** * Generates the internal HTML markup for cards. * @param {Object} items - Items for which to generate the markup. * @param {Object} options - Options for generating the markup. * @returns {string} The internal HTML markup of the cards. */ function buildCardsHtmlInternal(items, options) { let isVertical = false; if (options.shape === 'autoVertical') { isVertical = true; } setCardData(items, options); let html = ''; let itemsInRow = 0; let currentIndexValue; let hasOpenRow; let hasOpenSection; let sectionTitleTagName = options.sectionTitleTagName || 'div'; let apiClient; let lastServerId; for (const [i, item] of items.entries()) { let serverId = item.ServerId || options.serverId; if (serverId !== lastServerId) { lastServerId = serverId; apiClient = connectionManager.getApiClient(lastServerId); } if (options.indexBy) { let newIndexValue = ''; if (options.indexBy === 'PremiereDate') { if (item.PremiereDate) { try { newIndexValue = datetime.toLocaleDateString(datetime.parseISO8601Date(item.PremiereDate), { weekday: 'long', month: 'long', day: 'numeric' }); } catch (error) { console.error('error parsing timestamp for premiere date', error); } } } else if (options.indexBy === 'ProductionYear') { newIndexValue = item.ProductionYear; } else if (options.indexBy === 'CommunityRating') { newIndexValue = item.CommunityRating ? (Math.floor(item.CommunityRating) + (item.CommunityRating % 1 >= 0.5 ? 0.5 : 0)) + '+' : null; } if (newIndexValue !== currentIndexValue) { if (hasOpenRow) { html += '</div>'; hasOpenRow = false; itemsInRow = 0; } if (hasOpenSection) { html += '</div>'; if (isVertical) { html += '</div>'; } hasOpenSection = false; } if (isVertical) { html += '<div class="verticalSection">'; } else { html += '<div class="horizontalSection">'; } html += '<' + sectionTitleTagName + ' class="sectionTitle">' + newIndexValue + '</' + sectionTitleTagName + '>'; if (isVertical) { html += '<div class="itemsContainer vertical-wrap">'; } currentIndexValue = newIndexValue; hasOpenSection = true; } } if (options.rows && itemsInRow === 0) { if (hasOpenRow) { html += '</div>'; hasOpenRow = false; } html += '<div class="cardColumn">'; hasOpenRow = true; } html += buildCard(i, item, apiClient, options); itemsInRow++; if (options.rows && itemsInRow >= options.rows) { html += '</div>'; hasOpenRow = false; itemsInRow = 0; } } if (hasOpenRow) { html += '</div>'; } if (hasOpenSection) { html += '</div>'; if (isVertical) { html += '</div>'; } } return html; } /** * Computes the aspect ratio for a card given its shape. * @param {string} shape - Shape for which to get the aspect ratio. * @returns {null|number} Ratio of the shape. */ function getDesiredAspect(shape) { if (shape) { shape = shape.toLowerCase(); if (shape.indexOf('portrait') !== -1) { return (2 / 3); } if (shape.indexOf('backdrop') !== -1) { return (16 / 9); } if (shape.indexOf('square') !== -1) { return 1; } if (shape.indexOf('banner') !== -1) { return (1000 / 185); } } return null; } /** Get the URL of the card's image. * @param {Object} item - Item for which to generate a card. * @param {Object} apiClient - API client object. * @param {Object} options - Options of the card. * @param {string} shape - Shape of the desired image. * @returns {Object} Object representing the URL of the card's image. */ function getCardImageUrl(item, apiClient, options, shape) { item = item.ProgramInfo || item; const width = options.width; let height = null; const primaryImageAspectRatio = item.PrimaryImageAspectRatio; let forceName = false; let imgUrl = null; let imgTag = null; let coverImage = false; let uiAspect = null; let imgType = null; let itemId = null; if (options.preferThumb && item.ImageTags && item.ImageTags.Thumb) { imgType = 'Thumb'; imgTag = item.ImageTags.Thumb; } else if ((options.preferBanner || shape === 'banner') && item.ImageTags && item.ImageTags.Banner) { imgType = 'Banner'; imgTag = item.ImageTags.Banner; } else if (options.preferDisc && item.ImageTags && item.ImageTags.Disc) { imgType = 'Disc'; imgTag = item.ImageTags.Disc; } else if (options.preferLogo && item.ImageTags && item.ImageTags.Logo) { imgType = 'Logo'; imgTag = item.ImageTags.Logo; } else if (options.preferLogo && item.ParentLogoImageTag && item.ParentLogoItemId) { imgType = 'Logo'; imgTag = item.ParentLogoImageTag; itemId = item.ParentLogoItemId; } else if (options.preferThumb && item.SeriesThumbImageTag && options.inheritThumb !== false) { imgType = 'Thumb'; imgTag = item.SeriesThumbImageTag; itemId = item.SeriesId; } else if (options.preferThumb && item.ParentThumbItemId && options.inheritThumb !== false && item.MediaType !== 'Photo') { imgType = 'Thumb'; imgTag = item.ParentThumbImageTag; itemId = item.ParentThumbItemId; } else if (options.preferThumb && item.BackdropImageTags && item.BackdropImageTags.length) { imgType = 'Backdrop'; imgTag = item.BackdropImageTags[0]; forceName = true; } else if (options.preferThumb && item.ParentBackdropImageTags && item.ParentBackdropImageTags.length && options.inheritThumb !== false && item.Type === 'Episode') { imgType = 'Backdrop'; imgTag = item.ParentBackdropImageTags[0]; itemId = item.ParentBackdropItemId; } else if (item.ImageTags && item.ImageTags.Primary && (item.Type !== 'Episode' || item.ChildCount !== 0)) { imgType = 'Primary'; imgTag = item.ImageTags.Primary; height = width && primaryImageAspectRatio ? Math.round(width / primaryImageAspectRatio) : null; if (options.preferThumb && options.showTitle !== false) { forceName = true; } if (primaryImageAspectRatio) { uiAspect = getDesiredAspect(shape); if (uiAspect) { coverImage = (Math.abs(primaryImageAspectRatio - uiAspect) / uiAspect) <= 0.2; } } } else if (item.SeriesPrimaryImageTag) { imgType = 'Primary'; imgTag = item.SeriesPrimaryImageTag; itemId = item.SeriesId; } else if (item.PrimaryImageTag) { imgType = 'Primary'; imgTag = item.PrimaryImageTag; itemId = item.PrimaryImageItemId; height = width && primaryImageAspectRatio ? Math.round(width / primaryImageAspectRatio) : null; if (options.preferThumb && options.showTitle !== false) { forceName = true; } if (primaryImageAspectRatio) { uiAspect = getDesiredAspect(shape); if (uiAspect) { coverImage = (Math.abs(primaryImageAspectRatio - uiAspect) / uiAspect) <= 0.2; } } } else if (item.ParentPrimaryImageTag) { imgType = 'Primary'; imgTag = item.ParentPrimaryImageTag; itemId = item.ParentPrimaryImageItemId; } else if (item.AlbumId && item.AlbumPrimaryImageTag) { imgType = 'Primary'; imgTag = item.AlbumPrimaryImageTag; itemId = item.AlbumId; height = width && primaryImageAspectRatio ? Math.round(width / primaryImageAspectRatio) : null; if (primaryImageAspectRatio) { uiAspect = getDesiredAspect(shape); if (uiAspect) { coverImage = (Math.abs(primaryImageAspectRatio - uiAspect) / uiAspect) <= 0.2; } } } else if (item.Type === 'Season' && item.ImageTags && item.ImageTags.Thumb) { imgType = 'Thumb'; imgTag = item.ImageTags.Thumb; } else if (item.BackdropImageTags && item.BackdropImageTags.length) { imgType = 'Backdrop'; imgTag = item.BackdropImageTags[0]; } else if (item.ImageTags && item.ImageTags.Thumb) { imgType = 'Thumb'; imgTag = item.ImageTags.Thumb; } else if (item.SeriesThumbImageTag && options.inheritThumb !== false) { imgType = 'Thumb'; imgTag = item.SeriesThumbImageTag; itemId = item.SeriesId; } else if (item.ParentThumbItemId && options.inheritThumb !== false) { imgType = 'Thumb'; imgTag = item.ParentThumbImageTag; itemId = item.ParentThumbItemId; } else if (item.ParentBackdropImageTags && item.ParentBackdropImageTags.length && options.inheritThumb !== false) { imgType = 'Backdrop'; imgTag = item.ParentBackdropImageTags[0]; itemId = item.ParentBackdropItemId; } if (!itemId) { itemId = item.Id; } if (imgTag && imgType) { imgUrl = apiClient.getScaledImageUrl(itemId, { type: imgType, maxHeight: height, maxWidth: width, tag: imgTag }); } let blurHashes = options.imageBlurhashes || item.ImageBlurHashes || {}; return { imgUrl: imgUrl, blurhash: (blurHashes[imgType] || {})[imgTag], forceName: forceName, coverImage: coverImage }; } /** * Generates a random integer in a given range. * @param {number} min - Minimum of the range. * @param {number} max - Maximum of the range. * @returns {number} Randomly generated number. */ function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } /** * Generates an index used to select the default color of a card based on a string. * @param {string} str - String to use for generating the index. * @returns {number} Index of the color. */ function getDefaultColorIndex(str) { const numRandomColors = 5; if (str) { const charIndex = Math.floor(str.length / 2); const character = String(str.substr(charIndex, 1).charCodeAt()); let sum = 0; for (let i = 0; i < character.length; i++) { sum += parseInt(character.charAt(i)); } let index = String(sum).substr(-1); return (index % numRandomColors) + 1; } else { return getRandomInt(1, numRandomColors); } } /** * Generates the HTML markup for a card's text. * @param {Array} lines - Array containing the text lines. * @param {string} cssClass - Base CSS class to use for the lines. * @param {boolean} forceLines - Flag to force the rendering of all lines. * @param {boolean} isOuterFooter - Flag to mark the text lines as outer footer. * @param {string} cardLayout - DEPRECATED * @param {boolean} addRightMargin - Flag to add a right margin to the text. * @param {number} maxLines - Maximum number of lines to render. * @returns {string} HTML markup for the card's text. */ function getCardTextLines(lines, cssClass, forceLines, isOuterFooter, cardLayout, addRightMargin, maxLines) { let html = ''; let valid = 0; for (let i = 0; i < lines.length; i++) { let currentCssClass = cssClass; let text = lines[i]; if (valid > 0 && isOuterFooter) { currentCssClass += ' cardText-secondary'; } else if (valid === 0 && isOuterFooter) { currentCssClass += ' cardText-first'; } if (addRightMargin) { currentCssClass += ' cardText-rightmargin'; } if (text) { html += "<div class='" + currentCssClass + "'>"; html += text; html += '</div>'; valid++; if (maxLines && valid >= maxLines) { break; } } } if (forceLines) { let linesLength = maxLines || Math.min(lines.length, maxLines || lines.length); while (valid < linesLength) { html += "<div class='" + cssClass + "'>&nbsp;</div>"; valid++; } } return html; } /** * Determines if the item is live TV. * @param {Object} item - Item to use for the check. * @returns {boolean} Flag showing if the item is live TV. */ function isUsingLiveTvNaming(item) { return item.Type === 'Program' || item.Type === 'Timer' || item.Type === 'Recording'; } /** * Returns the air time text for the item based on the given times. * @param {object} item - Item used to generate the air time text. * @param {string} showAirDateTime - ISO8601 date for the start of the show. * @param {string} showAirEndTime - ISO8601 date for the end of the show. * @returns {string} The air time text for the item based on the given dates. */ function getAirTimeText(item, showAirDateTime, showAirEndTime) { let airTimeText = ''; if (item.StartDate) { try { let date = datetime.parseISO8601Date(item.StartDate); if (showAirDateTime) { airTimeText += datetime.toLocaleDateString(date, { weekday: 'short', month: 'short', day: 'numeric' }) + ' '; } airTimeText += datetime.getDisplayTime(date); if (item.EndDate && showAirEndTime) { date = datetime.parseISO8601Date(item.EndDate); airTimeText += ' - ' + datetime.getDisplayTime(date); } } catch (e) { console.error('error parsing date: ' + item.StartDate); } } return airTimeText; } /** * Generates the HTML markup for the card's footer text. * @param {Object} item - Item used to generate the footer text. * @param {Object} apiClient - API client instance. * @param {Object} options - Options used to generate the footer text. * @param {string} showTitle - Flag to show the title in the footer. * @param {boolean} forceName - Flag to force showing the name of the item. * @param {boolean} overlayText - Flag to show overlay text. * @param {Object} imgUrl - Object representing the card's image URL. * @param {string} footerClass - CSS classes of the footer element. * @param {string} progressHtml - HTML markup of the progress bar element. * @param {string} logoUrl - URL of the logo for the item. * @param {boolean} isOuterFooter - Flag to mark the text as outer footer. * @returns {string} HTML markup of the card's footer text element. */ function getCardFooterText(item, apiClient, options, showTitle, forceName, overlayText, imgUrl, footerClass, progressHtml, logoUrl, isOuterFooter) { let html = ''; if (logoUrl) { html += '<div class="lazy cardFooterLogo" data-src="' + logoUrl + '"></div>'; } const showOtherText = isOuterFooter ? !overlayText : overlayText; if (isOuterFooter && options.cardLayout && layoutManager.mobile) { if (options.cardFooterAside !== 'none') { html += '<button is="paper-icon-button-light" class="itemAction btnCardOptions cardText-secondary" data-action="menu"><span class="material-icons more_vert"></span></button>'; } } const cssClass = options.centerText ? 'cardText cardTextCentered' : 'cardText'; const serverId = item.ServerId || options.serverId; let lines = []; const parentTitleUnderneath = item.Type === 'MusicAlbum' || item.Type === 'Audio' || item.Type === 'MusicVideo'; let titleAdded; if (showOtherText) { if ((options.showParentTitle || options.showParentTitleOrTitle) && !parentTitleUnderneath) { if (isOuterFooter && item.Type === 'Episode' && item.SeriesName) { if (item.SeriesId) { lines.push(getTextActionButton({ Id: item.SeriesId, ServerId: serverId, Name: item.SeriesName, Type: 'Series', IsFolder: true })); } else { lines.push(item.SeriesName); } } else { if (isUsingLiveTvNaming(item)) { lines.push(item.Name); if (!item.EpisodeTitle) { titleAdded = true; } } else { const parentTitle = item.SeriesName || item.Series || item.Album || item.AlbumArtist || ''; if (parentTitle || showTitle) { lines.push(parentTitle); } } } } } let showMediaTitle = (showTitle && !titleAdded) || (options.showParentTitleOrTitle && !lines.length); if (!showMediaTitle && !titleAdded && (showTitle || forceName)) { showMediaTitle = true; } if (showMediaTitle) { const name = options.showTitle === 'auto' && !item.IsFolder && item.MediaType === 'Photo' ? '' : itemHelper.getDisplayName(item, { includeParentInfo: options.includeParentInfoInTitle }); lines.push(getTextActionButton({ Id: item.Id, ServerId: serverId, Name: name, Type: item.Type, CollectionType: item.CollectionType, IsFolder: item.IsFolder })); } if (showOtherText) { if (options.showParentTitle && parentTitleUnderneath) { if (isOuterFooter && item.AlbumArtists && item.AlbumArtists.length) { item.AlbumArtists[0].Type = 'MusicArtist'; item.AlbumArtists[0].IsFolder = true; lines.push(getTextActionButton(item.AlbumArtists[0], null, serverId)); } else { lines.push(isUsingLiveTvNaming(item) ? item.Name : (item.SeriesName || item.Series || item.Album || item.AlbumArtist || '')); } } if (options.showItemCounts) { lines.push(getItemCountsHtml(options, item)); } if (options.textLines) { const additionalLines = options.textLines(item); for (let i = 0; i < additionalLines.length; i++) { lines.push(additionalLines[i]); } } if (options.showSongCount) { let songLine = ''; if (item.SongCount) { songLine = item.SongCount === 1 ? globalize.translate('ValueOneSong') : globalize.translate('ValueSongCount', item.SongCount); } lines.push(songLine); } if (options.showPremiereDate) { if (item.PremiereDate) { try { lines.push(datetime.toLocaleDateString( datetime.parseISO8601Date(item.PremiereDate), { weekday: 'long', month: 'long', day: 'numeric' } )); } catch (err) { lines.push(''); } } else { lines.push(''); } } if (options.showYear || options.showSeriesYear) { if (item.Type === 'Series') { if (item.Status === 'Continuing') { lines.push(globalize.translate('SeriesYearToPresent', item.ProductionYear || '')); } else { if (item.EndDate && item.ProductionYear) { const endYear = datetime.parseISO8601Date(item.EndDate).getFullYear(); lines.push(item.ProductionYear + ((endYear === item.ProductionYear) ? '' : (' - ' + endYear))); } else { lines.push(item.ProductionYear || ''); } } } else { lines.push(item.ProductionYear || ''); } } if (options.showRuntime) { if (item.RunTimeTicks) { lines.push(datetime.getDisplayRunningTime(item.RunTimeTicks)); } else { lines.push(''); } } if (options.showAirTime) { lines.push(getAirTimeText(item, options.showAirDateTime, options.showAirEndTime) || ''); } if (options.showChannelName) { if (item.ChannelId) { lines.push(getTextActionButton({ Id: item.ChannelId, ServerId: serverId, Name: item.ChannelName, Type: 'TvChannel', MediaType: item.MediaType, IsFolder: false }, item.ChannelName)); } else { lines.push(item.ChannelName || '&nbsp;'); } } if (options.showCurrentProgram && item.Type === 'TvChannel') { if (item.CurrentProgram) { lines.push(item.CurrentProgram.Name); } else { lines.push(''); } } if (options.showCurrentProgramTime && item.Type === 'TvChannel') { if (item.CurrentProgram) { lines.push(getAirTimeText(item.CurrentProgram, false, true) || ''); } else { lines.push(''); } } if (options.showSeriesTimerTime) { if (item.RecordAnyTime) { lines.push(globalize.translate('Anytime')); } else { lines.push(datetime.getDisplayTime(item.StartDate)); } } if (options.showSeriesTimerChannel) { if (item.RecordAnyChannel) { lines.push(globalize.translate('AllChannels')); } else { lines.push(item.ChannelName || globalize.translate('OneChannel')); } } if (options.showPersonRoleOrType) { if (item.Role) { lines.push(globalize.translate('PersonRole', item.Role)); } } } if ((showTitle || !imgUrl) && forceName && overlayText && lines.length === 1) { lines = []; } const addRightTextMargin = isOuterFooter && options.cardLayout && !options.centerText && options.cardFooterAside !== 'none' && layoutManager.mobile; html += getCardTextLines(lines, cssClass, !options.overlayText, isOuterFooter, options.cardLayout, addRightTextMargin, options.lines); if (progressHtml) { html += progressHtml; } if (html) { if (!isOuterFooter || logoUrl || options.cardLayout) { html = '<div class="' + footerClass + '">' + html; //cardFooter html += '</div>'; } } return html; } /** * Generates the HTML markup for the action button. * @param {Object} item - Item used to generate the action button. * @param {string} text - Text of the action button. * @param {string} serverId - ID of the server. * @returns {string} HTML markup of the action button. */ function getTextActionButton(item, text, serverId) { if (!text) { text = itemHelper.getDisplayName(item); } if (layoutManager.tv) { return text; } let html = '<button ' + itemShortcuts.getShortcutAttributesHtml(item, serverId) + ' type="button" class="itemAction textActionButton" title="' + text + '" data-action="link">'; html += text; html += '</button>'; return html; } /** * Generates HTML markup for the item count indicator. * @param {Object} options - Options used to generate the item count. * @param {Object} item - Item used to generate the item count. * @returns {string} HTML markup for the item count indicator. */ function getItemCountsHtml(options, item) { let counts = []; let childText; if (item.Type === 'Playlist') { childText = ''; if (item.RunTimeTicks) { let minutes = item.RunTimeTicks / 600000000; minutes = minutes || 1; childText += globalize.translate('ValueMinutes', Math.round(minutes)); } else { childText += globalize.translate('ValueMinutes', 0); } counts.push(childText); } else if (item.Type === 'Genre' || item.Type === 'Studio') { if (item.MovieCount) { childText = item.MovieCount === 1 ? globalize.translate('ValueOneMovie') : globalize.translate('ValueMovieCount', item.MovieCount); counts.push(childText); } if (item.SeriesCount) { childText = item.SeriesCount === 1 ? globalize.translate('ValueOneSeries') : globalize.translate('ValueSeriesCount', item.SeriesCount); counts.push(childText); } if (item.EpisodeCount) { childText = item.EpisodeCount === 1 ? globalize.translate('ValueOneEpisode') : globalize.translate('ValueEpisodeCount', item.EpisodeCount); counts.push(childText); } } else if (item.Type === 'MusicGenre' || options.context === 'MusicArtist') { if (item.AlbumCount) { childText = item.AlbumCount === 1 ? globalize.translate('ValueOneAlbum') : globalize.translate('ValueAlbumCount', item.AlbumCount); counts.push(childText); } if (item.SongCount) { childText = item.SongCount === 1 ? globalize.translate('ValueOneSong') : globalize.translate('ValueSongCount', item.SongCount); counts.push(childText); } if (item.MusicVideoCount) { childText = item.MusicVideoCount === 1 ? globalize.translate('ValueOneMusicVideo') : globalize.translate('ValueMusicVideoCount', item.MusicVideoCount); counts.push(childText); } } else if (item.Type === 'Series') { childText = item.RecursiveItemCount === 1 ? globalize.translate('ValueOneEpisode') : globalize.translate('ValueEpisodeCount', item.RecursiveItemCount); counts.push(childText); } return counts.join(', '); } let refreshIndicatorLoaded; /** * Imports the refresh indicator element. */ function requireRefreshIndicator() { if (!refreshIndicatorLoaded) { refreshIndicatorLoaded = true; require(['emby-itemrefreshindicator']); } } /** * Returns the default background class for a card based on a string. * @param {string} str - Text used to generate the background class. * @returns {string} CSS classes for default card backgrounds. */ export function getDefaultBackgroundClass(str) { return 'defaultCardBackground defaultCardBackground' + getDefaultColorIndex(str); } /** * Builds the HTML markup for an individual card. * @param {number} index - Index of the card * @param {object} item - Item used to generate the card. * @param {object} apiClient - API client instance. * @param {object} options - Options used to generate the card. * @returns {string} HTML markup for the generated card. */ function buildCard(index, item, apiClient, options) { let action = options.action || 'link'; if (action === 'play' && item.IsFolder) { // If this hard-coding is ever removed make sure to test nested photo albums action = 'link'; } else if (item.MediaType === 'Photo') { action = 'play'; } let shape = options.shape; if (shape === 'mixed') { shape = null; const primaryImageAspectRatio = item.PrimaryImageAspectRatio; if (primaryImageAspectRatio) { if (primaryImageAspectRatio >= 1.33) { shape = 'mixedBackdrop'; } else if (primaryImageAspectRatio > 0.71) { shape = 'mixedSquare'; } else { shape = 'mixedPortrait'; } } shape = shape || 'mixedSquare'; } // TODO move card creation code to Card component let className = 'card'; if (shape) { className += ' ' + shape + 'Card'; } if (options.cardCssClass) { className += ' ' + options.cardCssClass; } if (options.cardClass) { className += ' ' + options.cardClass; } if (layoutManager.desktop) { className += ' card-hoverable'; } if (layoutManager.tv) { className += ' show-focus'; if (enableFocusTransform) { className += ' show-animation'; } } const imgInfo = getCardImageUrl(item, apiClient, options, shape); const imgUrl = imgInfo.imgUrl; const blurhash = imgInfo.blurhash; const forceName = imgInfo.forceName; const showTitle = options.showTitle === 'auto' ? true : (options.showTitle || item.Type === 'PhotoAlbum' || item.Type === 'Folder'); const overlayText = options.overlayText; let cardImageContainerClass = 'cardImageContainer'; const coveredImage = options.coverImage || imgInfo.coverImage; if (coveredImage) { cardImageContainerClass += ' coveredImage'; if (item.MediaType === 'Photo' || item.Type === 'PhotoAlbum' || item.Type === 'Folder' || item.ProgramInfo || item.Type === 'Program' || item.Type === 'Recording') { cardImageContainerClass += ' coveredImage-noScale'; } } if (!imgUrl) { cardImageContainerClass += ' ' + getDefaultBackgroundClass(item.Name); } let cardBoxClass = options.cardLayout ? 'cardBox visualCardBox' : 'cardBox'; let footerCssClass; let progressHtml = indicators.getProgressBarHtml(item); let innerCardFooter = ''; let footerOverlayed = false; let logoUrl; const logoHeight = 40; if (options.showChannelLogo && item.ChannelPrimaryImageTag) { logoUrl = apiClient.getScaledImageUrl(item.ChannelId, { type: 'Primary', height: logoHeight, tag: item.ChannelPrimaryImageTag }); } else if (options.showLogo && item.ParentLogoImageTag) { logoUrl = apiClient.getScaledImageUrl(item.ParentLogoItemId, { type: 'Logo', height: logoHeight, tag: item.ParentLogoImageTag }); } if (overlayText) { logoUrl = null; footerCssClass = progressHtml ? 'innerCardFooter fullInnerCardFooter' : 'innerCardFooter'; innerCardFooter += getCardFooterText(item, apiClient, options, showTitle, forceName, overlayText, imgUrl, footerCssClass, progressHtml, logoUrl, false); footerOverlayed = true; } else if (progressHtml) { innerCardFooter += '<div class="innerCardFooter fullInnerCardFooter innerCardFooterClear">'; innerCardFooter += progressHtml; innerCardFooter += '</div>'; progressHtml = ''; } const mediaSourceCount = item.MediaSourceCount || 1; if (mediaSourceCount > 1 && options.disableIndicators !== true) { innerCardFooter += '<div class="mediaSourceIndicator">' + mediaSourceCount + '</div>'; } let outerCardFooter = ''; if (!overlayText && !footerOverlayed) { footerCssClass = options.cardLayout ? 'cardFooter' : 'cardFooter cardFooter-transparent'; if (logoUrl) { footerCssClass += ' cardFooter-withlogo'; } if (!options.cardLayout) { logoUrl = null; } outerCardFooter = getCardFooterText(item, apiClient, options, showTitle, forceName, overlayText, imgUrl, footerCssClass, progressHtml, logoUrl, true); } if (outerCardFooter && !options.cardLayout) { cardBoxClass += ' cardBox-bottompadded'; } let overlayButtons = ''; if (layoutManager.mobile) { let overlayPlayButton = options.overlayPlayButton; if (overlayPlayButton == null && !options.overlayMoreButton && !options.overlayInfoButton && !options.cardLayout) { overlayPlayButton = item.MediaType === 'Video'; } const btnCssClass = 'cardOverlayButton cardOverlayButton-br itemAction'; if (options.centerPlayButton) { overlayButtons += '<button is="paper-icon-button-light" class="' + btnCssClass + ' cardOverlayButton-centered" data-action="play"><span class="material-icons cardOverlayButtonIcon play_arrow"></span></button>'; } if (overlayPlayButton && !item.IsPlaceHolder && (item.LocationType !== 'Virtual' || !item.MediaType || item.Type === 'Program') && item.Type !== 'Person') { overlayButtons += '<button is="paper-icon-button-light" class="' + btnCssClass + '" data-action="play"><span class="material-icons cardOverlayButtonIcon play_arrow"></span></button>'; } if (options.overlayMoreButton) { overlayButtons += '<button is="paper-icon-button-light" class="' + btnCssClass + '" data-action="menu"><span class="material-icons cardOverlayButtonIcon more_vert"></span></button>'; } } if (options.showChildCountIndicator && item.ChildCount) { className += ' groupedCard'; } // cardBox can be it's own separate element if an outer footer is ever needed let cardImageContainerOpen; let cardImageContainerClose = ''; let cardBoxClose = ''; let cardScalableClose = ''; let cardContentClass = 'cardContent'; let blurhashAttrib = ''; if (blurhash && blurhash.length > 0) { blurhashAttrib = 'data-blurhash="' + blurhash + '"'; } if (layoutManager.tv) { // Don't use the IMG tag with safari because it puts a white border around it cardImageContainerOpen = imgUrl ? ('<div class="' + cardImageContainerClass + ' ' + cardContentClass + ' lazy" data-src="' + imgUrl + '" ' + blurhashAttrib + '>') : ('<div class="' + cardImageContainerClass + ' ' + cardContentClass + '">'); cardImageContainerClose = '</div>'; } else { // Don't use the IMG tag with safari because it puts a white border around it cardImageContainerOpen = imgUrl ? ('<button data-action="' + action + '" class="' + cardImageContainerClass + ' ' + cardContentClass + ' itemAction lazy" data-src="' + imgUrl + '" ' + blurhashAttrib + '>') : ('<button data-action="' + action + '" class="' + cardImageContainerClass + ' ' + cardContentClass + ' itemAction">'); cardImageContainerClose = '</button>'; } let cardScalableClass = 'cardScalable'; cardImageContainerOpen = '<div class="' + cardBoxClass + '"><div class="' + cardScalableClass + '"><div class="cardPadder cardPadder-' + shape + '"></div>' + cardImageContainerOpen; cardBoxClose = '</div>'; cardScalableClose = '</div>'; if (options.disableIndicators !== true) { let indicatorsHtml = ''; if (options.missingIndicator !== false) { indicatorsHtml += indicators.getMissingIndicator(item); } indicatorsHtml += indicators.getSyncIndicator(item); indicatorsHtml += indicators.getTimerIndicator(item); indicatorsHtml += indicators.getTypeIndicator(item); if (options.showGroupCount) { indicatorsHtml += indicators.getChildCountIndicatorHtml(item, { minCount: 1 }); } else { indicatorsHtml += indicators.getPlayedIndicatorHtml(item); } if (item.Type === 'CollectionFolder' || item.CollectionType) { const refreshClass = item.RefreshProgress ? '' : ' class="hide"'; indicatorsHtml += '<div is="emby-itemrefreshindicator"' + refreshClass + ' data-progress="' + (item.RefreshProgress || 0) + '" data-status="' + item.RefreshStatus + '"></div>'; requireRefreshIndicator(); } if (indicatorsHtml) { cardImageContainerOpen += '<div class="cardIndicators">' + indicatorsHtml + '</div>'; } } if (!imgUrl) { cardImageContainerOpen += getDefaultText(item, options); } const tagName = (layoutManager.tv) && !overlayButtons ? 'button' : 'div'; const nameWithPrefix = (item.SortName || item.Name || ''); let prefix = nameWithPrefix.substring(0, Math.min(3, nameWithPrefix.length)); if (prefix) { prefix = prefix.toUpperCase(); } let timerAttributes = ''; if (item.TimerId) { timerAttributes += ' data-timerid="' + item.TimerId + '"'; } if (item.SeriesTimerId) { timerAttributes += ' data-seriestimerid="' + item.SeriesTimerId + '"'; } let actionAttribute; if (tagName === 'button') { className += ' itemAction'; actionAttribute = ' data-action="' + action + '"'; } else { actionAttribute = ''; } if (item.Type !== 'MusicAlbum' && item.Type !== 'MusicArtist' && item.Type !== 'Audio') { className += ' card-withuserdata'; } const positionTicksData = item.UserData && item.UserData.PlaybackPositionTicks ? (' data-positionticks="' + item.UserData.PlaybackPositionTicks + '"') : ''; const collectionIdData = options.collectionId ? (' data-collectionid="' + options.collectionId + '"') : ''; const playlistIdData = options.playlistId ? (' data-playlistid="' + options.playlistId + '"') : ''; const mediaTypeData = item.MediaType ? (' data-mediatype="' + item.MediaType + '"') : ''; const collectionTypeData = item.CollectionType ? (' data-collectiontype="' + item.CollectionType + '"') : ''; const channelIdData = item.ChannelId ? (' data-channelid="' + item.ChannelId + '"') : ''; const contextData = options.context ? (' data-context="' + options.context + '"') : ''; const parentIdData = options.parentId ? (' data-parentid="' + options.parentId + '"') : ''; let additionalCardContent = ''; if (layoutManager.desktop) { additionalCardContent += getHoverMenuHtml(item, action, options); } return '<' + tagName + ' data-index="' + index + '"' + timerAttributes + actionAttribute + ' data-isfolder="' + (item.IsFolder || false) + '" data-serverid="' + (item.ServerId || options.serverId) + '" data-id="' + (item.Id || item.ItemId) + '" data-type="' + item.Type + '"' + mediaTypeData + collectionTypeData + channelIdData + positionTicksData + collectionIdData + playlistIdData + contextData + parentIdData + ' data-prefix="' + prefix + '" class="' + className + '">' + cardImageContainerOpen + innerCardFooter + cardImageContainerClose + overlayButtons + additionalCardContent + cardScalableClose + outerCardFooter + cardBoxClose + '</' + tagName + '>'; } /** * Generates HTML markup for the card overlay. * @param {object} item - Item used to generate the card overlay. * @param {string} action - Action assigned to the overlay. * @param {Array} options - Card builder options. * @returns {string} HTML markup of the card overlay. */ function getHoverMenuHtml(item, action, options) { let html = ''; html += '<div class="cardOverlayContainer itemAction" data-action="' + action + '">'; const btnCssClass = 'cardOverlayButton cardOverlayButton-hover itemAction paper-icon-button-light'; if (playbackManager.canPlay(item)) { html += '<button is="paper-icon-button-light" class="' + btnCssClass + ' cardOverlayFab-primary" data-action="resume"><span class="material-icons cardOverlayButtonIcon cardOverlayButtonIcon-hover play_arrow"></span></button>'; } html += '<div class="cardOverlayButton-br flex">'; const userData = item.UserData || {}; if (itemHelper.canMarkPlayed(item) && !options.disableHoverMenu) { require(['emby-playstatebutton']); html += '<button is="emby-playstatebutton" type="button" data-action="none" class="' + btnCssClass + '" data-id="' + item.Id + '" data-serverid="' + item.ServerId + '" data-itemtype="' + item.Type + '" data-played="' + (userData.Played) + '"><span class="material-icons cardOverlayButtonIcon cardOverlayButtonIcon-hover check"></span></button>'; } if (itemHelper.canRate(item) && !options.disableHoverMenu) { const likes = userData.Likes == null ? '' : userData.Likes; require(['emby-ratingbutton']); html += '<button is="emby-ratingbutton" type="button" data-action="none" class="' + btnCssClass + '" data-id="' + item.Id + '" data-serverid="' + item.ServerId + '" data-itemtype="' + item.Type + '" data-likes="' + likes + '" data-isfavorite="' + (userData.IsFavorite) + '"><span class="material-icons cardOverlayButtonIcon cardOverlayButtonIcon-hover favorite"></span></button>'; } if (!options.disableHoverMenu) { html += '<button is="paper-icon-button-light" class="' + btnCssClass + '" data-action="menu"><span class="material-icons cardOverlayButtonIcon cardOverlayButtonIcon-hover more_vert"></span></button>'; } html += '</div>'; html += '</div>'; return html; } /** * Generates the text or icon used for default card backgrounds. * @param {object} item - Item used to generate the card overlay. * @param {object} options - Options used to generate the card overlay. * @returns {string} HTML markup of the card overlay. */ export function getDefaultText(item, options) { if (item.CollectionType) { return '<span class="cardImageIcon material-icons ' + imageHelper.getLibraryIcon(item.CollectionType) + '"></span>'; } switch (item.Type) { case 'MusicAlbum': return '<span class="cardImageIcon material-icons album"></span>'; case 'MusicArtist': case 'Person': return '<span class="cardImageIcon material-icons person"></span>'; case 'Audio': return '<span class="cardImageIcon material-icons audiotrack"></span>'; case 'Movie': return '<span class="cardImageIcon material-icons movie"></span>'; case 'Series': return '<span class="cardImageIcon material-icons tv"></span>'; case 'Book': return '<span class="cardImageIcon material-icons book"></span>'; case 'Folder': return '<span class="cardImageIcon material-icons folder"></span>'; } if (options && options.defaultCardImageIcon) { return '<span class="cardImageIcon material-icons ' + options.defaultCardImageIcon + '"></span>'; } const defaultName = isUsingLiveTvNaming(item) ? item.Name : itemHelper.getDisplayName(item); return '<div class="cardText cardDefaultText">' + defaultName + '</div>'; } /** * Builds a set of cards and inserts them into the page. * @param {Array} items - Array of items used to build the cards. * @param {options} options - Options of the cards to build. */ export function buildCards(items, options) { // Abort if the container has been disposed if (!document.body.contains(options.itemsContainer)) { return; } if (options.parentContainer) { if (items.length) { options.parentContainer.classList.remove('hide'); } else { options.parentContainer.classList.add('hide'); return; } } const html = buildCardsHtmlInternal(items, options); if (html) { if (options.itemsContainer.cardBuilderHtml !== html) { options.itemsContainer.innerHTML = html; if (items.length < 50) { options.itemsContainer.cardBuilderHtml = html; } else { options.itemsContainer.cardBuilderHtml = null; } } imageLoader.lazyChildren(options.itemsContainer); } else { options.itemsContainer.innerHTML = html; options.itemsContainer.cardBuilderHtml = null; } if (options.autoFocus) { focusManager.autoFocus(options.itemsContainer, true); } } /** * Ensures the indicators for a card exist and creates them if they don't exist. * @param {HTMLDivElement} card - DOM element of the card. * @param {HTMLDivElement} indicatorsElem - DOM element of the indicators. * @returns {HTMLDivElement} - DOM element of the indicators. */ function ensureIndicators(card, indicatorsElem) { if (indicatorsElem) { return indicatorsElem; } indicatorsElem = card.querySelector('.cardIndicators'); if (!indicatorsElem) { const cardImageContainer = card.querySelector('.cardImageContainer'); indicatorsElem = document.createElement('div'); indicatorsElem.classList.add('cardIndicators'); cardImageContainer.appendChild(indicatorsElem); } return indicatorsElem; } /** * Adds user data to the card such as progress indicators and played status. * @param {HTMLDivElement} card - DOM element of the card. * @param {Object} userData - User data to apply to the card. */ function updateUserData(card, userData) { const type = card.getAttribute('data-type'); const enableCountIndicator = type === 'Series' || type === 'BoxSet' || type === 'Season'; let indicatorsElem = null; let playedIndicator = null; let countIndicator = null; let itemProgressBar = null; if (userData.Played) { playedIndicator = card.querySelector('.playedIndicator'); if (!playedIndicator) { playedIndicator = document.createElement('div'); playedIndicator.classList.add('playedIndicator'); playedIndicator.classList.add('indicator'); indicatorsElem = ensureIndicators(card, indicatorsElem); indicatorsElem.appendChild(playedIndicator); } playedIndicator.innerHTML = '<span class="material-icons indicatorIcon check"></span>'; } else { playedIndicator = card.querySelector('.playedIndicator'); if (playedIndicator) { playedIndicator.parentNode.removeChild(playedIndicator); } } if (userData.UnplayedItemCount) { countIndicator = card.querySelector('.countIndicator'); if (!countIndicator) { countIndicator = document.createElement('div'); countIndicator.classList.add('countIndicator'); indicatorsElem = ensureIndicators(card, indicatorsElem); indicatorsElem.appendChild(countIndicator); } countIndicator.innerHTML = userData.UnplayedItemCount; } else if (enableCountIndicator) { countIndicator = card.querySelector('.countIndicator'); if (countIndicator) { countIndicator.parentNode.removeChild(countIndicator); } } const progressHtml = indicators.getProgressBarHtml({ Type: type, UserData: userData, MediaType: 'Video' }); if (progressHtml) { itemProgressBar = card.querySelector('.itemProgressBar'); if (!itemProgressBar) { itemProgressBar = document.createElement('div'); itemProgressBar.classList.add('itemProgressBar'); let innerCardFooter = card.querySelector('.innerCardFooter'); if (!innerCardFooter) { innerCardFooter = document.createElement('div'); innerCardFooter.classList.add('innerCardFooter'); const cardImageContainer = card.querySelector('.cardImageContainer'); cardImageContainer.appendChild(innerCardFooter); } innerCardFooter.appendChild(itemProgressBar); } itemProgressBar.innerHTML = progressHtml; } else { itemProgressBar = card.querySelector('.itemProgressBar'); if (itemProgressBar) { itemProgressBar.parentNode.removeChild(itemProgressBar); } } } /** * Handles when user data has changed. * @param {Object} userData - User data to apply to the card. * @param {HTMLElement} scope - DOM element to use as a scope when selecting cards. */ export function onUserDataChanged(userData, scope) { const cards = (scope || document.body).querySelectorAll('.card-withuserdata[data-id="' + userData.ItemId + '"]'); for (let i = 0, length = cards.length; i < length; i++) { updateUserData(cards[i], userData); } } /** * Handles when a timer has been created. * @param {string} programId - ID of the program. * @param {string} newTimerId - ID of the new timer. * @param {HTMLElement} itemsContainer - DOM element of the itemsContainer. */ export function onTimerCreated(programId, newTimerId, itemsContainer) { const cells = itemsContainer.querySelectorAll('.card[data-id="' + programId + '"]'); for (let i = 0, length = cells.length; i < length; i++) { let cell = cells[i]; const icon = cell.querySelector('.timerIndicator'); if (!icon) { const indicatorsElem = ensureIndicators(cell); indicatorsElem.insertAdjacentHTML('beforeend', '<span class="material-icons timerIndicator indicatorIcon fiber_manual_record"></span>'); } cell.setAttribute('data-timerid', newTimerId); } } /** * Handles when a timer has been cancelled. * @param {string} timerId - ID of the cancelled timer. * @param {HTMLElement} itemsContainer - DOM element of the itemsContainer. */ export function onTimerCancelled(timerId, itemsContainer) { const cells = itemsContainer.querySelectorAll('.card[data-timerid="' + timerId + '"]'); for (let i = 0; i < cells.length; i++) { let cell = cells[i]; let icon = cell.querySelector('.timerIndicator'); if (icon) { icon.parentNode.removeChild(icon); } cell.removeAttribute('data-timerid'); } } /** * Handles when a series timer has been cancelled. * @param {string} cancelledTimerId - ID of the cancelled timer. * @param {HTMLElement} itemsContainer - DOM element of the itemsContainer. */ export function onSeriesTimerCancelled(cancelledTimerId, itemsContainer) { const cells = itemsContainer.querySelectorAll('.card[data-seriestimerid="' + cancelledTimerId + '"]'); for (let i = 0; i < cells.length; i++) { let cell = cells[i]; let icon = cell.querySelector('.timerIndicator'); if (icon) { icon.parentNode.removeChild(icon); } cell.removeAttribute('data-seriestimerid'); } } /* eslint-enable indent */ export default { getCardsHtml: getCardsHtml, getDefaultBackgroundClass: getDefaultBackgroundClass, getDefaultText: getDefaultText, buildCards: buildCards, onUserDataChanged: onUserDataChanged, onTimerCreated: onTimerCreated, onTimerCancelled: onTimerCancelled, onSeriesTimerCancelled: onSeriesTimerCancelled };
1
16,396
Actually it could also be a video playlist. But music is used more often.
jellyfin-jellyfin-web
js
@@ -36,6 +36,11 @@ function writeCommand(server, type, opsField, ns, ops, options, callback) { writeCommand.bypassDocumentValidation = options.bypassDocumentValidation; } + if (writeConcern.w === 0) { + // don't include session for unacknowledged writes + delete options.session; + } + const commandOptions = Object.assign( { checkKeys: type === 'insert',
1
'use strict'; const MongoError = require('../error').MongoError; const collectionNamespace = require('./shared').collectionNamespace; const command = require('./command'); function writeCommand(server, type, opsField, ns, ops, options, callback) { if (ops.length === 0) throw new MongoError(`${type} must contain at least one document`); if (typeof options === 'function') { callback = options; options = {}; } options = options || {}; const ordered = typeof options.ordered === 'boolean' ? options.ordered : true; const writeConcern = options.writeConcern; const writeCommand = {}; writeCommand[type] = collectionNamespace(ns); writeCommand[opsField] = ops; writeCommand.ordered = ordered; if (writeConcern && Object.keys(writeConcern).length > 0) { writeCommand.writeConcern = writeConcern; } if (options.collation) { for (let i = 0; i < writeCommand[opsField].length; i++) { if (!writeCommand[opsField][i].collation) { writeCommand[opsField][i].collation = options.collation; } } } if (options.bypassDocumentValidation === true) { writeCommand.bypassDocumentValidation = options.bypassDocumentValidation; } const commandOptions = Object.assign( { checkKeys: type === 'insert', numberToReturn: 1 }, options ); command(server, ns, writeCommand, commandOptions, callback); } module.exports = writeCommand;
1
18,051
From the ticket: > I understand why a session ID would be silently omitted for implicit sessions, but what is the reasoning behind omitting it for explicit sessions instead of raising a logic error to the user? So what this change is doing is "silently omitting" the session if its an unacknowledged write. I think we want to actually return an error in this case.
mongodb-node-mongodb-native
js
@@ -85,6 +85,17 @@ namespace pwiz.Skyline.Model.Databinding.Entities [Format(NullValue = TextUtil.EXCEL_NA)] public int? PointsAcrossPeak { get { return ChromInfo.PointsAcrossPeak; } } + [Format(Formats.RETENTION_TIME, NullValue = TextUtil.EXCEL_NA)] + public double? AverageCycleTime + { + get + { + return StartTime.HasValue && EndTime.HasValue && PointsAcrossPeak.HasValue + ? (EndTime.Value - StartTime.Value) * 60 / PointsAcrossPeak.Value + : (double?) null; + } + } + public bool Coeluting { get { return !ChromInfo.IsForcedIntegration; } } [Format(Formats.RETENTION_TIME, NullValue = TextUtil.EXCEL_NA)]
1
/* * Original author: Nicholas Shulman <nicksh .at. u.washington.edu>, * MacCoss Lab, Department of Genome Sciences, UW * * Copyright 2012 University of Washington - Seattle, WA * * 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. */ using System; using System.ComponentModel; using pwiz.Common.DataBinding.Attributes; using pwiz.Skyline.Model.DocSettings; using pwiz.Skyline.Model.ElementLocators; using pwiz.Skyline.Model.Hibernate; using pwiz.Skyline.Model.Results; using pwiz.Skyline.Util.Extensions; namespace pwiz.Skyline.Model.Databinding.Entities { [InvariantDisplayName(nameof(TransitionResult))] [AnnotationTarget(AnnotationDef.AnnotationTarget.transition_result)] public class TransitionResult : Result { private readonly CachedValue<TransitionChromInfo> _chromInfo; private readonly CachedValue<Chromatogram> _chromatogram; public TransitionResult(Transition transition, ResultFile resultFile) : base(transition, resultFile) { _chromInfo = CachedValue.Create(DataSchema, () => GetResultFile().FindChromInfo(transition.DocNode.Results)); _chromatogram = CachedValue.Create(DataSchema, () => new Chromatogram(new ChromatogramGroup(PrecursorResult), Transition)); } [Browsable(false)] public TransitionChromInfo ChromInfo { get { return _chromInfo.Value; } } public void ChangeChromInfo(EditDescription editDescription, Func<TransitionChromInfo, TransitionChromInfo> newChromInfo) { Transition.ChangeDocNode(editDescription, docNode=>docNode.ChangeResults(GetResultFile().ChangeChromInfo(docNode.Results, newChromInfo))); } [HideWhen(AncestorOfType = typeof(Transition))] public Transition Transition { get { return (Transition)SkylineDocNode; } } [Format(Formats.RETENTION_TIME, NullValue = TextUtil.EXCEL_NA)] public double? RetentionTime { get { return ChromInfo.IsEmpty ? (double?) null : ChromInfo.RetentionTime; } } [Format(Formats.RETENTION_TIME, NullValue = TextUtil.EXCEL_NA)] public double? Fwhm { get { return ChromInfo.IsEmpty ? (double?) null : ChromInfo.Fwhm; } } public bool FwhmDegenerate { get { return ChromInfo.IsFwhmDegenerate; } } [Format(Formats.RETENTION_TIME, NullValue = TextUtil.EXCEL_NA)] public double? StartTime { get { return ChromInfo.IsEmpty ? (double?)null : ChromInfo.StartRetentionTime; } } [Format(Formats.RETENTION_TIME, NullValue = TextUtil.EXCEL_NA)] public double? EndTime { get { return ChromInfo.IsEmpty ? (double?) null : ChromInfo.EndRetentionTime; } } [Format(Formats.PEAK_AREA, NullValue = TextUtil.EXCEL_NA)] public double? Area { get { return ChromInfo.IsEmpty ? (double?) null : ChromInfo.Area; } } [Format(Formats.PEAK_AREA, NullValue = TextUtil.EXCEL_NA)] public double? Background { get { return ChromInfo.IsEmpty ? (double?)null : ChromInfo.BackgroundArea; } } [Format(Formats.STANDARD_RATIO, NullValue = TextUtil.EXCEL_NA)] public double? AreaRatio { get { return ChromInfo.Ratio; } } [Format(Formats.PEAK_AREA_NORMALIZED, NullValue = TextUtil.EXCEL_NA)] public double? AreaNormalized { get { return Area / GetResultFile().GetTotalArea(Transition.Precursor.IsotopeLabelType); } } [Format(Formats.PEAK_AREA, NullValue = TextUtil.EXCEL_NA)] public double? Height { get { return ChromInfo.IsEmpty ? (double?) null : ChromInfo.Height; } } [Format(Formats.MASS_ERROR, NullValue = TextUtil.EXCEL_NA)] public double? MassErrorPPM { get { return ChromInfo.MassError; } } public bool? Truncated { get { return ChromInfo.IsTruncated; } } [Format(NullValue = TextUtil.EXCEL_NA)] public int? PeakRank { get { return ChromInfo.IsEmpty ? (int?)null : ChromInfo.Rank; } } [Format(NullValue = TextUtil.EXCEL_NA)] public int? PeakRankByLevel { get { return ChromInfo.IsEmpty ? (int?)null : ChromInfo.RankByLevel; } } public UserSet UserSetPeak { get { return ChromInfo.UserSet; } } [Format(NullValue = TextUtil.EXCEL_NA)] public int OptStep { get { return ChromInfo.OptimizationStep; } } [Format(NullValue = TextUtil.EXCEL_NA)] public int? PointsAcrossPeak { get { return ChromInfo.PointsAcrossPeak; } } public bool Coeluting { get { return !ChromInfo.IsForcedIntegration; } } [Format(Formats.RETENTION_TIME, NullValue = TextUtil.EXCEL_NA)] public double? IonMobilityFragment { get { return IonMobilityFilter.IsNullOrEmpty(ChromInfo.IonMobility) ? null : ChromInfo.IonMobility.IonMobilityAndCCS.GetHighEnergyIonMobility(); } } public Chromatogram Chromatogram { get { return _chromatogram.Value; } } [InvariantDisplayName("TransitionReplicateNote")] [Importable] public string Note { get { return ChromInfo.Annotations.Note; } set { ChangeChromInfo(EditColumnDescription(nameof(Note), value), chromInfo=>chromInfo.ChangeAnnotations(chromInfo.Annotations.ChangeNote(value))); } } public override void SetAnnotation(AnnotationDef annotationDef, object value) { ChangeChromInfo(EditDescription.SetAnnotation(annotationDef, value), chromInfo=>chromInfo.ChangeAnnotations(chromInfo.Annotations.ChangeAnnotation(annotationDef, value))); } public override object GetAnnotation(AnnotationDef annotationDef) { return DataSchema.AnnotationCalculator.GetAnnotation(annotationDef, this, ChromInfo.Annotations); } [HideWhen(AncestorOfType = typeof(SkylineDocument))] public PrecursorResult PrecursorResult { get { return new PrecursorResult(Transition.Precursor, GetResultFile()); } } public override string ToString() { return string.Format(@"{0:0}", ChromInfo.Area); } [InvariantDisplayName("TransitionResultLocator")] public string Locator { get { return GetLocator(); } } public override ElementRef GetElementRef() { return TransitionResultRef.PROTOTYPE.ChangeChromInfo(GetResultFile().Replicate.ChromatogramSet, ChromInfo) .ChangeParent(Transition.GetElementRef()); } public override bool IsEmpty() { return ChromInfo.IsEmpty; } } }
1
13,930
You can simplify this by doing: return (EndTime - StartTime) * 60 / PointsAcrossPeak;
ProteoWizard-pwiz
.cs
@@ -56,7 +56,7 @@ ColorPickerWidget::ColorPickerWidget(QWidget *parent): QFrame(parent) { QFontMetrics fm (mLineEdit.font()); - mLineEdit.setFixedWidth ( 10*fm.width (QStringLiteral("a")) ); + mLineEdit.setFixedWidth ( 10*fm.horizontalAdvance (QStringLiteral("a")) ); QHBoxLayout *layout = new QHBoxLayout(this); layout->setContentsMargins (0, 0, 0, 0);
1
/* BEGIN_COMMON_COPYRIGHT_HEADER * (c)LGPL2+ * * LXQt - a lightweight, Qt based, desktop toolset * https://lxqt.org * * Copyright: 2012 Razor team * Authors: * Aaron Lewis <[email protected]> * * This program or library is free software; you can redistribute it * and/or modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General * Public License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA * * END_COMMON_COPYRIGHT_HEADER */ #include "colorpicker.h" #include <QMouseEvent> #include <QHBoxLayout> #include <QScreen> ColorPicker::ColorPicker(const ILXQtPanelPluginStartupInfo &startupInfo) : QObject(), ILXQtPanelPlugin(startupInfo) { realign(); } ColorPicker::~ColorPicker() { } void ColorPicker::realign() { mWidget.button()->setFixedHeight(panel()->iconSize()); mWidget.button()->setFixedWidth(panel()->iconSize()); mWidget.lineEdit()->setFixedHeight(panel()->iconSize()); } ColorPickerWidget::ColorPickerWidget(QWidget *parent): QFrame(parent) { QFontMetrics fm (mLineEdit.font()); mLineEdit.setFixedWidth ( 10*fm.width (QStringLiteral("a")) ); QHBoxLayout *layout = new QHBoxLayout(this); layout->setContentsMargins (0, 0, 0, 0); layout->setSpacing (1); setLayout(layout); layout->addWidget (&mButton); layout->addWidget (&mLineEdit); mButton.setAutoRaise(true); mButton.setIcon(XdgIcon::fromTheme(QStringLiteral("color-picker"), QStringLiteral("kcolorchooser"))); mCapturing = false; connect(&mButton, SIGNAL(clicked()), this, SLOT(captureMouse())); } ColorPickerWidget::~ColorPickerWidget() { } void ColorPickerWidget::mouseReleaseEvent(QMouseEvent *event) { if (!mCapturing) return; WId id = QApplication::desktop()->winId(); QPixmap pixmap = qApp->primaryScreen()->grabWindow(id, event->globalX(), event->globalY(), 1, 1); QImage img = pixmap.toImage(); QColor col = QColor(img.pixel(0,0)); mLineEdit.setText (col.name()); mCapturing = false; releaseMouse(); } void ColorPickerWidget::captureMouse() { grabMouse(Qt::CrossCursor); mCapturing = true; }
1
6,669
I think it's the time for bumping `REQUIRED_QT_VERSION` to the last LTS, 5.12. `QFontMetrics::horizontalAdvance()` doesn't exist in 5.10.
lxqt-lxqt-panel
cpp
@@ -21,7 +21,8 @@ module Bolt statement_count: :cd6, resource_mean: :cd7, plan_steps: :cd8, - return_type: :cd9 + return_type: :cd9, + boltdir_type: :cd11 }.freeze def self.build_client
1
# frozen_string_literal: true require 'bolt/util' require 'bolt/version' require 'json' require 'logging' require 'securerandom' module Bolt module Analytics PROTOCOL_VERSION = 1 APPLICATION_NAME = 'bolt' TRACKING_ID = 'UA-120367942-1' TRACKING_URL = 'https://google-analytics.com/collect' CUSTOM_DIMENSIONS = { operating_system: :cd1, inventory_nodes: :cd2, inventory_groups: :cd3, target_nodes: :cd4, output_format: :cd5, statement_count: :cd6, resource_mean: :cd7, plan_steps: :cd8, return_type: :cd9 }.freeze def self.build_client logger = Logging.logger[self] config_file = File.expand_path('~/.puppetlabs/bolt/analytics.yaml') config = load_config(config_file) if config['disabled'] || ENV['BOLT_DISABLE_ANALYTICS'] logger.debug "Analytics opt-out is set, analytics will be disabled" NoopClient.new else unless config.key?('user-id') config['user-id'] = SecureRandom.uuid write_config(config_file, config) end Client.new(config['user-id']) end rescue StandardError => e logger.debug "Failed to initialize analytics client, analytics will be disabled: #{e}" NoopClient.new end def self.load_config(filename) if File.exist?(filename) YAML.load_file(filename) else {} end end def self.write_config(filename, config) FileUtils.mkdir_p(File.dirname(filename)) File.write(filename, config.to_yaml) end class Client attr_reader :user_id attr_accessor :bundled_content def initialize(user_id) # lazy-load expensive gem code require 'concurrent/configuration' require 'concurrent/future' require 'httpclient' require 'locale' @logger = Logging.logger[self] @http = HTTPClient.new @user_id = user_id @executor = Concurrent.global_io_executor @os = compute_os @bundled_content = [] end def screen_view(screen, **kwargs) custom_dimensions = Bolt::Util.walk_keys(kwargs) do |k| CUSTOM_DIMENSIONS[k] || raise("Unknown analytics key '#{k}'") end screen_view_params = { # Type t: 'screenview', # Screen Name cd: screen }.merge(custom_dimensions) submit(base_params.merge(screen_view_params)) end def event(category, action, label: nil, value: nil, **kwargs) custom_dimensions = Bolt::Util.walk_keys(kwargs) do |k| CUSTOM_DIMENSIONS[k] || raise("Unknown analytics key '#{k}'") end event_params = { # Type t: 'event', # Event Category ec: category, # Event Action ea: action }.merge(custom_dimensions) # Event Label event_params[:el] = label if label # Event Value event_params[:ev] = value if value submit(base_params.merge(event_params)) end def submit(params) # Handle analytics submission in the background to avoid blocking the # app or polluting the log with errors Concurrent::Future.execute(executor: @executor) do @logger.debug "Submitting analytics: #{JSON.pretty_generate(params)}" @http.post(TRACKING_URL, params) @logger.debug "Completed analytics submission" end end # These parameters have terrible names. See this page for complete documentation: # https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters def base_params { v: PROTOCOL_VERSION, # Client ID cid: @user_id, # Tracking ID tid: TRACKING_ID, # Application Name an: APPLICATION_NAME, # Application Version av: Bolt::VERSION, # Anonymize IPs aip: true, # User locale ul: Locale.current.to_rfc, # Custom Dimension 1 (Operating System) cd1: @os.value } end def compute_os Concurrent::Future.execute(executor: @executor) do require 'facter' os = Facter.value('os') "#{os['name']} #{os.dig('release', 'major')}" end end # If the user is running a very fast command, there may not be time for # analytics submission to complete before the command is finished. In # that case, we give a little buffer for any stragglers to finish up. # 250ms strikes a balance between accomodating slower networks while not # introducing a noticeable "hang". def finish @executor.shutdown @executor.wait_for_termination(0.25) end end class NoopClient attr_accessor :bundled_content def initialize @logger = Logging.logger[self] @bundled_content = [] end def screen_view(screen, **_kwargs) @logger.debug "Skipping submission of '#{screen}' screenview because analytics is disabled" end def event(category, action, **_kwargs) @logger.debug "Skipping submission of '#{category} #{action}' event because analytics is disabled" end def finish; end end end end
1
12,013
I already set up cd10 for "inventory_version in google analytics. I've added cd11 for Boltdir Type now
puppetlabs-bolt
rb
@@ -45,6 +45,10 @@ module Travis module Build class Script TEMPLATES_PATH = File.expand_path('../templates', __FILE__) + INTERNAL_RUBY_REGEX = ENV.fetch( + 'TRAVIS_INTERNAL_RUBY_REGEX', + 'ruby-(2\.[0-2]\.[0-9]|1\.9\.3)' + ).untaint DEFAULTS = {} class << self
1
require 'core_ext/hash/deep_merge' require 'core_ext/hash/deep_symbolize_keys' require 'core_ext/object/false' require 'erb' require 'rbconfig' require 'travis/build/addons' require 'travis/build/appliances' require 'travis/build/git' require 'travis/build/helpers' require 'travis/build/stages' require 'travis/build/script/android' require 'travis/build/script/c' require 'travis/build/script/clojure' require 'travis/build/script/cpp' require 'travis/build/script/crystal' require 'travis/build/script/csharp' require 'travis/build/script/d' require 'travis/build/script/dart' require 'travis/build/script/erlang' require 'travis/build/script/elixir' require 'travis/build/script/go' require 'travis/build/script/groovy' require 'travis/build/script/generic' require 'travis/build/script/haskell' require 'travis/build/script/haxe' require 'travis/build/script/julia' require 'travis/build/script/nix' require 'travis/build/script/node_js' require 'travis/build/script/objective_c' require 'travis/build/script/perl' require 'travis/build/script/perl6' require 'travis/build/script/php' require 'travis/build/script/pure_java' require 'travis/build/script/python' require 'travis/build/script/r' require 'travis/build/script/ruby' require 'travis/build/script/rust' require 'travis/build/script/scala' require 'travis/build/script/smalltalk' require 'travis/build/script/shared/directory_cache' module Travis module Build class Script TEMPLATES_PATH = File.expand_path('../templates', __FILE__) DEFAULTS = {} class << self def defaults Git::DEFAULTS.merge(self::DEFAULTS) end end include Module.new { Stages::STAGES.each_slice(2).map(&:last).flatten.each { |stage| define_method(stage) {} } } include Appliances, DirectoryCache, Deprecation, Template attr_reader :sh, :data, :options, :validator, :addons, :stages attr_accessor :setup_cache_has_run_for def initialize(data) @data = Data.new({ config: self.class.defaults }.deep_merge(data.deep_symbolize_keys)) @options = {} @sh = Shell::Builder.new @addons = Addons.new(self, sh, self.data, config) @stages = Stages.new(self, sh, config) @setup_cache_has_run_for = {} end def compile(ignore_taint = false) Shell.generate(sexp, ignore_taint) end def sexp run sh.to_sexp end def cache_slug_keys plain_env_vars = Array((config[:env] || []).dup).delete_if {|env| env.start_with? 'SECURE '} [ 'cache', config[:os], config[:dist], config[:osx_image], OpenSSL::Digest::SHA256.hexdigest(plain_env_vars.sort.join('=')) ] end def cache_slug cache_slug_keys.compact.join('-') end def archive_url_for(bucket, version, lang = self.class.name.split('::').last.downcase, ext = 'bz2') sh.if "$(uname) = 'Linux'" do sh.raw "travis_host_os=$(lsb_release -is | tr 'A-Z' 'a-z')" sh.raw "travis_rel_version=$(lsb_release -rs)" end sh.elif "$(uname) = 'Darwin'" do sh.raw "travis_host_os=osx" sh.raw "travis_rel=$(sw_vers -productVersion)" sh.raw "travis_rel_version=${travis_rel%*.*}" end "archive_url=https://s3.amazonaws.com/#{bucket}/binaries/${travis_host_os}/${travis_rel_version}/$(uname -m)/#{lang}-#{version}.tar.#{ext}" end def debug_build_via_api? ! data.debug_options.empty? end private def config data.config end def debug if debug_build_via_api? sh.echo "Debug build initiated by #{data.debug_options[:created_by]}", ansi: :yellow if debug_quiet? sh.raw "travis_debug --quiet" else sh.raw "travis_debug" end sh.echo sh.echo "All remaining steps, including caching and deploy, will be skipped.", ansi: :yellow end end def run stages.run if apply :validate sh.raw template('footer.sh') # apply :deprecations end def header sh.raw template('header.sh', build_dir: BUILD_DIR), pos: 0 end def configure apply :show_system_info apply :update_glibc apply :clean_up_path apply :fix_resolv_conf apply :fix_etc_hosts apply :no_ipv6_localhost apply :fix_etc_mavenrc apply :etc_hosts_pinning apply :fix_wwdr_certificate apply :put_localhost_first apply :home_paths apply :disable_initramfs apply :disable_ssh_roaming apply :debug_tools apply :npm_registry apply :rvm_use end def checkout apply :checkout end def export apply :env end def prepare apply :services apply :fix_ps4 # TODO if this is to fix an rvm issue (as the specs say) then should this go to Rvm instead? end def disable_sudo apply :disable_sudo end def reset_state if debug_build_via_api? raise "Debug payload does not contain 'previous_state' value." unless previous_state = data.debug_options[:previous_state] sh.echo sh.echo "This is a debug build. The build result is reset to its previous value, \\\"#{previous_state}\\\".", ansi: :yellow case previous_state when "passed" sh.export 'TRAVIS_TEST_RESULT', '0', echo: false when "failed" sh.export 'TRAVIS_TEST_RESULT', '1', echo: false when "errored" sh.raw 'travis_terminate 2' end end end def config_env_vars @config_env_vars ||= Build::Env::Config.new(data, config) Array(@config_env_vars.data[:env]) end def host_os case RbConfig::CONFIG["host_os"] when /^(?i:linux)/ '$(lsb_release -is | tr "A-Z" "a-z")' when /^(?i:darwin)/ 'osx' end end def rel_version case RbConfig::CONFIG["host_os"] when /^(?i:linux)/ '$(lsb_release -rs)' when /^(?i:darwin)/ '${$(sw_vers -productVersion)%*.*}' end end def debug_quiet? debug_build_via_api? && data.debug_options[:quiet] end def debug_enabled? ENV['TRAVIS_ENABLE_DEBUG_TOOLS'] == '1' end end end end
1
14,454
@henrikhodne We are lazily skipping `jruby-*` here (assuming that JRuby all of a sudden start using these version numbers).
travis-ci-travis-build
rb
@@ -739,8 +739,11 @@ void CPaintStatistics::DrawAxis(wxDC &dc, const double max_val_y, const double m double y_start_val = ceil(min_val_y / d_oy_val) * d_oy_val; d_oy_count = (int)floor((max_val_y - y_start_val) / d_oy_val); + double temp_int_part; + int prec = modf(d_oy_val, &temp_int_part) == 0.0 ? 0 : 2; + for (double ny = 0; ny <= double(d_oy_count); ++ny){ - dc.GetTextExtent(wxString::Format(wxT("%s"), format_number(y_start_val + ny * d_oy_val, 2)), &w_temp, &h_temp, &des_temp, &lead_temp); + dc.GetTextExtent(wxString::Format(wxT("%s"), format_number(y_start_val + ny * d_oy_val, prec)), &w_temp, &h_temp, &des_temp, &lead_temp); x0 = wxCoord(m_Graph_X_start + 1.0); y0 = wxCoord(m_Ay_ValToCoord * (y_start_val + ny * d_oy_val) + m_By_ValToCoord); x1 = wxCoord(m_Graph_X_end - 1.0);
1
// This file is part of BOINC. // http://boinc.berkeley.edu // Copyright (C) 2008 University of California // // BOINC is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License // as published by the Free Software Foundation, // either version 3 of the License, or (at your option) any later version. // // BOINC is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // See the GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with BOINC. If not, see <http://www.gnu.org/licenses/>. #if defined(__GNUG__) && !defined(__APPLE__) #pragma implementation "ViewStatistics.h" #endif #include "stdwx.h" #include "BOINCGUIApp.h" #include "BOINCBaseFrame.h" #include "MainDocument.h" #include "AdvancedFrame.h" #include "BOINCTaskCtrl.h" #include "BOINCListCtrl.h" #include "ViewStatistics.h" #include "Events.h" #include "util.h" #include "res/stats.xpm" enum { // Command buttons (m_SelectedStatistic) show_user_total = 0, show_user_average, show_host_total, show_host_average, n_command_buttons }; enum { // Mode buttons (m_ModeViewStatistic) mode_one_project = 0, mode_all_separate, mode_all_together, mode_sum }; enum { // Project buttons previous_project = 0, next_project, show_hide_project_list }; BEGIN_EVENT_TABLE (CPaintStatistics, wxWindow) EVT_PAINT(CPaintStatistics::OnPaint) EVT_SIZE(CPaintStatistics::OnSize) EVT_LEFT_DOWN(CPaintStatistics::OnLeftMouseDown) EVT_LEFT_UP(CPaintStatistics::OnLeftMouseUp) EVT_RIGHT_DOWN(CPaintStatistics::OnRightMouseDown) EVT_RIGHT_UP(CPaintStatistics::OnRightMouseUp) EVT_MOTION(CPaintStatistics::OnMouseMotion) EVT_LEAVE_WINDOW(CPaintStatistics::OnMouseLeaveWindows) EVT_ERASE_BACKGROUND(CPaintStatistics::OnEraseBackground) EVT_SCROLL(CPaintStatistics::OnLegendScroll) END_EVENT_TABLE () // Set USE_MEMORYDC FALSE to aid debugging #define USE_MEMORYDC TRUE CPaintStatistics::CPaintStatistics(wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style, const wxString& name ): wxWindow(parent, id, pos, size, style, name) { m_font_standart = *wxSWISS_FONT; m_font_bold = *wxSWISS_FONT; m_font_standart_italic = *wxSWISS_FONT; m_SelectedStatistic = show_user_total; heading = wxT(""); m_ModeViewStatistic = mode_one_project; m_NextProjectStatistic = 0; m_ViewHideProjectStatistic = -1; m_GraphLineWidth = 2; m_GraphPointWidth = 4; m_Space_for_scrollbar = 0; m_Num_projects = 0; m_previous_SelProj = -1; m_scrollBar = new wxScrollBar(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxSB_VERTICAL); int h; m_scrollBar->GetSize(&m_Scrollbar_width, &h); m_scrollBar->SetScrollbar(0, 1, 1, 1); m_scrollBar->Hide(); m_Legend_Shift_Mode1 = 0; m_Legend_Shift_Mode2 = 0; m_GraphMarker_X1 = 0; m_GraphMarker_Y1 = 0; m_GraphMarker1 = false; m_GraphZoom_X1 = 0; m_GraphZoom_Y1 = 0; m_GraphZoom_X2 = 0; m_GraphZoom_Y2 = 0; m_GraphZoom_X2_old = 0; m_GraphZoom_Y2_old = 0; m_GraphZoomStart = false; m_GraphMove_X1 = 0; m_GraphMove_Y1 = 0; m_GraphMove_X2 = 0; m_GraphMove_Y2 = 0; m_GraphMoveStart = false; m_GraphMoveGo = false; m_Zoom_max_val_X = 0; m_Zoom_min_val_X = 0; m_Zoom_max_val_Y = 0; m_Zoom_min_val_Y = 0; m_Zoom_Auto = true; // XY m_main_X_start = 0; m_main_X_end = 0; m_main_Y_start = 0; m_main_Y_end = 0; m_WorkSpace_X_start = 0; m_WorkSpace_X_end = 0; m_WorkSpace_Y_start = 0; m_WorkSpace_Y_end = 0; m_Legend_X_start = 0; m_Legend_X_end = 0; m_Legend_Y_start = 0; m_Legend_Y_end = 0; m_Legend_select_X_start = 0; m_Legend_select_X_end = 0; m_Legend_select_Y_start = 0; m_Legend_select_Y_end = 0; m_Graph_X_start = 0; m_Graph_X_end = 0; m_Graph_Y_start = 0; m_Graph_Y_end = 0; m_Graph_draw_X_start = 0; m_Graph_draw_X_end = 0; m_Graph_draw_Y_start = 0; m_Graph_draw_Y_end = 0; m_Legend_dY = 0; m_LegendDraw = true; // Default colours m_pen_MarkerLineColour = wxColour(0, 0, 0); m_pen_ZoomRectColour = wxColour (128, 64, 95); m_brush_ZoomRectColour = wxColour(24, 31, 0); m_brush_AxisColour = wxColour(192, 224, 255); m_pen_AxisColour = wxColour(64, 128, 192); m_pen_AxisColourZoom = wxColour(255, 64, 0); m_pen_AxisColourAutoZoom = wxColour(64, 128, 192); m_pen_AxisXColour = wxColour(64, 128, 192); m_pen_AxisYColour = wxColour(64, 128, 192); m_pen_AxisXTextColour = wxColour(0, 0, 0); m_pen_AxisYTextColour = wxColour(0, 0, 0); m_brush_LegendColour = wxColour(235, 255, 255);//wxColour(220, 240, 255); m_brush_LegendSelectColour = wxColour(192, 224, 255); m_pen_LegendSelectColour = wxColour(64, 128, 192); m_pen_LegendSelectTextColour = wxColour(0, 0, 0); m_pen_LegendColour = wxColour(64, 128, 192); m_pen_LegendTextColour = wxColour(0, 0, 0); m_brush_MainColour = wxColour(255, 255, 255); m_pen_MainColour = wxColour(64, 128, 192); m_pen_HeadTextColour = wxColour(0, 0, 0); m_pen_ProjectHeadTextColour = wxColour(0, 0, 0); m_pen_GraphTotalColour = wxColour(255, 0, 0); m_pen_GraphRACColour = wxColour(0, 160, 0); m_pen_GraphTotalHostColour = wxColour(0, 0, 255); m_pen_GraphRACHostColour = wxColour(0, 0, 0); m_dc_bmp.Create(1, 1); m_full_repaint = true; m_bmp_OK = false; #ifdef __WXMAC__ m_fauxStatisticsView = NULL; SetupMacAccessibilitySupport(); #endif } CPaintStatistics::~CPaintStatistics() { if (m_scrollBar) { delete m_scrollBar; } #ifdef __WXMAC__ RemoveMacAccessibilitySupport(); #endif } static void getTypePoint(int &typePoint, int number) {typePoint = number / 10;} static bool CrossTwoLine(const double X1_1, const double Y1_1, const double X1_2, const double Y1_2, const double X2_1, const double Y2_1, const double X2_2, const double Y2_2, double &Xcross, double &Ycross) { double A1 = Y1_1 - Y1_2; double B1 = X1_2 - X1_1; double C1 = - X1_1 * A1 - Y1_1 * B1; double A2 = Y2_1 - Y2_2; double B2 = X2_2 - X2_1; double C2 = - X2_1 * A2 - Y2_1 * B2; double tmp1 = (A1 * B2 - A2 * B1); if (0 == tmp1){ Xcross = 0; Ycross = 0; return false; }else{ Xcross = (B1 * C2 - B2 * C1) / tmp1; Ycross = (C1 * A2 - C2 * A1) / tmp1; return true; } } //----Draw "Point" static void myDrawPoint(wxDC &dc,int X, int Y, wxColour graphColour,int numberTypePoint, int PointWidth) { dc.SetPen(wxPen(graphColour , 1 , wxSOLID)); switch (numberTypePoint % 5){ case 1: {wxPoint* points = new wxPoint[3]; points[0] = wxPoint(X, Y - 1 - (PointWidth / 2)); points[1] = wxPoint(X + (PointWidth / 2), Y + (PointWidth / 2)); points[2] = wxPoint(X - (PointWidth / 2), Y + (PointWidth / 2)); dc.DrawPolygon(3, points); delete[] points; break;} case 2: {wxPoint* points = new wxPoint[3]; points[0] = wxPoint(X, Y + 1 + (PointWidth / 2)); points[1] = wxPoint(X + (PointWidth / 2), Y - (PointWidth / 2)); points[2] = wxPoint(X - (PointWidth / 2), Y - (PointWidth / 2)); dc.DrawPolygon(3, points); delete[] points; break;} case 3: dc.DrawRectangle(wxCoord(X - (PointWidth / 2)),wxCoord(Y - (PointWidth / 2)),wxCoord(PointWidth + 1),wxCoord(PointWidth + 1)); break; case 4: {wxPoint* points = new wxPoint[4]; points[0] = wxPoint(X, Y - 1 - (PointWidth / 2)); points[1] = wxPoint(X + 1 + (PointWidth / 2), Y); points[2] = wxPoint(X, Y + 1 + (PointWidth / 2)); points[3] = wxPoint(X - 1 - (PointWidth / 2), Y); dc.DrawPolygon(4, points); delete[] points; break;} default:dc.DrawCircle(wxCoord(X), wxCoord(Y), wxCoord(PointWidth / 2)); } } //----Find minimum/maximum value---- static void MinMaxDayCredit(std::vector<PROJECT*>::const_iterator &i, double &min_credit, double &max_credit, double &min_day, double &max_day, const int m_SelectedStatistic, bool first = true) { for (std::vector<DAILY_STATS>::const_iterator j = (*i)->statistics.begin(); j != (*i)->statistics.end(); ++j) { if (first){ max_day = j->day; switch (m_SelectedStatistic){ case show_user_total: max_credit = j->user_total_credit; break; case show_user_average: max_credit = j->user_expavg_credit; break; case show_host_total: max_credit = j->host_total_credit; break; case show_host_average: max_credit = j->host_expavg_credit; break; default: max_credit = 0.0; } min_day = max_day; min_credit = max_credit; first = false; } else { if (j->day < min_day) min_day = j->day; if (j->day > max_day) max_day = j->day; switch (m_SelectedStatistic){ case show_user_total: if (j->user_total_credit > max_credit) max_credit = j->user_total_credit; if (j->user_total_credit < min_credit) min_credit = j->user_total_credit; break; case show_user_average: if (j->user_expavg_credit > max_credit) max_credit = j->user_expavg_credit; if (j->user_expavg_credit < min_credit) min_credit = j->user_expavg_credit; break; case show_host_total: if (j->host_total_credit > max_credit) max_credit = j->host_total_credit; if (j->host_total_credit < min_credit) min_credit = j->host_total_credit; break; case show_host_average: if (j->host_expavg_credit > max_credit) max_credit = j->host_expavg_credit; if (j->host_expavg_credit < min_credit) min_credit = j->host_expavg_credit; break; } } } } static void CheckMinMaxD(double &min_val, double &max_val) { if (min_val > max_val) min_val = max_val; if (max_val == min_val){ max_val += 0.5; min_val -= 0.5; } } void CPaintStatistics::ClearXY(){ m_main_X_start = 0; m_main_X_end = 0; m_main_Y_start = 0; m_main_Y_end = 0; m_WorkSpace_X_start = 0; m_WorkSpace_X_end = 0; m_WorkSpace_Y_start = 0; m_WorkSpace_Y_end = 0; m_Graph_X_start = 0; m_Graph_X_end = 0; m_Graph_Y_start = 0; m_Graph_Y_end = 0; m_Graph_draw_X_start = 0; m_Graph_draw_X_end = 0; m_Graph_draw_Y_start = 0; m_Graph_draw_Y_end = 0; } void CPaintStatistics::ClearLegendXY(){ m_Legend_X_start = 0; m_Legend_X_end = 0; m_Legend_Y_start = 0; m_Legend_Y_end = 0; m_Legend_select_X_start = 0; m_Legend_select_X_end = 0; m_Legend_select_Y_start = 0; m_Legend_select_Y_end = 0; m_Legend_dY = 0; } void CPaintStatistics::AB(const double x_coord1, const double y_coord1, const double x_coord2, const double y_coord2, const double x_val1, const double y_val1, const double x_val2, const double y_val2){ // Val -> Coord if (0.0 == (x_val2 - x_val1)){ m_Ax_ValToCoord = 0.0; m_Bx_ValToCoord = 0.0; }else{ m_Ax_ValToCoord = (x_coord2 - x_coord1) / (x_val2 - x_val1); m_Bx_ValToCoord = x_coord1 - (m_Ax_ValToCoord * x_val1); } if (0.0 == (y_val2 - y_val1)){ m_Ay_ValToCoord = 0.0; m_By_ValToCoord = 0.0; }else{ m_Ay_ValToCoord = (y_coord2 - y_coord1) / (y_val2 - y_val1); m_By_ValToCoord = y_coord1 - (m_Ay_ValToCoord * y_val1); } // Coord -> Val if (0.0 == (x_coord2 - x_coord1)){ m_Ax_CoordToVal = 0.0; m_Bx_CoordToVal = 0.0; }else{ m_Ax_CoordToVal = (x_val2 - x_val1) / (x_coord2 - x_coord1); m_Bx_CoordToVal = x_val1 - (m_Ax_CoordToVal * x_coord1); } if (0.0 == (y_coord2 - y_coord1)){ m_Ay_CoordToVal = 0.0; m_By_CoordToVal = 0.0; }else{ m_Ay_CoordToVal = (y_val2 - y_val1) / (y_coord2 - y_coord1); m_By_CoordToVal = y_val1 - (m_Ay_CoordToVal * y_coord1); } } void CPaintStatistics::AddToStats(const DAILY_STATS &src, DAILY_STATS &dst) { dst.user_total_credit += src.user_total_credit; dst.user_expavg_credit += src.user_expavg_credit; dst.host_total_credit += src.host_total_credit; dst.host_expavg_credit += src.host_expavg_credit; } //----Draw Main Head---- void CPaintStatistics::DrawMainHead(wxDC &dc, const wxString head_name){ wxCoord w_temp = 0, h_temp = 0, des_temp = 0, lead_temp = 0; dc.GetTextExtent(head_name, &w_temp, &h_temp, &des_temp, &lead_temp); dc.SetTextForeground (m_pen_HeadTextColour); wxCoord x0 = wxCoord(m_WorkSpace_X_start + ((m_WorkSpace_X_end - m_WorkSpace_X_start - double(w_temp)) / 2.0)); wxCoord y0 = wxCoord(m_WorkSpace_Y_start + 1.0); if (x0 > wxCoord(m_WorkSpace_X_end)) x0 = wxCoord(m_WorkSpace_X_end); if (x0 < wxCoord(m_WorkSpace_X_start)) x0 = wxCoord(m_WorkSpace_X_start); if (x0 < 0) x0 = 0; if (y0 > wxCoord(m_WorkSpace_Y_end)) y0 = wxCoord(m_WorkSpace_Y_end); if (y0 < wxCoord(m_WorkSpace_Y_start)) y0 = wxCoord(m_WorkSpace_Y_start); if (y0 < 0) y0 = 0; dc.DrawText (head_name, x0, y0); m_WorkSpace_Y_start += double(h_temp) + 2.0; if (m_WorkSpace_Y_start > m_WorkSpace_Y_end) m_WorkSpace_Y_start = m_WorkSpace_Y_end; if (m_WorkSpace_Y_start < 0.0) m_WorkSpace_Y_start = 0.0; } //----Draw Project Head---- void CPaintStatistics::DrawProjectHead(wxDC &dc, PROJECT* project1, const wxString head_name_last){ wxCoord w_temp = 0, h_temp = 0, des_temp = 0, lead_temp = 0; wxString head_name = wxT(""); wxCoord x0 = 0; wxCoord y0 = 0; if (project1) { head_name = wxString(_("Project")) + wxT(": ") + wxString(project1->project_name.c_str(), wxConvUTF8); dc.GetTextExtent(head_name, &w_temp, &h_temp, &des_temp, &lead_temp); x0 = wxCoord(m_WorkSpace_X_start + ((m_WorkSpace_X_end - m_WorkSpace_X_start - double(w_temp)) / 2.0)); y0 = wxCoord(m_WorkSpace_Y_start + 1.0); if (x0 > wxCoord(m_WorkSpace_X_end)) x0 = wxCoord(m_WorkSpace_X_end); if (x0 < wxCoord(m_WorkSpace_X_start)) x0 = wxCoord(m_WorkSpace_X_start); if (x0 < 0) x0 = 0; if (y0 > wxCoord(m_WorkSpace_Y_end)) y0 = wxCoord(m_WorkSpace_Y_end); if (y0 < wxCoord(m_WorkSpace_Y_start)) y0 = wxCoord(m_WorkSpace_Y_start); if (y0 < 0) y0 = 0; dc.DrawText (head_name, x0, y0); m_WorkSpace_Y_start += double(h_temp) + 2.0; if (m_WorkSpace_Y_start > m_WorkSpace_Y_end) m_WorkSpace_Y_start = m_WorkSpace_Y_end; if (m_WorkSpace_Y_start < 0.0) m_WorkSpace_Y_start = 0.0; head_name = wxString(_("Account")) + wxT(": ") + wxString(project1->user_name.c_str(), wxConvUTF8); dc.GetTextExtent(head_name, &w_temp, &h_temp, &des_temp, &lead_temp); x0 = wxCoord(m_WorkSpace_X_start + ((m_WorkSpace_X_end - m_WorkSpace_X_start - double(w_temp)) / 2.0)); y0 = wxCoord(m_WorkSpace_Y_start + 1.0); if (x0 > wxCoord(m_WorkSpace_X_end)) x0 = wxCoord(m_WorkSpace_X_end); if (x0 < wxCoord(m_WorkSpace_X_start)) x0 = wxCoord(m_WorkSpace_X_start); if (x0 < 0) x0 = 0; if (y0 > wxCoord(m_WorkSpace_Y_end)) y0 = wxCoord(m_WorkSpace_Y_end); if (y0 < wxCoord(m_WorkSpace_Y_start)) y0 = wxCoord(m_WorkSpace_Y_start); if (y0 < 0) y0 = 0; dc.DrawText (head_name, x0, y0); m_WorkSpace_Y_start += double(h_temp) + 2.0; if (m_WorkSpace_Y_start > m_WorkSpace_Y_end) m_WorkSpace_Y_start = m_WorkSpace_Y_end; if (m_WorkSpace_Y_start < 0.0) m_WorkSpace_Y_start = 0.0; head_name = wxString(_("Team")) + wxT(": ") + wxString(project1->team_name.c_str(), wxConvUTF8); dc.GetTextExtent(head_name, &w_temp, &h_temp, &des_temp, &lead_temp); x0 = wxCoord(m_WorkSpace_X_start + ((m_WorkSpace_X_end - m_WorkSpace_X_start - double(w_temp)) / 2.0)); y0 = wxCoord(m_WorkSpace_Y_start + 1.0); if (x0 > wxCoord(m_WorkSpace_X_end)) x0 = wxCoord(m_WorkSpace_X_end); if (x0 < wxCoord(m_WorkSpace_X_start)) x0 = wxCoord(m_WorkSpace_X_start); if (x0 < 0) x0 = 0; if (y0 > wxCoord(m_WorkSpace_Y_end)) y0 = wxCoord(m_WorkSpace_Y_end); if (y0 < wxCoord(m_WorkSpace_Y_start)) y0 = wxCoord(m_WorkSpace_Y_start); if (y0 < 0) y0 = 0; dc.DrawText (head_name, x0, y0); m_WorkSpace_Y_start += double(h_temp) + 2.0; if (m_WorkSpace_Y_start > m_WorkSpace_Y_end) m_WorkSpace_Y_start = m_WorkSpace_Y_end; if (m_WorkSpace_Y_start < 0.0) m_WorkSpace_Y_start = 0.0; dc.GetTextExtent(head_name_last, &w_temp, &h_temp, &des_temp, &lead_temp); x0 = wxCoord(m_WorkSpace_X_start + ((m_WorkSpace_X_end - m_WorkSpace_X_start - double(w_temp)) / 2.0)); y0 = wxCoord(m_WorkSpace_Y_start + 1.0); if (x0 > wxCoord(m_WorkSpace_X_end)) x0 = wxCoord(m_WorkSpace_X_end); if (x0 < wxCoord(m_WorkSpace_X_start)) x0 = wxCoord(m_WorkSpace_X_start); if (x0 < 0) x0 = 0; if (y0 > wxCoord(m_WorkSpace_Y_end)) y0 = wxCoord(m_WorkSpace_Y_end); if (y0 < wxCoord(m_WorkSpace_Y_start)) y0 = wxCoord(m_WorkSpace_Y_start); if (y0 < 0) y0 = 0; dc.DrawText (head_name_last, x0, y0); m_WorkSpace_Y_start += double(h_temp) + 2.0; if (m_WorkSpace_Y_start > m_WorkSpace_Y_end) m_WorkSpace_Y_start = m_WorkSpace_Y_end; if (m_WorkSpace_Y_start < 0.0) m_WorkSpace_Y_start = 0.0; } } //----Draw Legend---- void CPaintStatistics::DrawLegend(wxDC &dc, PROJECTS* proj, CMainDocument* pDoc, int SelProj, bool bColour, int &m_Legend_Shift){ wxString head_name = wxT("0"); wxCoord project_name_max_width = 0; const double radius1 = 5; const wxCoord buffer_y1 = 3; const wxCoord buffer_x1 = 3; int count = -1; // int project_count = -1; wxCoord w_temp = 0, h_temp = 0, des_temp = 0, lead_temp = 0; wxCoord x0 = 0; wxCoord y0 = 0; wxCoord h0 = 0; wxCoord w0 = 0; wxCoord totalTextAreaHeight = 0; dc.SetFont(m_font_bold); dc.GetTextExtent(head_name, &w_temp, &h_temp, &des_temp, &lead_temp); m_Legend_dY = (double)(h_temp) + 4.0; if (m_Legend_dY < 0) m_Legend_dY = 0; for (std::vector<PROJECT*>::const_iterator i = proj->projects.begin(); i != proj->projects.end(); ++i) { ++count; PROJECT* state_project = pDoc->state.lookup_project((*i)->master_url); if (state_project) head_name = wxString(state_project->project_name.c_str(), wxConvUTF8); dc.GetTextExtent(head_name, &w_temp, &h_temp, &des_temp, &lead_temp); if (project_name_max_width < w_temp) project_name_max_width = w_temp; } m_Num_projects = count + 1; project_name_max_width += wxCoord(8) + buffer_x1 + buffer_x1 + wxCoord(m_GraphPointWidth) + wxCoord(2); if (project_name_max_width < 0) project_name_max_width = 0; totalTextAreaHeight = (m_Num_projects * m_Legend_dY); dc.SetBrush(wxBrush(m_brush_LegendColour , wxSOLID)); dc.SetPen(wxPen(m_pen_LegendColour , 1 , wxSOLID)); y0 = wxCoord(m_WorkSpace_Y_start) + buffer_y1; if (y0 > wxCoord(m_WorkSpace_Y_end)) y0 = wxCoord(m_WorkSpace_Y_end); if (y0 < wxCoord(m_WorkSpace_Y_start)) y0 = wxCoord(m_WorkSpace_Y_start); if (y0 < 0) y0 = 0; w0 = project_name_max_width - buffer_x1 - buffer_x1; if (w0 < 0) w0 = 0; h0 = wxCoord(m_WorkSpace_Y_end - m_WorkSpace_Y_start) - buffer_y1 - buffer_y1; if (h0 < 0) h0 = 0; m_Space_for_scrollbar = 0; if (h0 < (totalTextAreaHeight + (2 * radius1))) m_Space_for_scrollbar = m_Scrollbar_width; int numVisible = (h0 - (2 * radius1)) / m_Legend_dY; int numSteps = m_Num_projects - numVisible + 1; if (numSteps < 2) { m_scrollBar->Hide(); } else { m_scrollBar->SetSize(m_WorkSpace_X_end - m_Scrollbar_width, m_WorkSpace_Y_start, m_Scrollbar_width, m_WorkSpace_Y_end - m_WorkSpace_Y_start, 0); m_scrollBar->SetScrollbar(m_scrollBar->GetThumbPosition(), 1, numSteps, 1); m_scrollBar->Show(); } x0 = wxCoord(m_WorkSpace_X_end) - project_name_max_width + buffer_x1 - m_Space_for_scrollbar; if (x0 > wxCoord(m_WorkSpace_X_end)) x0 = wxCoord(m_WorkSpace_X_end); if (x0 < wxCoord(m_WorkSpace_X_start)) x0 = wxCoord(m_WorkSpace_X_start); if (x0 < 0) x0 = 0; dc.DrawRoundedRectangle(x0, y0, w0, h0, radius1); m_Legend_X_start = double(x0); m_Legend_X_end = double(x0 + w0); m_Legend_Y_start = double(y0); m_Legend_Y_end = double(y0 + h0); if (m_Legend_X_end > m_WorkSpace_X_end) m_Legend_X_end = m_WorkSpace_X_end; if (m_Legend_Y_end > m_WorkSpace_Y_end) m_Legend_Y_end = m_WorkSpace_Y_end; if (m_Legend_X_start > m_Legend_X_end) m_Legend_X_start = m_Legend_X_end; if (m_Legend_Y_start > m_Legend_Y_end) m_Legend_Y_start = m_Legend_Y_end; m_Legend_select_X_start = m_Legend_X_start; m_Legend_select_X_end = m_Legend_X_end; m_Legend_select_Y_start = m_Legend_Y_start + radius1; m_Legend_select_Y_end = m_Legend_Y_end - radius1; if (m_Legend_select_Y_start < 0.0) m_Legend_select_Y_start = 0.0; if (m_Legend_select_Y_end < 0.0) m_Legend_select_Y_end = 0.0; if (m_Legend_select_Y_start > m_Legend_select_Y_end) m_Legend_select_Y_start = m_Legend_select_Y_end; // Legend Shift (start) int Legend_count_temp = 0; if (m_Legend_dY > 0) Legend_count_temp = int(floor((m_Legend_select_Y_end - m_Legend_select_Y_start) / m_Legend_dY)); if (numSteps > 1) { m_Legend_Shift = m_scrollBar->GetThumbPosition(); } else { m_Legend_Shift = 0; } if ((SelProj >= 0) && (m_previous_SelProj != SelProj)) { m_previous_SelProj = SelProj; if (Legend_count_temp <= 0){ m_Legend_Shift = SelProj; } else { if (SelProj < m_Legend_Shift) m_Legend_Shift = SelProj; if (SelProj >= (m_Legend_Shift + Legend_count_temp)) m_Legend_Shift = SelProj - Legend_count_temp + 1; } } if ((m_Legend_Shift + Legend_count_temp) > count) m_Legend_Shift = count - Legend_count_temp + 1; if (m_Legend_Shift > count) m_Legend_Shift = count; //??? if (m_Legend_Shift < 0) m_Legend_Shift = 0; m_scrollBar->SetThumbPosition(m_Legend_Shift); // Legend Shift (end) //--------------- // project_count = count; count = -1; m_WorkSpace_X_end -= double(project_name_max_width) + m_Space_for_scrollbar; if (m_WorkSpace_X_end < m_WorkSpace_X_start) m_WorkSpace_X_end = m_WorkSpace_X_start; if (m_WorkSpace_X_end < 0.0) m_WorkSpace_X_end = 0.0; for (std::vector<PROJECT*>::const_iterator i = proj->projects.begin(); i != proj->projects.end(); ++i) { ++count; if (count < m_Legend_Shift) continue; ///Draw project name head_name = wxT("?"); PROJECT* state_project = pDoc->state.lookup_project((*i)->master_url); if (state_project) head_name = wxString(state_project->project_name.c_str(), wxConvUTF8); if (SelProj == count){ dc.SetBrush(wxBrush(m_brush_LegendSelectColour , wxSOLID)); dc.SetPen(wxPen(m_pen_LegendSelectColour , 1 , wxSOLID)); x0 = wxCoord(m_WorkSpace_X_end) + buffer_x1 - wxCoord(1); y0 = wxCoord(m_WorkSpace_Y_start + (double)(count - m_Legend_Shift) * m_Legend_dY + double(buffer_y1) + radius1); w0 = project_name_max_width - buffer_x1 - buffer_x1 + 2; h0 = wxCoord(m_Legend_dY); if (x0 < 0) x0 = 0; if (y0 < 0) y0 = 0; if (w0 < 0) w0 = 0; if (h0 < 0) h0 = 0; dc.DrawRoundedRectangle(x0 ,y0 , w0, h0, 1); } wxColour graphColour = wxColour(0, 0, 0); int typePoint = 0; if (bColour){ getTypePoint(typePoint, count); color_cycle(count, proj->projects.size(), graphColour); } else if (SelProj == count) { graphColour = m_pen_LegendSelectTextColour; } else { graphColour = m_pen_LegendTextColour; } dc.SetBrush(wxBrush(m_brush_LegendColour , wxSOLID)); x0 = wxCoord(m_WorkSpace_X_end) + buffer_x1 + wxCoord(4) + wxCoord(m_GraphPointWidth / 2); y0 = wxCoord(m_WorkSpace_Y_start + ((double)(count - m_Legend_Shift) + 0.5) * m_Legend_dY + double(buffer_y1) + radius1); if (x0 < 0) x0 = 0; if (y0 < 0) y0 = 0; if ((SelProj >= 0) || (!(m_HideProjectStatistic.count( wxString( (*i)->master_url, wxConvUTF8 ) )))){ myDrawPoint(dc, int(x0), int(y0), graphColour, typePoint ,m_GraphPointWidth); dc.SetFont(m_font_bold); }else { dc.SetFont(m_font_standart_italic); graphColour = wxColour(0, 0, 0); } x0 = wxCoord(m_WorkSpace_X_end) + buffer_x1 + wxCoord(7) + wxCoord(m_GraphPointWidth); y0 = wxCoord(m_WorkSpace_Y_start + 1.0 + (double)(count - m_Legend_Shift) * m_Legend_dY + double(buffer_y1) + radius1); if (x0 < 0) x0 = 0; if (y0 < 0) y0 = 0; dc.SetTextForeground(graphColour); dc.DrawText(head_name, x0, y0); m_Legend_select_Y_end = m_WorkSpace_Y_start + (double)(count - m_Legend_Shift + 1) * m_Legend_dY + double(buffer_y1) + radius1; if ((m_Legend_select_Y_end + m_Legend_dY) > (m_WorkSpace_Y_end - double(buffer_y1) - radius1)){ break; } } dc.SetFont(m_font_standart); } //----Draw background, axis(lines), text(01-Jan-1980)---- void CPaintStatistics::DrawAxis(wxDC &dc, const double max_val_y, const double min_val_y, const double max_val_x, const double min_val_x, wxColour pen_AxisColour, const double max_val_y_all, const double min_val_y_all) { wxCoord x0 = wxCoord(m_WorkSpace_X_start); wxCoord y0 = wxCoord(m_WorkSpace_Y_start); wxCoord w0 = wxCoord(m_WorkSpace_X_end - m_WorkSpace_X_start); wxCoord h0 = wxCoord(m_WorkSpace_Y_end - m_WorkSpace_Y_start); wxCoord x1 = 0; wxCoord y1 = 0; if (x0 < 0) x0 = 0; if (y0 < 0) y0 = 0; if (w0 < 0) w0 = 0; if (h0 < 0) h0 = 0; dc.SetClippingRegion(x0, y0, w0, h0); dc.SetBrush(wxBrush(m_brush_AxisColour , wxSOLID)); dc.SetPen(wxPen(pen_AxisColour , 1 , wxSOLID)); wxCoord w_temp, h_temp, des_temp, lead_temp; wxCoord w_temp2; dc.GetTextExtent(wxString::Format(wxT(" %s"), format_number(max_val_y_all, 2)), &w_temp, &h_temp, &des_temp, &lead_temp); dc.GetTextExtent(wxString::Format(wxT(" %s"), format_number(min_val_y_all, 2)), &w_temp2, &h_temp, &des_temp, &lead_temp); if (w_temp < w_temp2) w_temp = w_temp2; m_WorkSpace_X_start += double(w_temp) + 3.0; m_WorkSpace_Y_end -= double(h_temp) + 3.0; dc.GetTextExtent(wxT("0"), &w_temp, &h_temp, &des_temp, &lead_temp); m_WorkSpace_X_end -= 3.0;//w_temp; const double radius1 = 5.0;//(double)(h_temp/2.0); double d_y = (double)(h_temp) / 2.0; if (d_y < 5.0) d_y = 5.0; wxDateTime dtTemp1; wxString strBuffer1; dtTemp1.Set((time_t)max_val_x); strBuffer1 = dtTemp1.Format(wxT("%d.%b.%y"), wxDateTime::GMT0); dc.GetTextExtent(strBuffer1, &w_temp, &h_temp, &des_temp, &lead_temp); double d_x = (double)(w_temp) / 2.0; // Draw background graph x0 = wxCoord(m_WorkSpace_X_start); y0 = wxCoord(m_WorkSpace_Y_start); w0 = wxCoord(m_WorkSpace_X_end - m_WorkSpace_X_start); h0 = wxCoord(m_WorkSpace_Y_end - m_WorkSpace_Y_start); if (x0 < 0) x0 = 0; if (y0 < 0) y0 = 0; if (w0 < 0) w0 = 0; if (h0 < 0) h0 = 0; dc.DrawRoundedRectangle(x0, y0, w0, h0, radius1); m_Graph_X_start = m_WorkSpace_X_start; //x0; m_Graph_X_end = m_WorkSpace_X_end; //x0 + w0; m_Graph_Y_start = m_WorkSpace_Y_start; //y0; m_Graph_Y_end = m_WorkSpace_Y_end; //y0 + h0; m_WorkSpace_X_start += d_x; m_WorkSpace_X_end -= d_x; m_WorkSpace_Y_start += d_y; m_WorkSpace_Y_end -= d_y; if (m_WorkSpace_X_end < m_WorkSpace_X_start) m_WorkSpace_X_start = m_WorkSpace_X_end = (m_WorkSpace_X_end + m_WorkSpace_X_start) / 2.0; if (m_WorkSpace_Y_end < m_WorkSpace_Y_start) m_WorkSpace_Y_start = m_WorkSpace_Y_end = (m_WorkSpace_Y_end + m_WorkSpace_Y_start) / 2.0; m_Graph_draw_X_start = m_WorkSpace_X_start; m_Graph_draw_X_end = m_WorkSpace_X_end; m_Graph_draw_Y_start = m_WorkSpace_Y_start; m_Graph_draw_Y_end = m_WorkSpace_Y_end; // A B AB(m_WorkSpace_X_start, m_WorkSpace_Y_end, m_WorkSpace_X_end, m_WorkSpace_Y_start, min_val_x, min_val_y, max_val_x, max_val_y); //Draw val and lines dc.SetPen(wxPen(m_pen_AxisYColour , 1 , wxDOT)); dc.SetTextForeground (m_pen_AxisYTextColour); int d_oy_count = 1; if (h_temp > 0) d_oy_count = (int)ceil((m_WorkSpace_Y_end - m_WorkSpace_Y_start) / ( 2.0 * double(h_temp))); if (d_oy_count <= 0) d_oy_count = 1; double d_oy_val = fabs((max_val_y - min_val_y) / double(d_oy_count)); double d2 = pow(double(10.0) , floor(log10(d_oy_val))); if (d2 >= d_oy_val){ d_oy_val = 1.0 * d2; } else if (2.0 * d2 >= d_oy_val){ d_oy_val = 2.0 * d2; } else if (5.0 * d2 >= d_oy_val){ d_oy_val = 5.0 * d2; } else { d_oy_val = 10.0 * d2; } if (0 == d_oy_val) d_oy_val = 0.01; double y_start_val = ceil(min_val_y / d_oy_val) * d_oy_val; d_oy_count = (int)floor((max_val_y - y_start_val) / d_oy_val); for (double ny = 0; ny <= double(d_oy_count); ++ny){ dc.GetTextExtent(wxString::Format(wxT("%s"), format_number(y_start_val + ny * d_oy_val, 2)), &w_temp, &h_temp, &des_temp, &lead_temp); x0 = wxCoord(m_Graph_X_start + 1.0); y0 = wxCoord(m_Ay_ValToCoord * (y_start_val + ny * d_oy_val) + m_By_ValToCoord); x1 = wxCoord(m_Graph_X_end - 1.0); if ((y0 >= wxCoord(m_WorkSpace_Y_start)) && (y0 <= wxCoord(m_WorkSpace_Y_end))){ if (x0 < 0) x0 = 0; if (y0 < 0) y0 = 0; if (x1 < 0) x1 = 0; dc.DrawLine(x0, y0, x1, y0); x0 = wxCoord(m_Graph_X_start - 2.0) - w_temp; y0 = wxCoord(m_Ay_ValToCoord * (y_start_val + ny * d_oy_val) + m_By_ValToCoord - double(h_temp) / 2.0); if (x0 < 0) x0 = 0; if (y0 < 0) y0 = 0; dc.DrawText(wxString::Format(wxT("%s"), format_number(y_start_val + ny * d_oy_val, 2)), x0, y0); } } //Draw day numbers and lines marking the days dc.SetPen(wxPen(m_pen_AxisXColour , 1 , wxDOT)); dc.SetTextForeground (m_pen_AxisXTextColour); dtTemp1.Set((time_t)max_val_x); strBuffer1 = dtTemp1.Format(wxT("%d.%b.%y"), wxDateTime::GMT0); dc.GetTextExtent(strBuffer1, &w_temp, &h_temp, &des_temp, &lead_temp); int d_ox_count = 1; if (w_temp > 0) d_ox_count = (int)((m_WorkSpace_X_end - m_WorkSpace_X_start) / (1.2 * double(w_temp))); if (d_ox_count <= 0) d_ox_count = 1; double d_ox_val = ceil(((double)(max_val_x - min_val_x) / double(d_ox_count)) / 86400.0) * 86400.0; if (0 == d_ox_val) d_ox_val = 1; double x_start_val = ceil(min_val_x / 86400.0) * 86400.0; d_ox_count = (int)floor((max_val_x - x_start_val) / d_ox_val); for (double nx = 0; nx <= double(d_ox_count); ++nx){ dtTemp1.Set((time_t)(x_start_val + nx * d_ox_val)); strBuffer1 = dtTemp1.Format(wxT("%d.%b.%y"), wxDateTime::GMT0); dc.GetTextExtent(strBuffer1, &w_temp, &h_temp, &des_temp, &lead_temp); x0 = wxCoord(m_Ax_ValToCoord * (x_start_val + nx * d_ox_val) + m_Bx_ValToCoord); y0 = wxCoord(m_Graph_Y_start + 1.0); y1 = wxCoord(m_Graph_Y_end - 1.0); if ((x0 <= wxCoord(m_WorkSpace_X_end)) && (x0 >= wxCoord(m_WorkSpace_X_start))){ if (x0 < 0) x0 = 0; if (y0 < 0) y0 = 0; if (y1 < 0) y1 = 0; dc.DrawLine(x0, y0, x0, y1); x0 = wxCoord(m_Ax_ValToCoord * (x_start_val + nx * d_ox_val) + m_Bx_ValToCoord - (double(w_temp) / 2.0)); y0 = (wxCoord)m_Graph_Y_end; if (x0 < 0) x0 = 0; if (y0 < 0) y0 = 0; dc.DrawText(strBuffer1, x0, y0); } } dc.DestroyClippingRegion(); } //----Draw graph---- void CPaintStatistics::DrawGraph(wxDC &dc, std::vector<PROJECT*>::const_iterator &i, const wxColour graphColour, const int typePoint, const int selectedStatistic) { std::vector<DAILY_STATS> stats = (*i)->statistics; DrawGraph2(dc, stats, graphColour, typePoint, selectedStatistic); } void CPaintStatistics::DrawGraph2(wxDC &dc, std::vector<DAILY_STATS> stats, const wxColour graphColour, const int typePoint, const int selectedStatistic) { wxCoord x0 = wxCoord(m_Graph_X_start); wxCoord y0 = wxCoord(m_Graph_Y_start); wxCoord w0 = wxCoord(m_Graph_X_end - m_Graph_X_start); wxCoord h0 = wxCoord(m_Graph_Y_end - m_Graph_Y_start); if (x0 < 0) x0 = 0; if (y0 < 0) y0 = 0; if (w0 < 0) w0 = 0; if (h0 < 0) h0 = 0; dc.SetClippingRegion(x0, y0, w0, h0); dc.SetPen(wxPen(graphColour , m_GraphLineWidth , wxSOLID)); wxCoord last_x = 0; wxCoord last_y = 0; wxCoord xpos = 0; wxCoord ypos = 0; double d_last_x = 0; double d_last_y = 0; bool last_point_in = false; double d_xpos = 0; double d_ypos = 0; bool point_in = false; bool b_point1 = false; bool b_point2 = false; // cross double d_cross_x1 = 0; double d_cross_y1 = 0; // first point (no line) bool first_point = true; // end point double d_end_point_x = 0; double d_end_point_y = 0; bool end_point = false; // for (std::vector<DAILY_STATS>::const_iterator j = stats.begin(); j != stats.end(); ++j) { double d_x1 = 0; double d_y1 = 0; double d_x2 = 0; double d_y2 = 0; double d_min1 = 0; double d_max1 = 0; double d_min2 = 0; double d_max2 = 0; b_point1 = false; b_point2 = false; d_xpos = (m_Ax_ValToCoord * j->day + m_Bx_ValToCoord);// äîáàâèòü îêðóãëåíèå switch (selectedStatistic){ // äîáàâèòü îêðóãëåíèå case show_user_total: d_ypos = (m_Ay_ValToCoord * j->user_total_credit + m_By_ValToCoord); break; case show_user_average: d_ypos = (m_Ay_ValToCoord * j->user_expavg_credit + m_By_ValToCoord); break; case show_host_total: d_ypos = (m_Ay_ValToCoord * j->host_total_credit + m_By_ValToCoord); break; case show_host_average: d_ypos = (m_Ay_ValToCoord * j->host_expavg_credit + m_By_ValToCoord); break; default:d_ypos = (m_Ay_ValToCoord * j->user_total_credit + m_By_ValToCoord); break; } if (first_point) { if ((d_xpos < m_Graph_X_start) || (d_xpos > m_Graph_X_end) || (d_ypos < m_Graph_Y_start) || (d_ypos > m_Graph_Y_end)){ point_in = false; b_point2 = false; end_point = false; }else { point_in = true; d_x2 = d_xpos; d_y2 = d_ypos; b_point2 = true; d_end_point_x = d_xpos; d_end_point_y = d_ypos; end_point = true; } first_point = false; }else { dc.SetPen(wxPen(graphColour , m_GraphLineWidth , wxSOLID)); // ïðîâåðêà ïîïàäàíèÿ ïåðâîé òî÷êè ëèíèè â îáëàñòü ðèñîâàíèÿ if (last_point_in){ d_x1 = d_last_x; d_y1 = d_last_y; b_point1 = true; }else b_point1 = false; // ïðîâåðêà ïîïàäàíèÿ âòîðîé òî÷êè ëèíèè â îáëàñòü ðèñîâàíèÿ if ((d_xpos < m_Graph_X_start) || (d_xpos > m_Graph_X_end) || (d_ypos < m_Graph_Y_start) || (d_ypos > m_Graph_Y_end)){ point_in = false; b_point2 = false; }else { point_in = true; d_x2 = d_xpos; d_y2 = d_ypos; b_point2 = true; } // Èùåì òî÷êó âõîäà ëèíèè â îáëàñòü ðèñîâàíèÿ (1) x=const if (!b_point1 || !b_point2){ if (CrossTwoLine(d_last_x, d_last_y, d_xpos, d_ypos, m_Graph_X_start, m_Graph_Y_end, m_Graph_X_start, m_Graph_Y_start, d_cross_x1, d_cross_y1)){ if (d_last_x > d_xpos){ d_min1 = d_xpos; d_max1 = d_last_x; }else{ d_max1 = d_xpos; d_min1 = d_last_x; } if (m_Graph_Y_end > m_Graph_Y_start){ d_min2 = m_Graph_Y_start; d_max2 = m_Graph_Y_end; }else{ d_max2 = m_Graph_Y_end; d_min2 = m_Graph_Y_start; } if ((d_cross_x1 <= d_max1) && (d_cross_x1 >= d_min1) && (d_cross_y1 <= d_max2) && (d_cross_y1 >= d_min2)){ if (!b_point1){ d_x1 = d_cross_x1; d_y1 = d_cross_y1; b_point1 = true; } else if (!b_point2){ d_x2 = d_cross_x1; d_y2 = d_cross_y1; b_point2 = true; } } } } // Èùåì òî÷êó âõîäà ëèíèè â îáëàñòü ðèñîâàíèÿ (2) x=const if (!b_point1 || !b_point2){ if (CrossTwoLine(d_last_x, d_last_y, d_xpos, d_ypos, m_Graph_X_end, m_Graph_Y_end, m_Graph_X_end, m_Graph_Y_start, d_cross_x1, d_cross_y1)){ if (d_last_x > d_xpos){ d_min1 = d_xpos; d_max1 = d_last_x; }else{ d_max1 = d_xpos; d_min1 = d_last_x; } if (m_Graph_Y_end > m_Graph_Y_start){ d_min2 = m_Graph_Y_start; d_max2 = m_Graph_Y_end; }else{ d_max2 = m_Graph_Y_end; d_min2 = m_Graph_Y_start; } if ((d_cross_x1 <= d_max1) && (d_cross_x1 >= d_min1) && (d_cross_y1 <= d_max2) && (d_cross_y1 >= d_min2)){ if (!b_point1){ d_x1 = d_cross_x1; d_y1 = d_cross_y1; b_point1 = true; } else if (!b_point2){ d_x2 = d_cross_x1; d_y2 = d_cross_y1; b_point2 = true; } } } } // Èùåì òî÷êó âõîäà ëèíèè â îáëàñòü ðèñîâàíèÿ (3) y=const if (!b_point1 || !b_point2){ if (CrossTwoLine(d_last_x, d_last_y, d_xpos, d_ypos, m_Graph_X_start, m_Graph_Y_start, m_Graph_X_end, m_Graph_Y_start, d_cross_x1, d_cross_y1)){ if (d_last_y > d_ypos){ d_min1 = d_ypos; d_max1 = d_last_y; }else{ d_max1 = d_ypos; d_min1 = d_last_y; } if (m_Graph_X_end > m_Graph_X_start){ d_min2 = m_Graph_X_start; d_max2 = m_Graph_X_end; }else{ d_max2 = m_Graph_X_end; d_min2 = m_Graph_X_start; } if ((d_cross_y1 <= d_max1) && (d_cross_y1 >= d_min1) && (d_cross_x1 <= d_max2) && (d_cross_x1 >= d_min2)){ if (!b_point1){ d_x1 = d_cross_x1; d_y1 = d_cross_y1; b_point1 = true; } else if (!b_point2){ d_x2 = d_cross_x1; d_y2 = d_cross_y1; b_point2 = true; } } } } // Èùåì òî÷êó âõîäà ëèíèè â îáëàñòü ðèñîâàíèÿ (4) y=const if (!b_point1 || !b_point2){ if (CrossTwoLine(d_last_x, d_last_y, d_xpos, d_ypos, m_Graph_X_start, m_Graph_Y_end, m_Graph_X_end, m_Graph_Y_end, d_cross_x1, d_cross_y1)){ if (d_last_y > d_ypos){ d_min1 = d_ypos; d_max1 = d_last_y; }else{ d_max1 = d_ypos; d_min1 = d_last_y; } if (m_Graph_X_end > m_Graph_X_start){ d_min2 = m_Graph_X_start; d_max2 = m_Graph_X_end; }else{ d_max2 = m_Graph_X_end; d_min2 = m_Graph_X_start; } if ((d_cross_y1 <= d_max1) && (d_cross_y1 >= d_min1) && (d_cross_x1 <= d_max2) && (d_cross_x1 >= d_min2)){ if (!b_point1){ d_x1 = d_cross_x1; d_y1 = d_cross_y1; b_point1 = true; } else if (!b_point2){ d_x2 = d_cross_x1; d_y2 = d_cross_y1; b_point2 = true; } } } } if (b_point1 && b_point2){ last_x = wxCoord(d_x1); last_y = wxCoord(d_y1); xpos = wxCoord(d_x2); ypos = wxCoord(d_y2); if (last_x > (wxCoord)m_Graph_X_end) last_x = (wxCoord)m_Graph_X_end; if (last_x < 0) last_x = 0; if (last_y > (wxCoord)m_Graph_Y_end) last_y = (wxCoord)m_Graph_Y_end; if (last_y < 0) last_y = 0; if (xpos > (wxCoord)m_Graph_X_end) xpos = (wxCoord)m_Graph_X_end; if (xpos < 0) xpos = 0; if (ypos > (wxCoord)m_Graph_Y_end) ypos = (wxCoord)m_Graph_Y_end; if (ypos < 0) ypos = 0; dc.DrawLine(last_x, last_y, xpos, ypos); if (last_point_in) myDrawPoint(dc, last_x, last_y, graphColour, typePoint ,m_GraphPointWidth); if (point_in){ d_end_point_x = d_xpos; d_end_point_y = d_ypos; end_point = true; }else end_point = false; }else end_point = false; } d_last_x = d_xpos; d_last_y = d_ypos; last_point_in = point_in; } // draw last point if (end_point){ xpos = wxCoord(d_end_point_x); ypos = wxCoord(d_end_point_y); if (xpos > (wxCoord)m_Graph_X_end) xpos = (wxCoord)m_Graph_X_end; if (xpos < 0) xpos = 0; if (ypos > (wxCoord)m_Graph_Y_end) ypos = (wxCoord)m_Graph_Y_end; if (ypos < 0) ypos = 0; myDrawPoint(dc, xpos, ypos, graphColour, typePoint ,m_GraphPointWidth); } dc.DestroyClippingRegion(); } //----Draw marker---- void CPaintStatistics::DrawMarker(wxDC &dc) { if (m_GraphMarker1){ wxCoord x0 = wxCoord(m_Graph_X_start); wxCoord y0 = wxCoord(m_Graph_Y_start); wxCoord w0 = wxCoord(m_Graph_X_end - m_Graph_X_start); wxCoord h0 = wxCoord(m_Graph_Y_end - m_Graph_Y_start); if (x0 < 0) x0 = 0; if (y0 < 0) y0 = 0; if (w0 < 0) w0 = 0; if (h0 < 0) h0 = 0; dc.SetClippingRegion(x0, y0, w0, h0); dc.SetPen(wxPen(m_pen_MarkerLineColour , 1 , wxSOLID)); wxCoord x00 = wxCoord(m_Ax_ValToCoord * m_GraphMarker_X1 + m_Bx_ValToCoord); wxCoord y00 = wxCoord(m_Ay_ValToCoord * m_GraphMarker_Y1 + m_By_ValToCoord); if (x00 < 0) x00 = 0; if (y00 < 0) y00 = 0; if ((x00 < wxCoord(m_Graph_X_start)) || (x00 > wxCoord(m_Graph_X_end)) || (y00 < wxCoord(m_Graph_Y_start)) || (y00 > wxCoord(m_Graph_Y_end))){ }else{ dc.CrossHair(x00, y00); wxDateTime dtTemp1; wxString strBuffer1; dtTemp1.Set((time_t)m_GraphMarker_X1); strBuffer1=dtTemp1.Format(wxT("%d.%b.%y"), wxDateTime::GMT0); dc.SetFont(m_font_bold); dc.SetTextBackground (m_brush_AxisColour); dc.SetBackgroundMode(wxSOLID); x0 += 2; y0 += 2; x00 += 2; y00 += 2; if (x00 < 0) x00 = 0; if (y00 < 0) y00 = 0; if (x0 < 0) x0 = 0; if (y0 < 0) y0 = 0; dc.SetTextForeground (m_pen_AxisYTextColour); dc.DrawText(wxString::Format(wxT("%s"), format_number(m_GraphMarker_Y1, 2)) , x0, y00); dc.SetTextForeground (m_pen_AxisXTextColour); dc.DrawText(strBuffer1 ,x00, y0); dc.SetBackgroundMode(wxTRANSPARENT); } dc.DestroyClippingRegion(); } } //-------- Draw All --------- void CPaintStatistics::DrawAll(wxDC &dc) { //Init global CMainDocument* pDoc = wxGetApp().GetDocument(); wxASSERT(pDoc); wxASSERT(wxDynamicCast(pDoc, CMainDocument)); PROJECTS *proj = &(pDoc->statistics_status); wxASSERT(proj); m_WorkSpace_X_start = m_main_X_start; m_WorkSpace_X_end = m_main_X_end; m_WorkSpace_Y_start = m_main_Y_start; m_WorkSpace_Y_end = m_main_Y_end; dc.SetBackground(m_brush_MainColour); // dc.SetTextForeground (GetForegroundColour ()); dc.SetTextForeground (m_pen_HeadTextColour); dc.SetTextBackground (GetBackgroundColour ()); // The next 3 lines seem unnecessary and cause problems // when monitor dpi is set to 125% of normal on MS Windows. // m_font_standart = dc.GetFont(); // m_font_bold = dc.GetFont(); // m_font_standart_italic = dc.GetFont(); m_font_standart.SetWeight(wxNORMAL); m_font_bold.SetWeight(wxBOLD); // m_font_standart_italic.SetFaceName(_T("Verdana")); m_font_standart_italic.SetStyle(wxFONTSTYLE_ITALIC); dc.SetFont(m_font_standart); //Start drawing dc.Clear(); dc.SetBrush(wxBrush(m_brush_MainColour , wxSOLID)); dc.SetPen(wxPen(m_pen_MainColour , 1 , wxSOLID)); wxCoord x0 = wxCoord(m_main_X_start); wxCoord y0 = wxCoord(m_main_Y_start); wxCoord w0 = wxCoord(m_main_X_end - m_main_X_start); wxCoord h0 = wxCoord(m_main_Y_end - m_main_Y_start); if (x0 < 0) x0 = 0; if (y0 < 0) y0 = 0; if (w0 < 0) w0 = 0; if (h0 < 0) h0 = 0; dc.SetBrush(wxBrush(m_brush_MainColour , wxSOLID)); dc.SetPen(wxPen(m_pen_MainColour , 1 , wxSOLID)); dc.DrawRectangle(x0, y0, w0, h0); //Number of Projects int nb_proj = 0; for (std::vector<PROJECT*>::const_iterator i = proj->projects.begin(); i != proj->projects.end(); ++i) { ++nb_proj; } if (0 == nb_proj) { dc.DrawRectangle(x0, y0, w0, h0); return; } // Check m_NextProjectStatistic if (m_NextProjectStatistic < 0) m_NextProjectStatistic = nb_proj - 1; if ((m_NextProjectStatistic < 0) || (m_NextProjectStatistic >= nb_proj)) m_NextProjectStatistic = 0; // Initial coord switch (m_SelectedStatistic){ case show_user_total: heading = _("User Total"); break; case show_user_average: heading = _("User Average"); break; case show_host_total: heading = _("Host Total"); break; case show_host_average: heading = _("Host Average"); break; default:heading = wxT(""); } if (!m_LegendDraw) { m_scrollBar->Hide(); m_Space_for_scrollbar = 0; } switch (m_ModeViewStatistic){ case mode_all_separate: { //Draw Legend if (m_ViewHideProjectStatistic >= 0){ int count = -1; std::set<wxString>::iterator s; for (std::vector<PROJECT*>::const_iterator i = proj->projects.begin(); i != proj->projects.end(); ++i) { ++count; if (m_ViewHideProjectStatistic == count){ s = m_HideProjectStatistic.find( wxString((*i)->master_url, wxConvUTF8) ); if (s != m_HideProjectStatistic.end()){ m_HideProjectStatistic.erase(s); } else { m_HideProjectStatistic.insert(wxString((*i)->master_url, wxConvUTF8)); } break; } } } m_ViewHideProjectStatistic = -1; if (m_LegendDraw) DrawLegend(dc, proj, pDoc, -1, false, m_Legend_Shift_Mode2); ///Draw heading dc.SetFont(m_font_bold); DrawMainHead(dc, heading); dc.SetFont(m_font_standart); //How many rows/colums? int nb_proj_show = 0; for (std::vector<PROJECT*>::const_iterator i = proj->projects.begin(); i != proj->projects.end(); ++i) { if (!(m_HideProjectStatistic.count( wxString((*i)->master_url, wxConvUTF8) ))){ ++nb_proj_show; } } // int nb_proj_row = 0, nb_proj_col = 0; if (nb_proj_show < 4) { nb_proj_col = 1; nb_proj_row = nb_proj_show; } else { nb_proj_col = 2; nb_proj_row = (int)ceil(double(nb_proj_show) / double(nb_proj_col)); } int col = 1, row = 1; //Used to identify the actual row/col double rectangle_x_start = m_WorkSpace_X_start; double rectangle_x_end = m_WorkSpace_X_end; double rectangle_y_start = m_WorkSpace_Y_start; double rectangle_y_end = m_WorkSpace_Y_end; if (0 == nb_proj_col) nb_proj_col = 1; if (0 == nb_proj_row) nb_proj_row = 1; const double x_fac = (rectangle_x_end - rectangle_x_start) / double(nb_proj_col); const double y_fac = (rectangle_y_end - rectangle_y_start) / double(nb_proj_row); double min_val_y_all = 10e32, max_val_y_all = 0; double min_val_x_all = 10e32, max_val_x_all = 0; for (std::vector<PROJECT*>::const_iterator i = proj->projects.begin(); i != proj->projects.end(); ++i) { if (!(m_HideProjectStatistic.count( wxString((*i)->master_url, wxConvUTF8) ))){ MinMaxDayCredit(i, min_val_y_all, max_val_y_all, min_val_x_all, max_val_x_all, m_SelectedStatistic, false); } } for (std::vector<PROJECT*>::const_iterator i = proj->projects.begin(); i != proj->projects.end(); ++i) { if (!(m_HideProjectStatistic.count( wxString((*i)->master_url, wxConvUTF8) ))){ //Find minimum/maximum value double min_val_y = 10e32, max_val_y = 0; double min_val_x = 10e32, max_val_x = 0; MinMaxDayCredit(i, min_val_y, max_val_y, min_val_x, max_val_x, m_SelectedStatistic); CheckMinMaxD(min_val_x, max_val_x); CheckMinMaxD(min_val_y, max_val_y); min_val_x = floor(min_val_x / 86400.0) * 86400.0; max_val_x = ceil(max_val_x / 86400.0) * 86400.0; //Where do we draw in? ClearXY(); m_main_X_start = (wxCoord)(rectangle_x_start + x_fac * (double)(col - 1)); m_main_X_end = (wxCoord)(rectangle_x_start + x_fac * ((double)col)); m_main_Y_start = (wxCoord)(rectangle_y_start + y_fac * (double)(row - 1)); m_main_Y_end = (wxCoord)(rectangle_y_start + y_fac * (double)row); if (m_main_X_start < 0) m_main_X_start = 0; if (m_main_X_start > m_main_X_end) m_main_X_end = m_main_X_start; if (m_main_Y_start < 0) m_main_Y_start = 0; if (m_main_Y_start > m_main_Y_end) m_main_Y_end = m_main_Y_start; m_WorkSpace_X_start = m_main_X_start; m_WorkSpace_X_end = m_main_X_end; m_WorkSpace_Y_start = m_main_Y_start; m_WorkSpace_Y_end = m_main_Y_end; //Draw scale Draw Project name wxString head_name = wxT("?"); PROJECT* state_project = pDoc->state.lookup_project((*i)->master_url); if (state_project) { head_name = wxString(state_project->project_name.c_str(), wxConvUTF8); } //Draw heading DrawMainHead(dc, head_name); //Draw axis DrawAxis(dc, max_val_y, min_val_y,max_val_x, min_val_x, m_pen_AxisColour, max_val_y_all, min_val_y_all); //Draw graph wxColour graphColour=wxColour(0,0,0); color_cycle(m_SelectedStatistic, n_command_buttons, graphColour); DrawGraph(dc, i, graphColour, 0, m_SelectedStatistic); //Change row/col if (col == nb_proj_col) { col = 1; ++row; } else { ++col; } } } break; } case mode_one_project: { //Draw Legend if (m_LegendDraw) DrawLegend(dc, proj, pDoc, m_NextProjectStatistic, false, m_Legend_Shift_Mode1); //Draw heading dc.SetFont(m_font_bold); DrawMainHead(dc, heading); dc.SetFont(m_font_standart); //Draw project int count = -1; for (std::vector<PROJECT*>::const_iterator i = proj->projects.begin(); i != proj->projects.end(); ++i) { ++count; if (count != m_NextProjectStatistic) continue; //Find minimum/maximum value double min_val_y = 10e32, max_val_y = 0; double min_val_x = 10e32, max_val_x = 0; MinMaxDayCredit(i, min_val_y, max_val_y, min_val_x, max_val_x, m_SelectedStatistic); double t_n1 = dtime(); double t_d1 = floor((t_n1 - max_val_x) / 86400.0); wxString head_name=wxString::Format(_("Last update: %.0f days ago"), t_d1); wxColour pen_AxisColour1 = m_pen_AxisColourAutoZoom; if (m_Zoom_Auto){ min_val_x = floor(min_val_x / 86400.0) * 86400.0; max_val_x = ceil(max_val_x / 86400.0) * 86400.0; }else{ pen_AxisColour1 = m_pen_AxisColourZoom; min_val_x = m_Zoom_min_val_X; max_val_x = m_Zoom_max_val_X; min_val_y = m_Zoom_min_val_Y; max_val_y = m_Zoom_max_val_Y; } CheckMinMaxD(min_val_x, max_val_x); CheckMinMaxD(min_val_y, max_val_y); // Draw heading PROJECT* state_project = pDoc->state.lookup_project((*i)->master_url); if (state_project) { dc.SetFont(m_font_standart_italic); DrawProjectHead(dc, state_project, head_name); dc.SetFont(m_font_standart); } m_Zoom_min_val_X = min_val_x; m_Zoom_max_val_X = max_val_x; m_Zoom_min_val_Y = min_val_y; m_Zoom_max_val_Y = max_val_y; // Draw axis DrawAxis(dc, max_val_y, min_val_y, max_val_x, min_val_x, pen_AxisColour1, max_val_y, min_val_y); // Draw graph wxColour graphColour=wxColour(0,0,0); color_cycle(m_SelectedStatistic, n_command_buttons, graphColour); DrawGraph(dc, i, graphColour, 0, m_SelectedStatistic); // Draw marker DrawMarker(dc); break; } break; } case mode_all_together: { //Draw Legend if (m_ViewHideProjectStatistic >= 0){ int count = -1; std::set<wxString>::iterator s; for (std::vector<PROJECT*>::const_iterator i = proj->projects.begin(); i != proj->projects.end(); ++i) { ++count; if (m_ViewHideProjectStatistic == count){ s = m_HideProjectStatistic.find( wxString((*i)->master_url, wxConvUTF8) ); if (s != m_HideProjectStatistic.end()){ m_HideProjectStatistic.erase(s); }else m_HideProjectStatistic.insert( wxString((*i)->master_url, wxConvUTF8) ); break; } } } m_ViewHideProjectStatistic = -1; if (m_LegendDraw) DrawLegend(dc, proj, pDoc, -1, true, m_Legend_Shift_Mode2); //Draw heading dc.SetFont(m_font_bold); DrawMainHead(dc, heading); dc.SetFont(m_font_standart); //Find minimum/maximum value double min_val_y = 10e32, max_val_y = 0; double min_val_x = 10e32, max_val_x = 0; wxColour pen_AxisColour1 = m_pen_AxisColourAutoZoom; if (m_Zoom_Auto){ for (std::vector<PROJECT*>::const_iterator i = proj->projects.begin(); i != proj->projects.end(); ++i) { if (!(m_HideProjectStatistic.count( wxString((*i)->master_url, wxConvUTF8) ))){ MinMaxDayCredit(i, min_val_y, max_val_y, min_val_x, max_val_x, m_SelectedStatistic, false); } } min_val_x = floor(min_val_x / 86400.0) * 86400.0; max_val_x = ceil(max_val_x / 86400.0) * 86400.0; }else{ pen_AxisColour1 = m_pen_AxisColourZoom; min_val_x = m_Zoom_min_val_X; max_val_x = m_Zoom_max_val_X; min_val_y = m_Zoom_min_val_Y; max_val_y = m_Zoom_max_val_Y; } CheckMinMaxD(min_val_x, max_val_x); CheckMinMaxD(min_val_y, max_val_y); m_Zoom_min_val_X = min_val_x; m_Zoom_max_val_X = max_val_x; m_Zoom_min_val_Y = min_val_y; m_Zoom_max_val_Y = max_val_y; //Draw axis DrawAxis(dc, max_val_y, min_val_y, max_val_x, min_val_x, pen_AxisColour1, max_val_y, min_val_y); //Draw graph int count = -1; for (std::vector<PROJECT*>::const_iterator i = proj->projects.begin(); i != proj->projects.end(); ++i) { ++count; if (!(m_HideProjectStatistic.count( wxString((*i)->master_url, wxConvUTF8) ))){ wxColour graphColour = wxColour(0,0,0); int typePoint = 0; getTypePoint(typePoint,count); color_cycle(count, proj->projects.size(), graphColour); DrawGraph(dc, i, graphColour, typePoint, m_SelectedStatistic); } } //Draw marker DrawMarker(dc); break; } case mode_sum: { //Draw Legend if (m_ViewHideProjectStatistic >= 0){ int count = -1; std::set<wxString>::iterator s; for (std::vector<PROJECT*>::const_iterator i = proj->projects.begin(); i != proj->projects.end(); ++i) { ++count; if (m_ViewHideProjectStatistic == count){ s = m_HideProjectStatistic.find( wxString((*i)->master_url, wxConvUTF8) ); if (s != m_HideProjectStatistic.end()){ m_HideProjectStatistic.erase(s); }else m_HideProjectStatistic.insert( wxString((*i)->master_url, wxConvUTF8) ); break; } } } m_ViewHideProjectStatistic = -1; if (m_LegendDraw) DrawLegend(dc, proj, pDoc, -1, true, m_Legend_Shift_Mode2); //Draw heading dc.SetFont(m_font_bold); DrawMainHead(dc, heading); dc.SetFont(m_font_standart); //Find minimum/maximum value double min_val_y = 10e32, max_val_y = 0; double min_val_x = 10e32, max_val_x = 0; double min_total_y = 0; double max_total_y = 0; wxColour pen_AxisColour1 = m_pen_AxisColourAutoZoom; if (m_Zoom_Auto){ for (std::vector<PROJECT*>::const_iterator i = proj->projects.begin(); i != proj->projects.end(); ++i) { if (!(m_HideProjectStatistic.count( wxString((*i)->master_url, wxConvUTF8) ))){ MinMaxDayCredit(i, min_val_y, max_val_y, min_val_x, max_val_x, m_SelectedStatistic, false); min_total_y += min_val_y; max_total_y += max_val_y; min_val_y = 10e32; max_val_y = 0; } } // Start graph 30 days before today min_val_x = dday() - (30*86400); max_val_x = ceil(max_val_x / 86400.0) * 86400.0; min_val_y = min_total_y; max_val_y = max_total_y; }else{ pen_AxisColour1 = m_pen_AxisColourZoom; min_val_x = m_Zoom_min_val_X; max_val_x = m_Zoom_max_val_X; min_val_y = m_Zoom_min_val_Y; max_val_y = m_Zoom_max_val_Y; } CheckMinMaxD(min_val_x, max_val_x); CheckMinMaxD(min_val_y, max_val_y); m_Zoom_min_val_X = min_val_x; m_Zoom_max_val_X = max_val_x; m_Zoom_min_val_Y = min_val_y; m_Zoom_max_val_Y = max_val_y; //Draw axis DrawAxis(dc, max_val_y, min_val_y, max_val_x, min_val_x, pen_AxisColour1, max_val_y, min_val_y); // Generate summed data DAILY_STATS stat, saved_sum_stat, prev_proj_stat; std::vector<DAILY_STATS> sumstats; stat.user_total_credit = 0.0; stat.user_expavg_credit = 0.0; stat.host_total_credit = 0.0; stat.host_expavg_credit = 0.0; stat.day = min_val_x; sumstats.push_back(stat); stat.day = max_val_x; sumstats.push_back(stat); int count = -1; for (std::vector<PROJECT*>::const_iterator i = proj->projects.begin(); i != proj->projects.end(); ++i) { ++count; if (m_HideProjectStatistic.count( wxString((*i)->master_url, wxConvUTF8) )) continue; saved_sum_stat.user_total_credit = 0.0; saved_sum_stat.user_expavg_credit = 0.0; saved_sum_stat.host_total_credit = 0.0; saved_sum_stat.host_expavg_credit = 0.0; saved_sum_stat.day = 0.0; prev_proj_stat = saved_sum_stat; if (sumstats.size() && (*i)->statistics.size()) { std::vector<DAILY_STATS>::iterator sum_iter = sumstats.begin(); std::vector<DAILY_STATS>::const_iterator proj_iter = (*i)->statistics.begin(); for (;;) { if ((*proj_iter).day >= min_val_x) { if ((*proj_iter).day < (*sum_iter).day) { sum_iter = sumstats.insert(sum_iter, stat); *sum_iter = saved_sum_stat; (*sum_iter).day = (*proj_iter).day; } else { saved_sum_stat = *sum_iter; } if ((*proj_iter).day > (*sum_iter).day) { AddToStats(prev_proj_stat, *sum_iter); } else { AddToStats(*proj_iter, *sum_iter); } ++sum_iter; if (sum_iter == sumstats.end()) { break; } } if ((*proj_iter).day <= (*sum_iter).day) { prev_proj_stat = *proj_iter; ++proj_iter; if (proj_iter == (*i)->statistics.end()) { for (; sum_iter != sumstats.end(); ++sum_iter) { AddToStats(prev_proj_stat, *sum_iter); } break; } } } } } //Draw graph wxColour graphColour = wxColour(0,0,0); int typePoint = 0; getTypePoint(typePoint,count); color_cycle(m_SelectedStatistic, n_command_buttons, graphColour); DrawGraph2(dc, sumstats, graphColour, typePoint, m_SelectedStatistic); // sumstats.clear(); //Draw marker DrawMarker(dc); break; } default:{ m_ModeViewStatistic = mode_all_separate; break; } } if (m_Space_for_scrollbar) { dc.SetPen(wxPen(m_pen_MainColour , 1 , wxSOLID)); dc.DrawLine(w0 - m_Space_for_scrollbar - x0 - 1, y0, w0 - m_Space_for_scrollbar - x0 - 1, y0 + h0); } } //================================================================= void CPaintStatistics::OnPaint(wxPaintEvent& WXUNUSED(event)) { #if USE_MEMORYDC wxPaintDC pdc(this); wxMemoryDC mdc; #else wxPaintDC mdc(this); m_full_repaint=true; #endif wxCoord width = 0, height = 0; GetClientSize(&width, &height); if (m_full_repaint){ if (!m_GraphZoomStart){ ClearXY(); ClearLegendXY(); m_main_X_start = 0.0; if (width > 0) m_main_X_end = double(width); else m_main_X_end = 0.0; m_main_Y_start = 0.0; if (height > 0) m_main_Y_end = double(height); else m_main_Y_end = 0.0; if (width < 1) width = 1; if (height < 1) height = 1; #if USE_MEMORYDC m_dc_bmp.Create(width, height); mdc.SelectObject(m_dc_bmp); #endif DrawAll(mdc); m_bmp_OK = true; m_full_repaint = false; }else if(m_bmp_OK){ #if USE_MEMORYDC mdc.SelectObject(m_dc_bmp); #endif } }else{ if (m_bmp_OK){ #if USE_MEMORYDC mdc.SelectObject(m_dc_bmp); #endif if (m_GraphZoomStart && (width == m_dc_bmp.GetWidth()) &&(height == m_dc_bmp.GetHeight())){ mdc.SetPen(wxPen(m_pen_ZoomRectColour , 1 , wxSOLID)); mdc.SetBrush(wxBrush(m_brush_ZoomRectColour , wxSOLID)); mdc.SetLogicalFunction(wxXOR); wxCoord x0 = 0; wxCoord y0 = 0; wxCoord w0 = 0; wxCoord h0 = 0; if (m_GraphZoom_X1 < m_GraphZoom_X2_old) x0 = m_GraphZoom_X1; else x0 = m_GraphZoom_X2_old; if (m_GraphZoom_Y1 < m_GraphZoom_Y2_old) y0 = m_GraphZoom_Y1; else y0 = m_GraphZoom_Y2_old; w0 = m_GraphZoom_X2_old - m_GraphZoom_X1; h0 = m_GraphZoom_Y2_old - m_GraphZoom_Y1; if (x0 < 0) x0 = 0; if (y0 < 0) y0 = 0; if (w0 < 0) w0 = -w0; if (h0 < 0) h0 = -h0; mdc.DrawRectangle(x0, y0, w0, h0); if (m_GraphZoom_X1 < m_GraphZoom_X2) x0 = m_GraphZoom_X1; else x0 = m_GraphZoom_X2; if (m_GraphZoom_Y1 < m_GraphZoom_Y2) y0 = m_GraphZoom_Y1; else y0 = m_GraphZoom_Y2; w0 = m_GraphZoom_X2 - m_GraphZoom_X1; h0 = m_GraphZoom_Y2 - m_GraphZoom_Y1; if (x0 < 0) x0 = 0; if (y0 < 0) y0 = 0; if (w0 < 0) w0 = -w0; if (h0 < 0) h0 = -h0; mdc.DrawRectangle(x0, y0, w0, h0); m_GraphZoom_X2_old = m_GraphZoom_X2; m_GraphZoom_Y2_old = m_GraphZoom_Y2; mdc.SetLogicalFunction(wxCOPY); } } } #if USE_MEMORYDC if (m_bmp_OK && (width == m_dc_bmp.GetWidth()) &&(height == m_dc_bmp.GetHeight())){ pdc.Blit(0, 0, width - m_Space_for_scrollbar, height,& mdc, 0, 0); } mdc.SelectObject(wxNullBitmap); #endif } void CPaintStatistics::OnLeftMouseDown(wxMouseEvent& event) { // Legend if (m_Legend_dY > 0){ wxClientDC dc (this); wxPoint pt(event.GetLogicalPosition(dc)); if((double(pt.y) > m_Legend_select_Y_start) && (double(pt.y) < m_Legend_select_Y_end) && (double(pt.x) > m_Legend_select_X_start) && (double(pt.x) < m_Legend_select_X_end)){ int i1 = (int)floor((double(pt.y) - m_Legend_select_Y_start) / m_Legend_dY); switch (m_ModeViewStatistic){ case mode_one_project: m_NextProjectStatistic = i1 + m_Legend_Shift_Mode1; m_Zoom_Auto = true; m_GraphMarker1 = false; break; case mode_all_separate: case mode_all_together: case mode_sum: m_ViewHideProjectStatistic = i1 + m_Legend_Shift_Mode2; break; } m_full_repaint = true; Refresh(false); event.Skip(); return; } } // Graph switch (m_ModeViewStatistic){ case mode_one_project: case mode_all_together: case mode_sum: { wxClientDC dc (this); wxPoint pt(event.GetLogicalPosition(dc)); if((double(pt.y) > m_Graph_Y_start) && (double(pt.y) < m_Graph_Y_end) && (double(pt.x) > m_Graph_X_start) && (double(pt.x) < m_Graph_X_end)){ m_GraphMarker_X1 = m_Ax_CoordToVal * double(pt.x) + m_Bx_CoordToVal; m_GraphMarker_Y1 = m_Ay_CoordToVal * double(pt.y) + m_By_CoordToVal; m_GraphMarker1 = true; m_GraphZoom_X1 = wxCoord(pt.x); m_GraphZoom_Y1 = wxCoord(pt.y); m_GraphZoom_X2 = wxCoord(pt.x); m_GraphZoom_Y2 = wxCoord(pt.y); m_GraphZoom_X2_old = wxCoord(pt.x); m_GraphZoom_Y2_old = wxCoord(pt.y); m_GraphZoomStart = true; } break; } } event.Skip(); } void CPaintStatistics::OnMouseMotion(wxMouseEvent& event) { switch (m_ModeViewStatistic){ case mode_one_project: case mode_all_together: case mode_sum: { if (m_GraphZoomStart){ if (event.LeftIsDown()){ wxClientDC cdc (this); wxPoint pt(event.GetLogicalPosition(cdc)); if((double(pt.y) > m_Graph_Y_start) && (double(pt.y) < m_Graph_Y_end) && (double(pt.x) > m_Graph_X_start) && (double(pt.x) < m_Graph_X_end)){ m_GraphZoom_X2 = wxCoord(pt.x); m_GraphZoom_Y2 = wxCoord(pt.y); m_full_repaint = false; Refresh(false); } }else{ m_GraphZoomStart = false; m_full_repaint = true; Refresh(false); } }else if (m_GraphMoveStart){ if (event.RightIsDown()){ wxClientDC cdc (this); wxPoint pt(event.GetLogicalPosition(cdc)); if((double(pt.y) > m_Graph_Y_start) && (double(pt.y) < m_Graph_Y_end) && (double(pt.x) > m_Graph_X_start) && (double(pt.x) < m_Graph_X_end)){ m_GraphMove_X2 = wxCoord(pt.x); m_GraphMove_Y2 = wxCoord(pt.y); double X1 = m_Ax_CoordToVal * double(m_GraphMove_X1 - m_GraphMove_X2); double Y1 = m_Ay_CoordToVal * double(m_GraphMove_Y1 - m_GraphMove_Y2); if ( (X1 != 0) || (Y1 != 0)){ m_GraphMove_X1 = m_GraphMove_X2; m_GraphMove_Y1 = m_GraphMove_Y2; m_Zoom_min_val_X = m_Zoom_min_val_X + X1; m_Zoom_max_val_X = m_Zoom_max_val_X + X1; m_Zoom_min_val_Y = m_Zoom_min_val_Y + Y1; m_Zoom_max_val_Y = m_Zoom_max_val_Y + Y1; m_GraphMoveGo = true; m_Zoom_Auto = false; m_full_repaint = true; Refresh(false); } } }else{ m_GraphMoveStart = false; m_GraphMoveGo = false; m_full_repaint = true; Refresh(false); } } break; } } event.Skip(); } void CPaintStatistics::OnLeftMouseUp(wxMouseEvent& event) { switch (m_ModeViewStatistic){ case mode_one_project: case mode_all_together: case mode_sum: { if (m_GraphZoomStart){ if ((abs(int(m_GraphZoom_X1 - m_GraphZoom_X2)) > 2) && (abs(int(m_GraphZoom_Y1 - m_GraphZoom_Y2)) > 2)){ double X1 = m_Ax_CoordToVal * double(m_GraphZoom_X1) + m_Bx_CoordToVal; double Y1 = m_Ay_CoordToVal * double(m_GraphZoom_Y1) + m_By_CoordToVal; double X2 = m_Ax_CoordToVal * double(m_GraphZoom_X2) + m_Bx_CoordToVal; double Y2 = m_Ay_CoordToVal * double(m_GraphZoom_Y2) + m_By_CoordToVal; if (X1 > X2){ m_Zoom_max_val_X = X1; m_Zoom_min_val_X = X2; }else{ m_Zoom_min_val_X = X1; m_Zoom_max_val_X = X2; } if (Y1 > Y2){ m_Zoom_max_val_Y = Y1; m_Zoom_min_val_Y = Y2; }else{ m_Zoom_min_val_Y = Y1; m_Zoom_max_val_Y = Y2; } m_GraphMarker1 = false; m_Zoom_Auto = false; } m_GraphZoomStart = false; m_full_repaint = true; Refresh(false); } break; } } event.Skip(); } void CPaintStatistics::OnRightMouseDown(wxMouseEvent& event) { switch (m_ModeViewStatistic){ case mode_one_project: case mode_all_together: case mode_sum: { if (m_GraphZoomStart){ //??? m_GraphZoomStart = false; m_GraphMarker1 = false; m_full_repaint = true; Refresh(false); }else{ wxClientDC dc (this); wxPoint pt(event.GetLogicalPosition(dc)); if((double(pt.y) > m_Graph_Y_start) && (double(pt.y) < m_Graph_Y_end) && (double(pt.x) > m_Graph_X_start) && (double(pt.x) < m_Graph_X_end)){ m_GraphMove_X1 = wxCoord(pt.x); m_GraphMove_Y1 = wxCoord(pt.y); m_GraphMoveStart = true; m_GraphMoveGo = false; } } break; } } event.Skip(); } void CPaintStatistics::OnRightMouseUp(wxMouseEvent& event) { if (m_GraphMoveGo){ m_GraphMoveStart = false; m_GraphMoveGo = false; }else if (m_GraphMarker1){ m_GraphMarker1 = false; m_full_repaint = true; Refresh(false); }else if (!m_Zoom_Auto){ m_Zoom_Auto = true; m_full_repaint = true; Refresh(false); } event.Skip(); } void CPaintStatistics::OnMouseLeaveWindows(wxMouseEvent& event) { if (m_GraphZoomStart){ m_GraphMarker1 = false; m_GraphZoomStart = false; m_full_repaint = true; Refresh(false); } if (m_GraphMoveStart || m_GraphMoveGo){ m_GraphMoveStart = false; m_GraphMoveGo = false; } event.Skip(); } void CPaintStatistics::OnLegendScroll(wxScrollEvent& event) { m_full_repaint = true; Refresh(false); event.Skip(); } void CPaintStatistics::OnSize(wxSizeEvent& event) { m_full_repaint = true; Refresh(false); #ifdef __WXMAC__ ResizeMacAccessibilitySupport(); #endif event.Skip(); } IMPLEMENT_DYNAMIC_CLASS(CViewStatistics, CBOINCBaseView) BEGIN_EVENT_TABLE (CViewStatistics, CBOINCBaseView) EVT_BUTTON(ID_TASK_STATISTICS_USERTOTAL, CViewStatistics::OnStatisticsUserTotal) EVT_BUTTON(ID_TASK_STATISTICS_USERAVERAGE, CViewStatistics::OnStatisticsUserAverage) EVT_BUTTON(ID_TASK_STATISTICS_HOSTTOTAL, CViewStatistics::OnStatisticsHostTotal) EVT_BUTTON(ID_TASK_STATISTICS_HOSTAVERAGE, CViewStatistics::OnStatisticsHostAverage) EVT_BUTTON(ID_TASK_STATISTICS_MODEVIEWALLSEPARATE, CViewStatistics::OnStatisticsModeViewAllSeparate) EVT_BUTTON(ID_TASK_STATISTICS_MODEVIEWONEPROJECT, CViewStatistics::OnStatisticsModeViewOneProject) EVT_BUTTON(ID_TASK_STATISTICS_MODEVIEWALLTOGETHER, CViewStatistics::OnStatisticsModeViewAllTogether) EVT_BUTTON(ID_TASK_STATISTICS_MODEVIEWSUM, CViewStatistics::OnStatisticsModeViewSum) EVT_BUTTON(ID_TASK_STATISTICS_NEXTPROJECT, CViewStatistics::OnStatisticsNextProject) EVT_BUTTON(ID_TASK_STATISTICS_PREVPROJECT, CViewStatistics::OnStatisticsPrevProject) EVT_BUTTON(ID_TASK_STATISTICS_HIDEPROJLIST, CViewStatistics::OnShowHideProjectList) END_EVENT_TABLE () CViewStatistics::CViewStatistics() {} CViewStatistics::CViewStatistics(wxNotebook* pNotebook) : CBOINCBaseView(pNotebook) { CTaskItemGroup* pGroup = NULL; CTaskItem* pItem = NULL; // // Setup View // wxFlexGridSizer* itemFlexGridSizer = new wxFlexGridSizer(2, 0, 0); wxASSERT(itemFlexGridSizer); itemFlexGridSizer->AddGrowableRow(0); itemFlexGridSizer->AddGrowableCol(1); m_pTaskPane = new CBOINCTaskCtrl(this, ID_TASK_STATISTICSVIEW, DEFAULT_TASK_FLAGS); wxASSERT(m_pTaskPane); m_PaintStatistics = new CPaintStatistics(this, ID_LIST_STATISTICSVIEW, wxDefaultPosition, wxSize(-1, -1), 0); wxASSERT(m_PaintStatistics); itemFlexGridSizer->Add(m_pTaskPane, 1, wxGROW|wxALL, 1); itemFlexGridSizer->Add(m_PaintStatistics, 1, wxGROW|wxALL, 1); SetSizer(itemFlexGridSizer); Layout(); pGroup = new CTaskItemGroup( _("Commands") ); m_TaskGroups.push_back( pGroup ); pItem = new CTaskItem( _("Show user total"), _("Show total credit for user"), ID_TASK_STATISTICS_USERTOTAL ); pGroup->m_Tasks.push_back( pItem ); pItem = new CTaskItem( _("Show user average"), _("Show average credit for user"), ID_TASK_STATISTICS_USERAVERAGE ); pGroup->m_Tasks.push_back( pItem ); pItem = new CTaskItem( _("Show host total"), _("Show total credit for host"), ID_TASK_STATISTICS_HOSTTOTAL ); pGroup->m_Tasks.push_back( pItem ); pItem = new CTaskItem( _("Show host average"), _("Show average credit for host"), ID_TASK_STATISTICS_HOSTAVERAGE ); pGroup->m_Tasks.push_back( pItem ); pGroup = new CTaskItemGroup( _("Project") ); m_TaskGroups.push_back( pGroup ); pItem = new CTaskItem( _("< &Previous project"), _("Show chart for previous project"), ID_TASK_STATISTICS_PREVPROJECT ); pGroup->m_Tasks.push_back( pItem ); pItem = new CTaskItem( _("&Next project >"), _("Show chart for next project"), ID_TASK_STATISTICS_NEXTPROJECT ); pGroup->m_Tasks.push_back( pItem ); pItem = new CTaskItem( _("Hide project list"), _("Use entire area for graphs"), ID_TASK_STATISTICS_HIDEPROJLIST ); pGroup->m_Tasks.push_back( pItem ); pGroup = new CTaskItemGroup( _("Mode view") ); m_TaskGroups.push_back( pGroup ); pItem = new CTaskItem( _("One project"), _("Show one chart with selected project"), ID_TASK_STATISTICS_MODEVIEWONEPROJECT ); pGroup->m_Tasks.push_back( pItem ); pItem = new CTaskItem( _("All projects (separate)"), _("Show all projects, one chart per project"), ID_TASK_STATISTICS_MODEVIEWALLSEPARATE ); pGroup->m_Tasks.push_back( pItem ); pItem = new CTaskItem( _("All projects (together)"), _("Show one chart with all projects"), ID_TASK_STATISTICS_MODEVIEWALLTOGETHER ); pGroup->m_Tasks.push_back( pItem ); pItem = new CTaskItem( _("All projects (sum)"), _("Show one chart with sum of projects"), ID_TASK_STATISTICS_MODEVIEWSUM ); pGroup->m_Tasks.push_back( pItem ); // Create Task Pane Items m_pTaskPane->UpdateControls(); UpdateSelection(); } CViewStatistics::~CViewStatistics() { EmptyTasks(); } wxString& CViewStatistics::GetViewName() { static wxString strViewName(wxT("Statistics")); return strViewName; } wxString& CViewStatistics::GetViewDisplayName() { static wxString strViewName(_("Statistics")); return strViewName; } const char** CViewStatistics::GetViewIcon() { return stats_xpm; } int CViewStatistics::GetViewRefreshRate() { return 60; } int CViewStatistics::GetViewCurrentViewPage() { return VW_STAT; } void CViewStatistics::OnStatisticsUserTotal( wxCommandEvent& WXUNUSED(event) ) { wxLogTrace(wxT("Function Start/End"), wxT("CViewStatistics::OnStatisticsUserTotal - Function Begin")); CAdvancedFrame* pFrame = wxDynamicCast(GetParent()->GetParent()->GetParent(), CAdvancedFrame); wxASSERT(pFrame); wxASSERT(wxDynamicCast(pFrame, CAdvancedFrame)); m_PaintStatistics->m_SelectedStatistic = show_user_total; m_PaintStatistics->m_Zoom_Auto = true; m_PaintStatistics->m_GraphMarker1 = false; m_PaintStatistics->m_full_repaint = true; UpdateSelection(); pFrame->FireRefreshView(); wxLogTrace(wxT("Function Start/End"), wxT("CViewStatistics::OnStatisticsUserTotal - Function End")); } void CViewStatistics::OnStatisticsUserAverage( wxCommandEvent& WXUNUSED(event) ) { wxLogTrace(wxT("Function Start/End"), wxT("CViewStatistics::OnStatisticsUserAverage - Function Begin")); CAdvancedFrame* pFrame = wxDynamicCast(GetParent()->GetParent()->GetParent(), CAdvancedFrame); wxASSERT(pFrame); wxASSERT(wxDynamicCast(pFrame, CAdvancedFrame)); m_PaintStatistics->m_SelectedStatistic = show_user_average; m_PaintStatistics->m_Zoom_Auto = true; m_PaintStatistics->m_GraphMarker1 = false; m_PaintStatistics->m_full_repaint = true; UpdateSelection(); pFrame->FireRefreshView(); wxLogTrace(wxT("Function Start/End"), wxT("CViewStatistics::OnStatisticsUserAverage - Function End")); } void CViewStatistics::OnStatisticsHostTotal( wxCommandEvent& WXUNUSED(event) ) { wxLogTrace(wxT("Function Start/End"), wxT("CViewStatistics::OnStatisticsHostTotal - Function Begin")); CAdvancedFrame* pFrame = wxDynamicCast(GetParent()->GetParent()->GetParent(), CAdvancedFrame); wxASSERT(pFrame); wxASSERT(wxDynamicCast(pFrame, CAdvancedFrame)); m_PaintStatistics->m_SelectedStatistic = show_host_total; m_PaintStatistics->m_Zoom_Auto = true; m_PaintStatistics->m_GraphMarker1 = false; m_PaintStatistics->m_full_repaint = true; UpdateSelection(); pFrame->FireRefreshView(); wxLogTrace(wxT("Function Start/End"), wxT("CViewStatistics::OnStatisticsHostTotal - Function End")); } void CViewStatistics::OnStatisticsHostAverage( wxCommandEvent& WXUNUSED(event) ) { wxLogTrace(wxT("Function Start/End"), wxT("CViewStatistics::OnStatisticsHostAverage - Function Begin")); CAdvancedFrame* pFrame = wxDynamicCast(GetParent()->GetParent()->GetParent(), CAdvancedFrame); wxASSERT(pFrame); wxASSERT(wxDynamicCast(pFrame, CAdvancedFrame)); m_PaintStatistics->m_SelectedStatistic = show_host_average; m_PaintStatistics->m_Zoom_Auto = true; m_PaintStatistics->m_GraphMarker1 = false; m_PaintStatistics->m_full_repaint = true; UpdateSelection(); pFrame->FireRefreshView(); wxLogTrace(wxT("Function Start/End"), wxT("CViewStatistics::OnStatisticsHostAverage - Function End")); } void CViewStatistics::OnStatisticsModeViewAllSeparate( wxCommandEvent& WXUNUSED(event) ) { wxLogTrace(wxT("Function Start/End"), wxT("CViewStatistics::OnStatisticsModeView - Function Begin")); CAdvancedFrame* pFrame = wxDynamicCast(GetParent()->GetParent()->GetParent(), CAdvancedFrame); wxASSERT(pFrame); wxASSERT(wxDynamicCast(pFrame, CAdvancedFrame)); m_PaintStatistics->m_ModeViewStatistic = mode_all_separate; m_PaintStatistics->m_Zoom_Auto = true; m_PaintStatistics->m_GraphMarker1 = false; m_PaintStatistics->m_full_repaint = true; UpdateSelection(); pFrame->FireRefreshView(); wxLogTrace(wxT("Function Start/End"), wxT("CViewStatistics::OnStatisticsModeView - Function End")); } void CViewStatistics::OnStatisticsModeViewOneProject( wxCommandEvent& WXUNUSED(event) ) { wxLogTrace(wxT("Function Start/End"), wxT("CViewStatistics::OnStatisticsModeView - Function Begin")); CAdvancedFrame* pFrame = wxDynamicCast(GetParent()->GetParent()->GetParent(), CAdvancedFrame); wxASSERT(pFrame); wxASSERT(wxDynamicCast(pFrame, CAdvancedFrame)); m_PaintStatistics->m_ModeViewStatistic = mode_one_project; m_PaintStatistics->m_Zoom_Auto = true; m_PaintStatistics->m_GraphMarker1 = false; m_PaintStatistics->m_full_repaint = true; UpdateSelection(); pFrame->FireRefreshView(); wxLogTrace(wxT("Function Start/End"), wxT("CViewStatistics::OnStatisticsModeView - Function End")); } void CViewStatistics::OnStatisticsModeViewAllTogether( wxCommandEvent& WXUNUSED(event) ) { wxLogTrace(wxT("Function Start/End"), wxT("CViewStatistics::OnStatisticsModeView - Function Begin")); CAdvancedFrame* pFrame = wxDynamicCast(GetParent()->GetParent()->GetParent(), CAdvancedFrame); wxASSERT(pFrame); wxASSERT(wxDynamicCast(pFrame, CAdvancedFrame)); m_PaintStatistics->m_ModeViewStatistic = mode_all_together; m_PaintStatistics->m_Zoom_Auto = true; m_PaintStatistics->m_GraphMarker1 = false; m_PaintStatistics->m_full_repaint = true; UpdateSelection(); pFrame->FireRefreshView(); wxLogTrace(wxT("Function Start/End"), wxT("CViewStatistics::OnStatisticsModeView - Function End")); } void CViewStatistics::OnStatisticsModeViewSum( wxCommandEvent& WXUNUSED(event) ) { wxLogTrace(wxT("Function Start/End"), wxT("CViewStatistics::OnStatisticsModeView - Function Begin")); CAdvancedFrame* pFrame = wxDynamicCast(GetParent()->GetParent()->GetParent(), CAdvancedFrame); wxASSERT(pFrame); wxASSERT(wxDynamicCast(pFrame, CAdvancedFrame)); m_PaintStatistics->m_ModeViewStatistic = mode_sum; m_PaintStatistics->m_Zoom_Auto = true; m_PaintStatistics->m_GraphMarker1 = false; m_PaintStatistics->m_full_repaint = true; UpdateSelection(); pFrame->FireRefreshView(); wxLogTrace(wxT("Function Start/End"), wxT("CViewStatistics::OnStatisticsModeView - Function End")); } void CViewStatistics::OnStatisticsNextProject( wxCommandEvent& WXUNUSED(event) ) { wxLogTrace(wxT("Function Start/End"), wxT("CViewStatistics::OnStatisticsNextProject - Function Begin")); CAdvancedFrame* pFrame = wxDynamicCast(GetParent()->GetParent()->GetParent(), CAdvancedFrame); wxASSERT(pFrame); wxASSERT(wxDynamicCast(pFrame, CAdvancedFrame)); if (m_PaintStatistics->m_ModeViewStatistic == mode_one_project) m_PaintStatistics->m_NextProjectStatistic++; m_PaintStatistics->m_Zoom_Auto = true; m_PaintStatistics->m_GraphMarker1 = false; m_PaintStatistics->m_full_repaint = true; if (m_PaintStatistics->m_ModeViewStatistic == mode_all_separate) m_PaintStatistics->m_Legend_Shift_Mode2++; if (m_PaintStatistics->m_ModeViewStatistic == mode_all_together) m_PaintStatistics->m_Legend_Shift_Mode2++; if (m_PaintStatistics->m_ModeViewStatistic == mode_sum) m_PaintStatistics->m_Legend_Shift_Mode2++; UpdateSelection(); pFrame->FireRefreshView(); wxLogTrace(wxT("Function Start/End"), wxT("CViewStatistics::OnStatisticsNextProject - Function End")); } void CViewStatistics::OnStatisticsPrevProject( wxCommandEvent& WXUNUSED(event) ) { wxLogTrace(wxT("Function Start/End"), wxT("CViewStatistics::OnStatisticsPrevProject - Function Begin")); CAdvancedFrame* pFrame = wxDynamicCast(GetParent()->GetParent()->GetParent(), CAdvancedFrame); wxASSERT(pFrame); wxASSERT(wxDynamicCast(pFrame, CAdvancedFrame)); if (m_PaintStatistics->m_ModeViewStatistic == mode_one_project) m_PaintStatistics->m_NextProjectStatistic--; m_PaintStatistics->m_Zoom_Auto = true; m_PaintStatistics->m_GraphMarker1 = false; m_PaintStatistics->m_full_repaint = true; if (m_PaintStatistics->m_ModeViewStatistic == mode_all_separate) m_PaintStatistics->m_Legend_Shift_Mode2--; if (m_PaintStatistics->m_ModeViewStatistic == mode_all_together) m_PaintStatistics->m_Legend_Shift_Mode2--; if (m_PaintStatistics->m_ModeViewStatistic == mode_sum) m_PaintStatistics->m_Legend_Shift_Mode2--; UpdateSelection(); pFrame->FireRefreshView(); wxLogTrace(wxT("Function Start/End"), wxT("CViewStatistics::OnStatisticsPrevProject - Function End")); } void CViewStatistics::OnShowHideProjectList( wxCommandEvent& WXUNUSED(event) ) { wxLogTrace(wxT("Function Start/End"), wxT("CViewStatistics::OnShowHideProjectList - Function Begin")); m_PaintStatistics->m_LegendDraw = !m_PaintStatistics->m_LegendDraw; m_PaintStatistics->m_full_repaint = true; m_PaintStatistics->Refresh(false); UpdateSelection(); wxLogTrace(wxT("Function Start/End"), wxT("CViewStatistics::OnShowHideProjectList - Function End")); } bool CViewStatistics::OnSaveState(wxConfigBase* pConfig) { bool bReturnValue = true; wxASSERT(pConfig); wxASSERT(m_pTaskPane); if (!m_pTaskPane->OnSaveState(pConfig)) { bReturnValue = false; } //-- wxString strBaseConfigLocation = wxEmptyString; strBaseConfigLocation = wxT("/Statistics"); pConfig->SetPath(strBaseConfigLocation); pConfig->Write(wxT("ModeViewStatistic"), m_PaintStatistics->m_ModeViewStatistic); pConfig->Write(wxT("SelectedStatistic"), m_PaintStatistics->m_SelectedStatistic); pConfig->Write(wxT("NextProjectStatistic"), m_PaintStatistics->m_NextProjectStatistic); strBaseConfigLocation = wxT("/Statistics/ViewAll"); pConfig->DeleteGroup(strBaseConfigLocation); pConfig->SetPath(strBaseConfigLocation); int count = -1; for (std::set<wxString>::const_iterator i_s = m_PaintStatistics->m_HideProjectStatistic.begin(); i_s != m_PaintStatistics->m_HideProjectStatistic.end(); ++i_s) { ++count; pConfig->Write(wxString::Format(wxT("%d"), count), (*i_s)); } //-- return bReturnValue; } bool CViewStatistics::OnRestoreState(wxConfigBase* pConfig) { wxASSERT(pConfig); wxASSERT(m_pTaskPane); if (!m_pTaskPane->OnRestoreState(pConfig)) { return false; } //-- int iTempValue = 0; wxString strBaseConfigLocation = wxEmptyString; strBaseConfigLocation = wxT("/Statistics"); pConfig->SetPath(strBaseConfigLocation); m_PaintStatistics->m_ModeViewStatistic = mode_all_separate; pConfig->Read(wxT("ModeViewStatistic"), &iTempValue, -1); if ((iTempValue >= mode_one_project) && (iTempValue <= mode_sum))m_PaintStatistics->m_ModeViewStatistic = iTempValue; m_PaintStatistics->m_SelectedStatistic = show_user_total; pConfig->Read(wxT("SelectedStatistic"), &iTempValue, -1); if ((iTempValue >= show_user_total) && (iTempValue <= show_host_average))m_PaintStatistics->m_SelectedStatistic = iTempValue; m_PaintStatistics->m_NextProjectStatistic = 0; pConfig->Read(wxT("NextProjectStatistic"), &iTempValue, -1); if (iTempValue >= 0)m_PaintStatistics->m_NextProjectStatistic = iTempValue; // -- Hide View All projects strBaseConfigLocation = wxT("/Statistics/ViewAll"); pConfig->SetPath(strBaseConfigLocation); wxString tmpstr1; if (!(m_PaintStatistics->m_HideProjectStatistic.empty())) m_PaintStatistics->m_HideProjectStatistic.clear(); for (int count = 0; count < 1000; ++count) { pConfig->Read(wxString::Format(wxT("%d"), count), &tmpstr1, wxT("")); if (tmpstr1 == wxEmptyString){ break; }else{ m_PaintStatistics->m_HideProjectStatistic.insert(tmpstr1); } } UpdateSelection(); return true; } void CViewStatistics::OnListRender( wxTimerEvent& WXUNUSED(event) ) { if (wxGetApp().GetDocument()->GetStatisticsCount()) { m_PaintStatistics->m_full_repaint = true; m_PaintStatistics->Refresh(false); } } void CViewStatistics::UpdateSelection() { CTaskItemGroup* pGroup = m_TaskGroups[0]; CBOINCBaseView::PreUpdateSelection(); pGroup->m_Tasks[show_user_total]->m_pButton->Enable(m_PaintStatistics->m_SelectedStatistic != show_user_total); pGroup->m_Tasks[show_user_average]->m_pButton->Enable(m_PaintStatistics->m_SelectedStatistic != show_user_average); pGroup->m_Tasks[show_host_total]->m_pButton->Enable(m_PaintStatistics->m_SelectedStatistic != show_host_total); pGroup->m_Tasks[show_host_average]->m_pButton->Enable(m_PaintStatistics->m_SelectedStatistic != show_host_average); pGroup = m_TaskGroups[1]; pGroup->m_Tasks[previous_project]->m_pButton->Enable(m_PaintStatistics->m_ModeViewStatistic == mode_one_project); pGroup->m_Tasks[next_project]->m_pButton->Enable(m_PaintStatistics->m_ModeViewStatistic == mode_one_project); if (m_PaintStatistics->m_LegendDraw) { m_pTaskPane->UpdateTask( pGroup->m_Tasks[show_hide_project_list], _("Hide project list"), _("Use entire area for graphs") ); } else { m_pTaskPane->UpdateTask( pGroup->m_Tasks[show_hide_project_list], _("Show project list"), _("Uses smaller area for graphs") ); } pGroup = m_TaskGroups[2]; pGroup->m_Tasks[mode_one_project]->m_pButton->Enable(m_PaintStatistics->m_ModeViewStatistic != mode_one_project); pGroup->m_Tasks[mode_all_separate]->m_pButton->Enable(m_PaintStatistics->m_ModeViewStatistic != mode_all_separate); pGroup->m_Tasks[mode_all_together]->m_pButton->Enable(m_PaintStatistics->m_ModeViewStatistic != mode_all_together); pGroup->m_Tasks[mode_sum]->m_pButton->Enable(m_PaintStatistics->m_ModeViewStatistic != mode_sum); CBOINCBaseView::PostUpdateSelection(); }
1
9,275
How does this cope with values like `5.001`? Shouldn't that set precision to 0? Instead it is set to 2.
BOINC-boinc
php
@@ -40,7 +40,7 @@ class APITestCase(IntegrationTestCase): # This sleep allows for the influx subscriber to take its time in getting # the listen submitted from redis and writing it to influx. # Removing it causes an empty list of listens to be returned. - time.sleep(10) + time.sleep(15) url = url_for('api_v1.get_listens', user_name = self.user['musicbrainz_id']) response = self.client.get(url, query_string = {'count': '1'})
1
from __future__ import absolute_import, print_function import sys import os import uuid sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "..")) from tests.integration import IntegrationTestCase from flask import url_for import db.user import time import json TEST_DATA_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..', 'testdata') # lifted from AcousticBrainz def is_valid_uuid(u): try: u = uuid.UUID(u) return True except ValueError: return False class APITestCase(IntegrationTestCase): def setUp(self): super(APITestCase, self).setUp() self.user = db.user.get_or_create('testuserpleaseignore') def test_get_listens(self): """ Test to make sure that the api sends valid listens on get requests. """ with open(self.path_to_data_file('valid_single.json'), 'r') as f: payload = json.load(f) # send a listen payload['payload'][0]['listened_at'] = int(time.time()) response = self.send_data(payload) self.assert200(response) # This sleep allows for the influx subscriber to take its time in getting # the listen submitted from redis and writing it to influx. # Removing it causes an empty list of listens to be returned. time.sleep(10) url = url_for('api_v1.get_listens', user_name = self.user['musicbrainz_id']) response = self.client.get(url, query_string = {'count': '1'}) self.assert200(response) data = json.loads(response.data)['payload'] # make sure user id is correct self.assertEquals(data['user_id'], self.user['musicbrainz_id']) # make sure that count is 1 and list also contains 1 listen self.assertEquals(data['count'], 1) self.assertEquals(len(data['listens']), 1) # make sure timestamp is the same as sent sent_time = payload['payload'][0]['listened_at'] self.assertEquals(data['listens'][0]['listened_at'], sent_time) # make sure that artist msid, release msid and recording msid are present in data self.assertTrue(is_valid_uuid(data['listens'][0]['recording_msid'])) self.assertTrue(is_valid_uuid(data['listens'][0]['track_metadata']['additional_info']['artist_msid'])) self.assertTrue(is_valid_uuid(data['listens'][0]['track_metadata']['additional_info']['release_msid'])) def send_data(self, payload): """ Sends payload to api.submit_listen and return the response """ return self.client.post( url_for('api_v1.submit_listen'), data = json.dumps(payload), headers = {'Authorization': 'Token {}'.format(self.user['auth_token'])}, content_type = 'application/json' ) def test_unauthorized_submission(self): """ Test for checking that unauthorized submissions return 401 """ with open(self.path_to_data_file('valid_single.json'), 'r') as f: payload = json.load(f) # request with no authorization header response = self.client.post( url_for('api_v1.submit_listen'), data = json.dumps(payload), content_type = 'application/json' ) self.assert401(response) # request with invalid authorization header response = self.client.post( url_for('api_v1.submit_listen'), data = json.dumps(payload), headers = {'Authorization' : 'Token testtokenplsignore'}, content_type = 'application/json' ) self.assert401(response) def test_valid_single(self): """ Test for valid submissioon of listen_type listen """ with open(self.path_to_data_file('valid_single.json'), 'r') as f: payload = json.load(f) response = self.send_data(payload) self.assert200(response) def test_single_more_than_one_listen(self): """ Test for an invalid submission which has listen_type 'single' but more than one listen in payload """ with open(self.path_to_data_file('single_more_than_one_listen.json'), 'r') as f: payload = json.load(f) response = self.send_data(payload) self.assert400(response) def test_valid_playing_now(self): """ Test for valid submission of listen_type 'playing_now' """ with open(self.path_to_data_file('valid_playing_now.json'), 'r') as f: payload = json.load(f) response = self.send_data(payload) self.assert200(response) def test_playing_now_with_ts(self): """ Test for invalid submission of listen_type 'playing_now' which contains timestamp 'listened_at' """ with open(self.path_to_data_file('playing_now_with_ts.json'), 'r') as f: payload = json.load(f) response = self.send_data(payload) self.assert400(response) def test_playing_now_more_than_one_listen(self): """ Test for invalid submission of listen_type 'playing_now' which contains more than one listen in payload """ with open(self.path_to_data_file('playing_now_more_than_one_listen.json'), 'r') as f: payload = json.load(f) response = self.send_data(payload) self.assert400(response) def test_valid_import(self): """ Test for a valid submission of listen_type 'import' """ with open(self.path_to_data_file('valid_import.json'), 'r') as f: payload = json.load(f) response = self.send_data(payload) self.assert200(response) def test_too_large_listen(self): """ Test for invalid submission in which the overall size of the listens sent is more than 10240 bytes """ with open(self.path_to_data_file('too_large_listen.json'), 'r') as f: payload = json.load(f) response = self.send_data(payload) self.assert400(response) def test_too_many_tags_in_listen(self): """ Test for invalid submission in which a listen contains more than the allowed number of tags in additional_info. """ with open(self.path_to_data_file('too_many_tags.json'), 'r') as f: payload = json.load(f) response = self.send_data(payload) self.assert400(response) def test_too_long_tag(self): """ Test for invalid submission in which a listen contains a tag of length > 64 """ with open(self.path_to_data_file('too_long_tag.json'), 'r') as f: payload = json.load(f) response = self.send_data(payload) self.assert400(response) def test_invalid_release_mbid(self): """ Test for invalid submission in which a listen contains an invalid release_mbid in additional_info """ with open(self.path_to_data_file('invalid_release_mbid.json'), 'r') as f: payload = json.load(f) response = self.send_data(payload) self.assert400(response) def test_invalid_artist_mbid(self): """ Test for invalid submission in which a listen contains an invalid artist_mbid in additional_info """ with open(self.path_to_data_file('invalid_artist_mbid.json'), 'r') as f: payload = json.load(f) response = self.send_data(payload) self.assert400(response) def test_invalid_recording_mbid(self): """ Test for invalid submission in which a listen contains an invalid recording_mbid in additional_info """ with open(self.path_to_data_file('invalid_recording_mbid.json'), 'r') as f: payload = json.load(f) response = self.send_data(payload) self.assert400(response) def path_to_data_file(self, fn): """ Returns the path of the test data file relative to the test file. Args: fn: the name of the data file """ return os.path.join(TEST_DATA_PATH, fn)
1
14,196
Rather than having a sleep here, we should check to see if the service we're waiting for is up yet, using something like dockerize. Not critical this second, but would be nice for later.
metabrainz-listenbrainz-server
py
@@ -0,0 +1,18 @@ +import path from 'path'; +import execa from 'execa'; +import { + displayErrorMessage +} from '../../scripts/utils/console.mjs'; + +((async function() { + try { + await execa('npm', ['run', 'swap-package-links'], { + cwd: path.resolve(process.cwd(), '..'), + stdio: 'inherit' + }); + + } catch (error) { + displayErrorMessage('Error running the script.'); + process.exit(error.exitCode); + } +})());
1
1
20,131
I'm not sure if there are any links to swap for Handosntable package. Should this be a top lvl script?
handsontable-handsontable
js
@@ -537,7 +537,16 @@ signal_thread_init(dcontext_t *dcontext, void *os_data) signal_frame_extra_size(true) /* sigpending_t has xstate inside it already */ IF_LINUX(IF_X86(-sizeof(kernel_xstate_t))); - IF_LINUX(IF_X86(ASSERT(!YMM_ENABLED() || ALIGNED(pend_unit_size, AVX_ALIGNMENT)))); +/* Above does not guarantee alignment, it only guarantees sufficient space including + * aligmment of the extended state. The following is needed in order to guarantee + * alignment of our pending unit's size, which is used as the block size in the + * special allocator. + */ +#ifdef X86 + pend_unit_size = + ALIGN_FORWARD(pend_unit_size, YMM_ENABLED() ? AVX_ALIGNMENT : FPSTATE_ALIGNMENT); + IF_LINUX(ASSERT(!YMM_ENABLED() || ALIGNED(pend_unit_size, AVX_ALIGNMENT))); +#endif /* all fields want to be initialized to 0 */ memset(info, 0, sizeof(thread_sig_info_t));
1
/* ********************************************************** * Copyright (c) 2011-2019 Google, Inc. All rights reserved. * Copyright (c) 2000-2010 VMware, Inc. All rights reserved. * **********************************************************/ /* * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of VMware, Inc. nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL VMWARE, INC. OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. */ /* Copyright (c) 2003-2007 Determina Corp. */ /* Copyright (c) 2001-2003 Massachusetts Institute of Technology */ /* Copyright (c) 2000-2001 Hewlett-Packard Company */ /* * signal.c - dynamorio signal handler */ #include <errno.h> #undef errno #include "signal_private.h" /* pulls in globals.h for us, in right order */ /* We want to build on older toolchains so we have our own copy of signal * data structures */ #include "include/siginfo.h" #ifdef LINUX # include "include/sigcontext.h" # include "include/signalfd.h" # include "../globals.h" /* after our sigcontext.h, to preclude bits/sigcontext.h */ #elif defined(MACOS) # include "../globals.h" /* this defines _XOPEN_SOURCE for Mac */ # include <signal.h> /* after globals.h, for _XOPEN_SOURCE from os_exports.h */ #endif #ifdef LINUX # include <linux/sched.h> #endif #include <sys/time.h> #include <sys/types.h> #include <sys/wait.h> #include <ucontext.h> #include "os_private.h" #include "../fragment.h" #include "../fcache.h" #include "../perfctr.h" #include "arch.h" #include "../monitor.h" /* for trace_abort */ #include "../link.h" /* for linking interrupted fragment_t */ #include "instr.h" /* to find target of SIGSEGV */ #include "decode.h" /* to find target of SIGSEGV */ #include "decode_fast.h" /* to handle self-mod code */ #include "../synch.h" #include "../nudge.h" #include "disassemble.h" #include "ksynch.h" #include "tls.h" /* tls_reinstate_selector */ #include "../translate.h" #ifdef LINUX # include "include/syscall.h" #else # include <sys/syscall.h> #endif #ifdef CLIENT_INTERFACE # include "instrument.h" #endif #ifdef VMX86_SERVER # include <errno.h> #endif /* Define the Linux names, which the code is already using */ #ifndef SA_NOMASK # define SA_NOMASK SA_NODEFER #endif #ifndef SA_ONESHOT # define SA_ONESHOT SA_RESETHAND #endif #ifndef SS_AUTODISARM # define SS_AUTODISARM (1U << 31) #endif #ifndef SS_FLAG_BITS # define SS_FLAG_BITS SS_AUTODISARM #endif #ifdef X86 /* Kernel-only flags. */ # define SA_IA32_ABI 0x02000000U # define SA_X32_ABI 0x01000000U #endif /**** data structures ***************************************************/ /* The signal numbers are slightly different between operating systems. * To support differing default actions, we have separate arrays, rather * than indirecting to a single all-signals array. */ extern int default_action[]; /* We know that many signals are always asynchronous. * Others, however, may be synchronous or may not -- e.g., another process * could send us a SIGSEGV, and there is no way we can tell whether it * was generated by a real memory fault or not. Thus we have to assume * that we must not delay any SIGSEGV deliveries. */ extern bool can_always_delay[]; static inline bool sig_is_alarm_signal(int sig) { return (sig == SIGALRM || sig == SIGVTALRM || sig == SIGPROF); } /* we do not use SIGSTKSZ b/c for things like code modification * we end up calling many core routines and so want more space * (though currently non-debug stack size == SIGSTKSZ (8KB)) */ #define SIGSTACK_SIZE (DYNAMO_OPTION(signal_stack_size)) /* this flag not defined in our headers */ #define SA_RESTORER 0x04000000 /* if no app sigaction, it's RT, since that's our handler */ #ifdef LINUX # define IS_RT_FOR_APP(info, sig) \ IF_X64_ELSE(true, \ ((info)->app_sigaction[(sig)] == NULL \ ? true \ : (TEST(SA_SIGINFO, (info)->app_sigaction[(sig)]->flags)))) #elif defined(MACOS) # define IS_RT_FOR_APP(info, sig) (true) #endif /* kernel sets size and sp to 0 for SS_DISABLE * when asked, will hand back SS_ONSTACK only if current xsp is inside the * alt stack; otherwise, if an alt stack is registered, it will give flags of 0 * We do not support the "legacy stack switching" that uses the restorer field * as seen in kernel sources. */ #define APP_HAS_SIGSTACK(info) \ ((info)->app_sigstack.ss_sp != NULL && (info)->app_sigstack.ss_flags != SS_DISABLE) /* Under normal circumstances the app_sigaction is lazily initialized when the * app registers a signal handler, but during detach there are points where we * are still intercepting signals after app_sigaction has been set to * zeros. To be extra defensive, we do a NULL check. */ #define USE_APP_SIGSTACK(info, sig) \ (APP_HAS_SIGSTACK(info) && (info)->app_sigaction[sig] != NULL && \ TEST(SA_ONSTACK, (info)->app_sigaction[sig]->flags)) /* If we only intercept a few signals, we leave whether un-intercepted signals * are blocked unchanged and stored in the kernel. If we intercept all (not * quite yet: PR 297033, hence the need for this macro) we emulate the mask for * all. */ #define EMULATE_SIGMASK(info, sig) \ (DYNAMO_OPTION(intercept_all_signals) || (info)->we_intercept[(sig)]) /* i#27: custom data to pass to the child of a clone */ /* PR i#149/403015: clone record now passed via a new dstack */ typedef struct _clone_record_t { byte *dstack; /* dstack for new thread - allocated by parent thread */ #ifdef MACOS /* XXX i#1403: once we have lower-level, earlier thread interception we can * likely switch to something closer to what we do on Linux. * This is used for bsdthread_create, where app_thread_xsp is NULL; * for vfork, app_thread_xsp is non-NULL and this is unused. */ void *thread_arg; #endif reg_t app_thread_xsp; /* app xsp preserved for new thread to use */ app_pc continuation_pc; thread_id_t caller_id; int clone_sysnum; uint clone_flags; thread_sig_info_t info; thread_sig_info_t *parent_info; void *pcprofile_info; #ifdef AARCHXX /* To ensure we have the right value as of the point of the clone, we * store it here (we'll have races if we try to get it during new thread * init). */ reg_t app_stolen_value; # ifndef AARCH64 dr_isa_mode_t isa_mode; # endif /* To ensure we have the right app lib tls base in child thread, * we store it here if necessary (clone w/o CLONE_SETTLS or vfork). */ void *app_lib_tls_base; #endif /* we leave some padding at base of stack for dynamorio_clone * to store values */ reg_t for_dynamorio_clone[4]; } __attribute__((__aligned__(ABI_STACK_ALIGNMENT))) clone_record_t; /* i#350: set up signal handler for safe_read/faults during init */ static thread_sig_info_t init_info; static kernel_sigset_t init_sigmask; #ifdef DEBUG static bool removed_sig_handler; #endif os_cxt_ptr_t osc_empty; /**** function prototypes ***********************************************/ /* in x86.asm */ void master_signal_handler(int sig, kernel_siginfo_t *siginfo, kernel_ucontext_t *ucxt); static void set_handler_and_record_app(dcontext_t *dcontext, thread_sig_info_t *info, int sig, kernel_sigaction_t *act); static void intercept_signal(dcontext_t *dcontext, thread_sig_info_t *info, int sig); static void signal_info_init_sigaction(dcontext_t *dcontext, thread_sig_info_t *info); static void signal_info_exit_sigaction(dcontext_t *dcontext, thread_sig_info_t *info, bool other_thread); static bool execute_handler_from_cache(dcontext_t *dcontext, int sig, sigframe_rt_t *our_frame, sigcontext_t *sc_orig, fragment_t *f _IF_CLIENT(byte *access_address)); static bool execute_handler_from_dispatch(dcontext_t *dcontext, int sig); /* Execute default action from code cache and may terminate the process. * If returns, the return value decides if caller should restore * the untranslated context. */ static bool execute_default_from_cache(dcontext_t *dcontext, int sig, sigframe_rt_t *frame, sigcontext_t *sc_orig, bool forged); static void execute_default_from_dispatch(dcontext_t *dcontext, int sig, sigframe_rt_t *frame); static bool handle_alarm(dcontext_t *dcontext, int sig, kernel_ucontext_t *ucxt); static bool handle_suspend_signal(dcontext_t *dcontext, kernel_ucontext_t *ucxt, sigframe_rt_t *frame); static bool handle_nudge_signal(dcontext_t *dcontext, kernel_siginfo_t *siginfo, kernel_ucontext_t *ucxt); static void init_itimer(dcontext_t *dcontext, bool first); static bool set_actual_itimer(dcontext_t *dcontext, int which, thread_sig_info_t *info, bool enable); static bool alarm_signal_has_DR_only_itimer(dcontext_t *dcontext, int signal); #ifdef DEBUG static void dump_sigset(dcontext_t *dcontext, kernel_sigset_t *set); #endif static bool is_sys_kill(dcontext_t *dcontext, byte *pc, byte *xsp, kernel_siginfo_t *info); int sigaction_syscall(int sig, kernel_sigaction_t *act, kernel_sigaction_t *oact) { #if !defined(VMX86_SERVER) && defined(LINUX) /* PR 305020: must have SA_RESTORER for x64 */ /* i#2812: must have SA_RESTORER to handle vsyscall32 being disabled */ if (act != NULL && !TEST(SA_RESTORER, act->flags)) { act->flags |= SA_RESTORER; act->restorer = (void (*)(void))dynamorio_sigreturn; } #endif return dynamorio_syscall(IF_MACOS_ELSE(SYS_sigaction, SYS_rt_sigaction), 4, sig, act, oact, sizeof(kernel_sigset_t)); } static inline bool signal_is_interceptable(int sig) { return (sig != SIGKILL && sig != SIGSTOP); } static inline int sigaltstack_syscall(const stack_t *newstack, stack_t *oldstack) { return dynamorio_syscall(SYS_sigaltstack, 2, newstack, oldstack); } static inline int getitimer_syscall(int which, struct itimerval *val) { return dynamorio_syscall(SYS_getitimer, 2, which, val); } static inline int setitimer_syscall(int which, struct itimerval *val, struct itimerval *old) { return dynamorio_syscall(SYS_setitimer, 3, which, val, old); } static inline int sigprocmask_syscall(int how, kernel_sigset_t *set, kernel_sigset_t *oset, size_t sigsetsize) { return dynamorio_syscall(IF_MACOS_ELSE(SYS_sigprocmask, SYS_rt_sigprocmask), 4, how, set, oset, sigsetsize); } void block_all_signals_except(kernel_sigset_t *oset, int num_signals, ... /* list of signals */) { kernel_sigset_t set; kernel_sigfillset(&set); va_list ap; va_start(ap, num_signals); for (int i = 0; i < num_signals; ++i) { kernel_sigdelset(&set, va_arg(ap, int)); } va_end(ap); sigprocmask_syscall(SIG_SETMASK, &set, oset, sizeof(set)); } static void unblock_all_signals(kernel_sigset_t *oset) { kernel_sigset_t set; kernel_sigemptyset(&set); sigprocmask_syscall(SIG_SETMASK, &set, oset, sizeof(set)); } /* exported for stackdump.c */ bool set_default_signal_action(int sig) { kernel_sigset_t set; kernel_sigaction_t act; int rc; memset(&act, 0, sizeof(act)); act.handler = (handler_t)SIG_DFL; /* arm the signal */ rc = sigaction_syscall(sig, &act, NULL); DODEBUG({ removed_sig_handler = true; }); /* If we're in our handler now, we have to unblock */ kernel_sigemptyset(&set); kernel_sigaddset(&set, sig); sigprocmask_syscall(SIG_UNBLOCK, &set, NULL, sizeof(set)); return (rc == 0); } static bool set_ignore_signal_action(int sig) { kernel_sigaction_t act; int rc; memset(&act, 0, sizeof(act)); act.handler = (handler_t)SIG_IGN; /* arm the signal */ rc = sigaction_syscall(sig, &act, NULL); return (rc == 0); } /* We assume that signal handlers will be shared most of the time * (pthreads shares them) * Rather than start out with the handler table in local memory and then * having to transfer to global, we just always use global */ static void handler_free(dcontext_t *dcontext, void *p, size_t size) { global_heap_free(p, size HEAPACCT(ACCT_OTHER)); } static void * handler_alloc(dcontext_t *dcontext, size_t size) { return global_heap_alloc(size HEAPACCT(ACCT_OTHER)); } /**** top-level routines ***********************************************/ static bool os_itimers_thread_shared(void) { static bool itimers_shared; static bool cached = false; if (!cached) { file_t f = os_open("/proc/version", OS_OPEN_READ); if (f != INVALID_FILE) { char buf[128]; int major, minor, rel; os_read(f, buf, BUFFER_SIZE_ELEMENTS(buf)); NULL_TERMINATE_BUFFER(buf); if (sscanf(buf, "%*s %*s %d.%d.%d", &major, &minor, &rel) == 3) { /* Linux NPTL in kernel 2.6.12+ has POSIX-style itimers shared * among threads. */ LOG(GLOBAL, LOG_ASYNCH, 1, "kernel version = %d.%d.%d\n", major, minor, rel); itimers_shared = ((major == 2 && minor >= 6 && rel >= 12) || (major >= 3 /* linux-3.0 or above */)); cached = true; } os_close(f); } if (!cached) { /* assume not shared */ itimers_shared = false; cached = true; } LOG(GLOBAL, LOG_ASYNCH, 1, "itimers are %s\n", itimers_shared ? "thread-shared" : "thread-private"); } return itimers_shared; } static void unset_initial_crash_handlers(dcontext_t *dcontext) { ASSERT(init_info.app_sigaction != NULL); signal_info_exit_sigaction(GLOBAL_DCONTEXT, &init_info, false /*!other_thread*/); /* Undo the unblock-all */ sigprocmask_syscall(SIG_SETMASK, &init_sigmask, NULL, sizeof(init_sigmask)); DOLOG(2, LOG_ASYNCH, { LOG(THREAD, LOG_ASYNCH, 2, "initial app signal mask:\n"); dump_sigset(dcontext, &init_sigmask); }); } void d_r_signal_init(void) { kernel_sigset_t set; IF_LINUX(IF_X86_64(ASSERT(ALIGNED(offsetof(sigpending_t, xstate), AVX_ALIGNMENT)))); IF_MACOS(ASSERT(sizeof(kernel_sigset_t) == sizeof(__darwin_sigset_t))); os_itimers_thread_shared(); /* Set up a handler for safe_read (or other fault detection) during * DR init before thread is initialized. * * XXX: could set up a clone_record_t and pass to the initial * signal_thread_inherit() but that would require further code changes. * Could also call signal_thread_inherit to init this, but we don't want * to intercept timer signals, etc. before we're ready to handle them, * so we do a partial init. */ signal_info_init_sigaction(GLOBAL_DCONTEXT, &init_info); intercept_signal(GLOBAL_DCONTEXT, &init_info, SIGSEGV); intercept_signal(GLOBAL_DCONTEXT, &init_info, SIGBUS); kernel_sigemptyset(&set); kernel_sigaddset(&set, SIGSEGV); kernel_sigaddset(&set, SIGBUS); sigprocmask_syscall(SIG_UNBLOCK, &set, &init_sigmask, sizeof(set)); IF_LINUX(signalfd_init()); signal_arch_init(); } void d_r_signal_exit() { IF_LINUX(signalfd_exit()); if (init_info.app_sigaction != NULL) { /* We never took over the app (e.g., standalone mode). Restore its state. */ unset_initial_crash_handlers(GLOBAL_DCONTEXT); } #ifdef DEBUG if (d_r_stats->loglevel > 0 && (d_r_stats->logmask & (LOG_ASYNCH | LOG_STATS)) != 0) { LOG(GLOBAL, LOG_ASYNCH | LOG_STATS, 1, "Total signals delivered: %d\n", GLOBAL_STAT(num_signals)); } #endif } #ifdef HAVE_SIGALTSTACK /* Separated out to run from the dstack (i#2016: see below). */ static void set_our_alt_stack(void *arg) { thread_sig_info_t *info = (thread_sig_info_t *)arg; DEBUG_DECLARE(int rc =) sigaltstack_syscall(&info->sigstack, &info->app_sigstack); ASSERT(rc == 0); } #endif void signal_thread_init(dcontext_t *dcontext, void *os_data) { thread_sig_info_t *info = HEAP_TYPE_ALLOC(dcontext, thread_sig_info_t, ACCT_OTHER, PROTECTED); size_t pend_unit_size = sizeof(sigpending_t) + /* include alignment for xsave on xstate */ signal_frame_extra_size(true) /* sigpending_t has xstate inside it already */ IF_LINUX(IF_X86(-sizeof(kernel_xstate_t))); IF_LINUX(IF_X86(ASSERT(!YMM_ENABLED() || ALIGNED(pend_unit_size, AVX_ALIGNMENT)))); /* all fields want to be initialized to 0 */ memset(info, 0, sizeof(thread_sig_info_t)); dcontext->signal_field = (void *)info; /* our special heap to avoid reentrancy problems * composed entirely of sigpending_t units * Note that it's fine to have the special heap do page-at-a-time * committing, which does not use locks (unless triggers reset!), * but if we need a new unit that will grab a lock: we try to * avoid that by limiting the # of pending alarm signals (PR 596768). */ info->sigheap = special_heap_init_aligned( pend_unit_size, IF_X86_ELSE(AVX_ALIGNMENT, 0), false /* cannot have any locking */, false /* -x */, true /* persistent */, pend_unit_size * DYNAMO_OPTION(max_pending_signals)); #ifdef HAVE_SIGALTSTACK /* set up alternate stack * i#552 we may terminate the process without freeing the stack, so we * stack_alloc it to exempt from the memory leak check. */ info->sigstack.ss_sp = (char *)stack_alloc(SIGSTACK_SIZE, NULL) - SIGSTACK_SIZE; info->sigstack.ss_size = SIGSTACK_SIZE; /* kernel will set xsp to sp+size to grow down from there, we don't have to */ info->sigstack.ss_flags = 0; /* i#2016: for late takeover, this app thread may already be on its own alt * stack. Not setting SA_ONSTACK for SUSPEND_SIGNAL is not sufficient to avoid * this, as our SUSPEND_SIGNAL can interrupt the app inside its own signal * handler. Thus, we simply swap to another stack temporarily to avoid the * kernel complaining. The dstack is set up but it has the clone record and * initial mcxt, so we use the new alt stack. */ call_switch_stack((void *)info, (byte *)info->sigstack.ss_sp + info->sigstack.ss_size, set_our_alt_stack, NULL, true /*return*/); LOG(THREAD, LOG_ASYNCH, 1, "signal stack is " PFX " - " PFX "\n", info->sigstack.ss_sp, info->sigstack.ss_sp + info->sigstack.ss_size); /* app_sigstack dealt with below, based on parentage */ #endif kernel_sigemptyset(&info->app_sigblocked); ASSIGN_INIT_LOCK_FREE(info->child_lock, child_lock); /* signal_thread_inherit() finishes per-thread init and is invoked * by os_thread_init_finalize(): we need it after synch_thread_init() and * other post-os_thread_init() setup b/c we can't yet record pending signals, * but we need it before we give up thread_initexit_lock so we can handle * our own suspend signals (i#2779). */ } bool is_thread_signal_info_initialized(dcontext_t *dcontext) { thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field; return info->fully_initialized; } /* i#27: create custom data to pass to the child of a clone * since we can't rely on being able to find the caller, or that * its syscall data is still valid, once in the child. * * i#149/ PR 403015: The clone record is passed to the new thread via the dstack * created for it. Unlike before, where the child thread would create its own * dstack, now the parent thread creates the dstack. Also, switches app stack * to dstack. * * XXX i#1403: for Mac we want to eventually do lower-level earlier interception * of threads, but for now we're later and higher-level, intercepting the user * thread function on the new thread's stack. We ignore app_thread_xsp. */ void * #ifdef MACOS create_clone_record(dcontext_t *dcontext, reg_t *app_thread_xsp, app_pc thread_func, void *thread_arg) #else create_clone_record(dcontext_t *dcontext, reg_t *app_thread_xsp) #endif { clone_record_t *record; byte *dstack = stack_alloc(DYNAMORIO_STACK_SIZE, NULL); LOG(THREAD, LOG_ASYNCH, 1, "create_clone_record: dstack for new thread is " PFX "\n", dstack); #ifdef MACOS if (app_thread_xsp == NULL) { record = HEAP_TYPE_ALLOC(GLOBAL_DCONTEXT, clone_record_t, ACCT_THREAD_MGT, true /*prot*/); record->app_thread_xsp = 0; record->continuation_pc = thread_func; record->thread_arg = thread_arg; record->clone_flags = CLONE_THREAD | CLONE_VM | CLONE_SIGHAND | SIGCHLD; } else { #endif /* Note, the stack grows to low memory addr, so dstack points to the high * end of the allocated stack region. So, we must subtract to get space for * the clone record. */ record = (clone_record_t *)(dstack - sizeof(clone_record_t)); ASSERT(ALIGNED(record, get_ABI_stack_alignment())); record->app_thread_xsp = *app_thread_xsp; /* asynch_target is set in d_r_dispatch() prior to calling pre_system_call(). */ record->continuation_pc = dcontext->asynch_target; record->clone_flags = dcontext->sys_param0; #ifdef MACOS } #endif LOG(THREAD, LOG_ASYNCH, 1, "allocated clone record: " PFX "\n", record); record->dstack = dstack; record->caller_id = dcontext->owning_thread; record->clone_sysnum = dcontext->sys_num; record->info = *((thread_sig_info_t *)dcontext->signal_field); /* Sigstack is not inherited so clear it now to avoid having to figure out * where it got its value in signal_thread_inherit (i#3116). */ memset(&record->info.app_sigstack, 0, sizeof(record->info.app_sigstack)); record->info.app_sigstack.ss_flags = SS_DISABLE; record->parent_info = (thread_sig_info_t *)dcontext->signal_field; record->pcprofile_info = dcontext->pcprofile_field; #ifdef AARCHXX record->app_stolen_value = get_stolen_reg_val(get_mcontext(dcontext)); # ifndef AARCH64 record->isa_mode = dr_get_isa_mode(dcontext); # endif /* If the child thread shares the same TLS with parent by not setting * CLONE_SETTLS or vfork, we put the TLS base here and clear the * thread register in new_thread_setup, so that DR can distinguish * this case from normal pthread thread creation. */ record->app_lib_tls_base = (!TEST(CLONE_SETTLS, record->clone_flags)) ? os_get_app_tls_base(dcontext, TLS_REG_LIB) : NULL; #endif LOG(THREAD, LOG_ASYNCH, 1, "create_clone_record: thread " TIDFMT ", pc " PFX "\n", record->caller_id, record->continuation_pc); #ifdef MACOS if (app_thread_xsp != NULL) { #endif /* Set the thread stack to point to the dstack, below the clone record. * Note: it's glibc who sets up the arg to the thread start function; * the kernel just does a fork + stack swap, so we can get away w/ our * own stack swap if we restore before the glibc asm code takes over. * We restore this parameter to the app value in * restore_clone_param_from_clone_record(). */ /* i#754: set stack to be XSTATE aligned for saving YMM registers */ ASSERT(ALIGNED(XSTATE_ALIGNMENT, REGPARM_END_ALIGN)); *app_thread_xsp = ALIGN_BACKWARD(record, XSTATE_ALIGNMENT); #ifdef MACOS } #endif return (void *)record; } /* This is to support dr_create_client_thread() */ void set_clone_record_fields(void *record, reg_t app_thread_xsp, app_pc continuation_pc, uint clone_sysnum, uint clone_flags) { clone_record_t *rec = (clone_record_t *)record; ASSERT(rec != NULL); rec->app_thread_xsp = app_thread_xsp; rec->continuation_pc = continuation_pc; rec->clone_sysnum = clone_sysnum; rec->clone_flags = clone_flags; } /* i#149/PR 403015: The clone record is passed to the new thread by placing it * at the bottom of the dstack, i.e., the high memory. So the new thread gets * it from the base of the dstack. The dstack is then set as the app stack. * * CAUTION: don't use a lot of stack in this routine as it gets invoked on the * dstack from new_thread_setup - this is because this routine assumes * no more than a page of dstack has been used so far since the clone * system call was done. */ void * get_clone_record(reg_t xsp) { clone_record_t *record; byte *dstack_base; /* xsp should be in a dstack, i.e., dynamorio heap. */ ASSERT(is_dynamo_address((app_pc)xsp)); /* The (size of the clone record + * stack used by new_thread_start (only for setting up priv_mcontext_t) + * stack used by new_thread_setup before calling get_clone_record()) * is less than a page. This is verified by the assert below. If it does * exceed a page, it won't happen at random during runtime, but in a * predictable way during development, which will be caught by the assert. * The current usage is about 800 bytes for clone_record + * sizeof(priv_mcontext_t) + few words in new_thread_setup before * get_clone_record() is called. */ dstack_base = (byte *)ALIGN_FORWARD(xsp, PAGE_SIZE); record = (clone_record_t *)(dstack_base - sizeof(clone_record_t)); /* dstack_base and the dstack in the clone record should be the same. */ ASSERT(dstack_base == record->dstack); #ifdef MACOS ASSERT(record->app_thread_xsp != 0); /* else it's not in dstack */ #endif return (void *)record; } /* i#149/PR 403015: App xsp is passed to the new thread via the clone record. */ reg_t get_clone_record_app_xsp(void *record) { ASSERT(record != NULL); return ((clone_record_t *)record)->app_thread_xsp; } #ifdef MACOS void * get_clone_record_thread_arg(void *record) { ASSERT(record != NULL); return ((clone_record_t *)record)->thread_arg; } #endif byte * get_clone_record_dstack(void *record) { ASSERT(record != NULL); return ((clone_record_t *)record)->dstack; } #ifdef AARCHXX reg_t get_clone_record_stolen_value(void *record) { ASSERT(record != NULL); return ((clone_record_t *)record)->app_stolen_value; } # ifndef AARCH64 uint /* dr_isa_mode_t but we have a header ordering problem */ get_clone_record_isa_mode(void *record) { ASSERT(record != NULL); return ((clone_record_t *)record)->isa_mode; } # endif void set_thread_register_from_clone_record(void *record) { /* If record->app_lib_tls_base is not NULL, it means the parent * thread did not setup TLS for the child, and we need clear the * thread register. */ if (((clone_record_t *)record)->app_lib_tls_base != NULL) write_thread_register(NULL); } void set_app_lib_tls_base_from_clone_record(dcontext_t *dcontext, void *record) { if (((clone_record_t *)record)->app_lib_tls_base != NULL) { /* child and parent share the same TLS */ os_set_app_tls_base(dcontext, TLS_REG_LIB, ((clone_record_t *)record)->app_lib_tls_base); } } #endif void restore_clone_param_from_clone_record(dcontext_t *dcontext, void *record) { #ifdef LINUX ASSERT(record != NULL); clone_record_t *crec = (clone_record_t *)record; if (crec->clone_sysnum == SYS_clone && TEST(CLONE_VM, crec->clone_flags)) { /* Restore the original stack parameter to the syscall, which we clobbered * in create_clone_record(). Some apps examine it post-syscall (i#3171). */ set_syscall_param(dcontext, SYSCALL_PARAM_CLONE_STACK, get_mcontext(dcontext)->xsp); } #endif } /* Initializes info's app_sigaction, restorer_valid, and we_intercept fields */ static void signal_info_init_sigaction(dcontext_t *dcontext, thread_sig_info_t *info) { info->app_sigaction = (kernel_sigaction_t **)handler_alloc( dcontext, SIGARRAY_SIZE * sizeof(kernel_sigaction_t *)); memset(info->app_sigaction, 0, SIGARRAY_SIZE * sizeof(kernel_sigaction_t *)); memset(&info->restorer_valid, -1, SIGARRAY_SIZE * sizeof(info->restorer_valid[0])); info->we_intercept = (bool *)handler_alloc(dcontext, SIGARRAY_SIZE * sizeof(bool)); memset(info->we_intercept, 0, SIGARRAY_SIZE * sizeof(bool)); } /* Cleans up info's app_sigaction and we_intercept entries */ static void signal_info_exit_sigaction(dcontext_t *dcontext, thread_sig_info_t *info, bool other_thread) { int i; kernel_sigaction_t act; memset(&act, 0, sizeof(act)); act.handler = (handler_t)SIG_DFL; kernel_sigemptyset(&act.mask); /* does mask matter for SIG_DFL? */ for (i = 1; i <= MAX_SIGNUM; i++) { if (sig_is_alarm_signal(i) && doing_detach && IF_CLIENT_INTERFACE(!standalone_library &&) alarm_signal_has_DR_only_itimer(dcontext, i)) { /* We ignore alarms *during* detach in signal_remove_alarm_handlers(), * but to avoid crashing on an alarm arriving post-detach we set to * SIG_IGN if we have an itimer and the app does not (a slight * transparency violation to gain robustness: i#2270). */ set_ignore_signal_action(i); } else if (!other_thread) { if (info->app_sigaction[i] != NULL) { /* Restore to old handler, but not if exiting whole process: * else may get itimer during cleanup, so we set to SIG_IGN. We * do this during detach in signal_remove_alarm_handlers() (and * post-detach above). */ if (dynamo_exited && !doing_detach) { info->app_sigaction[i]->handler = (handler_t)SIG_IGN; } LOG(THREAD, LOG_ASYNCH, 2, "\trestoring " PFX " as handler for %d\n", info->app_sigaction[i]->handler, i); sigaction_syscall(i, info->app_sigaction[i], NULL); } else if (info->we_intercept[i]) { /* restore to default */ LOG(THREAD, LOG_ASYNCH, 2, "\trestoring SIG_DFL as handler for %d\n", i); sigaction_syscall(i, &act, NULL); } } if (info->app_sigaction[i] != NULL) { handler_free(dcontext, info->app_sigaction[i], sizeof(kernel_sigaction_t)); } } handler_free(dcontext, info->app_sigaction, SIGARRAY_SIZE * sizeof(kernel_sigaction_t *)); info->app_sigaction = NULL; handler_free(dcontext, info->we_intercept, SIGARRAY_SIZE * sizeof(bool)); info->we_intercept = NULL; } /* Called to finalize per-thread initialization. * Inherited and shared fields are set up here. * The clone_record contains the continuation pc, which is stored in dcontext->next_tag. */ void signal_thread_inherit(dcontext_t *dcontext, void *clone_record) { clone_record_t *record = (clone_record_t *)clone_record; thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field; int i; if (record != NULL) { LOG(THREAD, LOG_ASYNCH, 1, "continuation pc is " PFX "\n", record->continuation_pc); dcontext->next_tag = record->continuation_pc; LOG(THREAD, LOG_ASYNCH, 1, "parent tid is " TIDFMT ", parent sysnum is %d(%s), clone flags=" PIFX "\n", record->caller_id, record->clone_sysnum, #ifdef SYS_vfork (record->clone_sysnum == SYS_vfork) ? "vfork" : #endif (IF_LINUX(record->clone_sysnum == SYS_clone ? "clone" :) IF_MACOS( record->clone_sysnum == SYS_bsdthread_create ? "bsdthread_create" :) "unexpected"), record->clone_flags); #ifdef SYS_vfork if (record->clone_sysnum == SYS_vfork) { /* The above clone_flags argument is bogus. SYS_vfork doesn't have a free register to keep the hardcoded value see /usr/src/linux/arch/i386/kernel/process.c */ /* CHECK: is this the only place real clone flags are needed? */ record->clone_flags = CLONE_VFORK | CLONE_VM | SIGCHLD; } #endif /* handlers are either inherited or shared */ if (TEST(CLONE_SIGHAND, record->clone_flags)) { /* need to share table of handlers! */ LOG(THREAD, LOG_ASYNCH, 2, "sharing signal handlers with parent\n"); info->shared_app_sigaction = true; info->shared_refcount = record->info.shared_refcount; info->shared_lock = record->info.shared_lock; info->app_sigaction = record->info.app_sigaction; info->we_intercept = record->info.we_intercept; d_r_mutex_lock(info->shared_lock); (*info->shared_refcount)++; #ifdef DEBUG for (i = 1; i <= MAX_SIGNUM; i++) { if (info->app_sigaction[i] != NULL) { LOG(THREAD, LOG_ASYNCH, 2, "\thandler for signal %d is " PFX "\n", i, info->app_sigaction[i]->handler); } } #endif d_r_mutex_unlock(info->shared_lock); } else { /* copy handlers */ LOG(THREAD, LOG_ASYNCH, 2, "inheriting signal handlers from parent\n"); info->app_sigaction = (kernel_sigaction_t **)handler_alloc( dcontext, SIGARRAY_SIZE * sizeof(kernel_sigaction_t *)); memset(info->app_sigaction, 0, SIGARRAY_SIZE * sizeof(kernel_sigaction_t *)); for (i = 1; i <= MAX_SIGNUM; i++) { info->restorer_valid[i] = -1; /* clear cache */ if (record->info.app_sigaction[i] != NULL) { info->app_sigaction[i] = (kernel_sigaction_t *)handler_alloc( dcontext, sizeof(kernel_sigaction_t)); memcpy(info->app_sigaction[i], record->info.app_sigaction[i], sizeof(kernel_sigaction_t)); LOG(THREAD, LOG_ASYNCH, 2, "\thandler for signal %d is " PFX "\n", i, info->app_sigaction[i]->handler); } } info->we_intercept = (bool *)handler_alloc(dcontext, SIGARRAY_SIZE * sizeof(bool)); memcpy(info->we_intercept, record->info.we_intercept, SIGARRAY_SIZE * sizeof(bool)); d_r_mutex_lock(&record->info.child_lock); record->info.num_unstarted_children--; d_r_mutex_unlock(&record->info.child_lock); /* this should be safe since parent should wait for us */ d_r_mutex_lock(&record->parent_info->child_lock); record->parent_info->num_unstarted_children--; d_r_mutex_unlock(&record->parent_info->child_lock); } /* itimers are either private or shared */ if (TEST(CLONE_THREAD, record->clone_flags) && os_itimers_thread_shared()) { ASSERT(record->info.shared_itimer); LOG(THREAD, LOG_ASYNCH, 2, "sharing itimers with parent\n"); info->shared_itimer = true; info->shared_itimer_refcount = record->info.shared_itimer_refcount; info->shared_itimer_underDR = record->info.shared_itimer_underDR; info->itimer = record->info.itimer; atomic_add_exchange_int((volatile int *)info->shared_itimer_refcount, 1); /* shared_itimer_underDR will be incremented in start_itimer() */ } else { info->shared_itimer = false; init_itimer(dcontext, false /*!first thread*/); } /* rest of state is never shared. * app_sigstack should already be in place, when we set up our sigstack * we asked for old sigstack. * FIXME: are current pending or blocked inherited? */ #ifdef MACOS if (record->app_thread_xsp != 0) { HEAP_TYPE_FREE(GLOBAL_DCONTEXT, record, clone_record_t, ACCT_THREAD_MGT, true /*prot*/); } #endif } else { /* Initialize in isolation */ if (APP_HAS_SIGSTACK(info)) { /* parent was NOT under our control, so the real sigstack we see is * a real sigstack that was present before we took control */ LOG(THREAD, LOG_ASYNCH, 1, "app already has signal stack " PFX " - " PFX "\n", info->app_sigstack.ss_sp, info->app_sigstack.ss_sp + info->app_sigstack.ss_size); } signal_info_init_sigaction(dcontext, info); info->shared_itimer = false; /* we'll set to true if a child is created */ init_itimer(dcontext, true /*first*/); /* We split init vs start for the signal handlers and mask. We do not * install ours until we start running the app, to avoid races like * i#2335. We'll set them up when os_process_under_dynamorio_*() invokes * signal_reinstate_handlers(). All we do now is mark which signals we * want to intercept. */ if (DYNAMO_OPTION(intercept_all_signals)) { /* PR 304708: to support client signal handlers without * the complexity of per-thread and per-signal callbacks * we always intercept all signals. We also check here * for handlers the app registered before our init. */ for (i = 1; i <= MAX_SIGNUM; i++) { /* cannot intercept KILL or STOP */ if (signal_is_interceptable(i) && /* FIXME PR 297033: we don't support intercepting DEFAULT_STOP / * DEFAULT_CONTINUE signals. Once add support, update * dr_register_signal_event() comments. */ default_action[i] != DEFAULT_STOP && default_action[i] != DEFAULT_CONTINUE) info->we_intercept[i] = true; } } else { /* we intercept the following signals ourselves: */ info->we_intercept[SIGSEGV] = true; /* PR 313665: look for DR crashes on unaligned memory or mmap bounds */ info->we_intercept[SIGBUS] = true; /* PR 212090: the signal we use to suspend threads */ info->we_intercept[SUSPEND_SIGNAL] = true; #ifdef PAPI /* use SIGPROF for updating gui so it can be distinguished from SIGVTALRM */ info->we_intercept[SIGPROF] = true; #endif /* vtalarm only used with pc profiling. it interferes w/ PAPI * so arm this signal only if necessary */ if (INTERNAL_OPTION(profile_pcs)) { info->we_intercept[SIGVTALRM] = true; } #ifdef CLIENT_INTERFACE info->we_intercept[SIGALRM] = true; #endif #ifdef SIDELINE info->we_intercept[SIGCHLD] = true; #endif /* i#61/PR 211530: the signal we use for nudges */ info->we_intercept[NUDGESIG_SIGNUM] = true; } /* should be 1st thread */ if (d_r_get_num_threads() > 1) ASSERT_NOT_REACHED(); } /* only when SIGVTALRM handler is in place should we start itimer (PR 537743) */ if (INTERNAL_OPTION(profile_pcs)) { /* even if the parent thread exits, we can use a pointer to its * pcprofile_info b/c when shared it's process-shared and is not freed * until the entire process exits */ pcprofile_thread_init(dcontext, info->shared_itimer, (record == NULL) ? NULL : record->pcprofile_info); } info->pre_syscall_app_sigprocmask_valid = false; /* Assumed to be async safe. */ info->fully_initialized = true; } /* When taking over existing app threads, we assume they're using pthreads and * expect to share signal handlers, memory, thread group id, etc. * Invokes dynamo_thread_init() with the appropriate os_data. */ dcontext_t * init_thread_with_shared_siginfo(priv_mcontext_t *mc, dcontext_t *takeover_dc) { clone_record_t crec = { 0, }; thread_sig_info_t *parent_siginfo = (thread_sig_info_t *)takeover_dc->signal_field; /* Create a fake clone record with the given siginfo. All threads in the * same thread group must share signal handlers since Linux 2.5.35, but we * have to guess at the other flags. * FIXME i#764: If we take over non-pthreads threads, we'll need some way to * tell if they're sharing signal handlers or not. */ crec.caller_id = takeover_dc->owning_thread; #ifdef LINUX crec.clone_sysnum = SYS_clone; #else ASSERT_NOT_IMPLEMENTED(false); /* FIXME i#58: NYI on Mac */ #endif crec.clone_flags = PTHREAD_CLONE_FLAGS; crec.parent_info = parent_siginfo; crec.info = *parent_siginfo; crec.pcprofile_info = takeover_dc->pcprofile_field; IF_DEBUG(int r =) dynamo_thread_init(NULL, mc, &crec _IF_CLIENT_INTERFACE(false)); ASSERT(r == SUCCESS); return get_thread_private_dcontext(); } static void free_pending_signal(thread_sig_info_t *info, int sig) { sigpending_t *temp = info->sigpending[sig]; info->sigpending[sig] = temp->next; special_heap_free(info->sigheap, temp); info->num_pending--; } /* This is split from os_fork_init() so the new logfiles are available * (xref i#189/PR 452168). It had to be after dynamo_other_thread_exit() * called in dynamorio_fork_init() after os_fork_init() else we clean * up data structs used in signal_thread_exit(). */ void signal_fork_init(dcontext_t *dcontext) { thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field; int i; /* Child of fork is a single thread in a new process so should * start over w/ no sharing (xref i#190/PR 452178) */ if (info->shared_app_sigaction) { info->shared_app_sigaction = false; if (info->shared_lock != NULL) { DELETE_LOCK(*info->shared_lock); global_heap_free(info->shared_lock, sizeof(mutex_t) HEAPACCT(ACCT_OTHER)); } if (info->shared_refcount != NULL) global_heap_free(info->shared_refcount, sizeof(int) HEAPACCT(ACCT_OTHER)); info->shared_lock = NULL; info->shared_refcount = NULL; } if (info->shared_itimer) { /* itimers are not inherited across fork */ info->shared_itimer = false; for (i = 0; i < NUM_ITIMERS; i++) DELETE_RECURSIVE_LOCK((*info->itimer)[i].lock); if (os_itimers_thread_shared()) global_heap_free(info->itimer, sizeof(*info->itimer) HEAPACCT(ACCT_OTHER)); else heap_free(dcontext, info->itimer, sizeof(*info->itimer) HEAPACCT(ACCT_OTHER)); info->itimer = NULL; /* reset by init_itimer */ ASSERT(info->shared_itimer_refcount != NULL); global_heap_free(info->shared_itimer_refcount, sizeof(int) HEAPACCT(ACCT_OTHER)); info->shared_itimer_refcount = NULL; ASSERT(info->shared_itimer_underDR != NULL); global_heap_free(info->shared_itimer_underDR, sizeof(int) HEAPACCT(ACCT_OTHER)); info->shared_itimer_underDR = NULL; init_itimer(dcontext, true /*first*/); } info->num_unstarted_children = 0; for (i = 1; i <= MAX_SIGNUM; i++) { /* "A child created via fork(2) initially has an empty pending signal set" */ dcontext->signals_pending = 0; while (info->sigpending[i] != NULL) { free_pending_signal(info, i); } info->num_pending = 0; } if (INTERNAL_OPTION(profile_pcs)) { pcprofile_fork_init(dcontext); } info->pre_syscall_app_sigprocmask_valid = false; /* Assumed to be async safe. */ info->fully_initialized = true; } #ifdef DEBUG static bool sigsegv_handler_is_ours(void) { int rc; kernel_sigaction_t oldact; rc = sigaction_syscall(SIGSEGV, NULL, &oldact); return (rc == 0 && oldact.handler == (handler_t)master_signal_handler); } #endif /* DEBUG */ #if defined(X86) && defined(LINUX) static byte * get_xstate_buffer(dcontext_t *dcontext) { /* See thread_sig_info_t.xstate_buf comments for why this is in TLS. */ thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field; if (info->xstate_buf == NULL) { info->xstate_alloc = heap_alloc(dcontext, signal_frame_extra_size(true) HEAPACCT(ACCT_OTHER)); info->xstate_buf = (byte *)ALIGN_FORWARD(info->xstate_alloc, XSTATE_ALIGNMENT); ASSERT(info->xstate_alloc + signal_frame_extra_size(true) >= info->xstate_buf + signal_frame_extra_size(false)); } return info->xstate_buf; } #endif void signal_thread_exit(dcontext_t *dcontext, bool other_thread) { thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field; int i; /* i#1012: DR's signal handler should always be installed before this point. */ ASSERT(sigsegv_handler_is_ours() || removed_sig_handler); while (info->num_unstarted_children > 0) { /* must wait for children to start and copy our state * before we destroy it! */ os_thread_yield(); } /* stop_itimer() was already called by os_thread_not_under_dynamo() called * from dynamo_thread_exit_common(). We need to leave the app itimers in place * in case we're detaching. */ #if defined(X86) && defined(LINUX) if (info->xstate_alloc != NULL) { heap_free(dcontext, info->xstate_alloc, signal_frame_extra_size(true) HEAPACCT(ACCT_OTHER)); } #endif /* FIXME: w/ shared handlers, if parent (the owner here) dies, * can children keep living w/ a copy of the handlers? */ if (info->shared_app_sigaction) { d_r_mutex_lock(info->shared_lock); (*info->shared_refcount)--; d_r_mutex_unlock(info->shared_lock); } if (!info->shared_app_sigaction || *info->shared_refcount == 0) { LOG(THREAD, LOG_ASYNCH, 2, "signal handler cleanup:\n"); signal_info_exit_sigaction(dcontext, info, other_thread); if (info->shared_lock != NULL) { DELETE_LOCK(*info->shared_lock); global_heap_free(info->shared_lock, sizeof(mutex_t) HEAPACCT(ACCT_OTHER)); } if (info->shared_refcount != NULL) global_heap_free(info->shared_refcount, sizeof(int) HEAPACCT(ACCT_OTHER)); } if (info->shared_itimer) { atomic_add_exchange_int((volatile int *)info->shared_itimer_refcount, -1); } if (!info->shared_itimer || *info->shared_itimer_refcount == 0) { if (INTERNAL_OPTION(profile_pcs)) { /* no cleanup needed for non-final thread in group */ pcprofile_thread_exit(dcontext); } for (i = 0; i < NUM_ITIMERS; i++) DELETE_RECURSIVE_LOCK((*info->itimer)[i].lock); if (os_itimers_thread_shared()) global_heap_free(info->itimer, sizeof(*info->itimer) HEAPACCT(ACCT_OTHER)); else heap_free(dcontext, info->itimer, sizeof(*info->itimer) HEAPACCT(ACCT_OTHER)); if (info->shared_itimer_refcount != NULL) { global_heap_free(info->shared_itimer_refcount, sizeof(int) HEAPACCT(ACCT_OTHER)); ASSERT(info->shared_itimer_underDR != NULL); global_heap_free(info->shared_itimer_underDR, sizeof(int) HEAPACCT(ACCT_OTHER)); } } for (i = 1; i <= MAX_SIGNUM; i++) { /* pending queue is per-thread and not shared */ while (info->sigpending[i] != NULL) { sigpending_t *temp = info->sigpending[i]; info->sigpending[i] = temp->next; special_heap_free(info->sigheap, temp); } info->num_pending = 0; } /* If no detach flag is set, we assume that this thread is on its way to exit. * In order to prevent receiving signals while a thread is on its way to exit * without a valid dcontext, signals at this stage are blocked. The exceptions * are the suspend signal and any signal that a terminating SYS_kill may need. * (i#2921). In this case, we do not want to restore the signal mask. For detach, * we do need to restore the app's mask. */ if (!other_thread && doing_detach) signal_swap_mask(dcontext, true /*to_app*/); #ifdef HAVE_SIGALTSTACK /* Remove our sigstack and restore the app sigstack if it had one. */ if (!other_thread) { LOG(THREAD, LOG_ASYNCH, 2, "removing our signal stack " PFX " - " PFX "\n", info->sigstack.ss_sp, info->sigstack.ss_sp + info->sigstack.ss_size); if (APP_HAS_SIGSTACK(info)) { LOG(THREAD, LOG_ASYNCH, 2, "restoring app signal stack " PFX " - " PFX "\n", info->app_sigstack.ss_sp, info->app_sigstack.ss_sp + info->app_sigstack.ss_size); } else { ASSERT(TEST(SS_DISABLE, info->app_sigstack.ss_flags)); } if (info->sigstack.ss_sp != NULL) { /* i#552: to raise client exit event, we may call dynamo_process_exit * on sigstack in signal handler. * In that case we set sigstack (ss_sp) NULL to avoid stack swap. */ # ifdef MACOS if (info->app_sigstack.ss_sp == NULL) { /* Kernel fails w/ ENOMEM (even for SS_DISABLE) if ss_size is too small */ info->sigstack.ss_flags = SS_DISABLE; i = sigaltstack_syscall(&info->sigstack, NULL); /* i#1814: kernel gives EINVAL if last handler didn't call sigreturn! */ ASSERT(i == 0 || i == -EINVAL); } else { i = sigaltstack_syscall(&info->app_sigstack, NULL); /* i#1814: kernel gives EINVAL if last handler didn't call sigreturn! */ ASSERT(i == 0 || i == -EINVAL); } # else i = sigaltstack_syscall(&info->app_sigstack, NULL); ASSERT(i == 0); # endif } } #endif IF_LINUX(signalfd_thread_exit(dcontext, info)); special_heap_exit(info->sigheap); DELETE_LOCK(info->child_lock); #ifdef DEBUG /* for non-debug we do fast exit path and don't free local heap */ # ifdef HAVE_SIGALTSTACK if (info->sigstack.ss_sp != NULL) { /* i#552: to raise client exit event, we may call dynamo_process_exit * on sigstack in signal handler. * In that case we set sigstack (ss_sp) NULL to avoid stack free. */ stack_free(info->sigstack.ss_sp + info->sigstack.ss_size, info->sigstack.ss_size); } # endif HEAP_TYPE_FREE(dcontext, info, thread_sig_info_t, ACCT_OTHER, PROTECTED); #endif #ifdef PAPI /* use SIGPROF for updating gui so it can be distinguished from SIGVTALRM */ set_itimer_callback( dcontext, ITIMER_PROF, 500, (void (*func)(dcontext_t *, priv_mcontext_t *))perfctr_update_gui()); #endif } void set_handler_sigact(kernel_sigaction_t *act, int sig, handler_t handler) { act->handler = handler; #ifdef MACOS /* This is the real target */ act->tramp = (tramp_t)handler; #endif act->flags = SA_SIGINFO; /* send 3 args to handler */ #ifdef HAVE_SIGALTSTACK act->flags |= SA_ONSTACK; /* use our sigstack */ #endif /* We want the kernel to help us auto-restart syscalls, esp. when our signals * interrupt native code such as during attach or in client or DR code (i#2659). */ act->flags |= SA_RESTART; #if !defined(VMX86_SERVER) && defined(LINUX) /* PR 305020: must have SA_RESTORER for x64 */ /* i#2812: must have SA_RESTORER to handle vsyscall32 being disabled */ act->flags |= SA_RESTORER; act->restorer = (void (*)(void))dynamorio_sigreturn; #endif /* We block most signals within our handler */ kernel_sigfillset(&act->mask); /* i#184/PR 450670: we let our suspend signal interrupt our own handler * We never send more than one before resuming, so no danger to stack usage * from our own: but app could pile them up. */ kernel_sigdelset(&act->mask, SUSPEND_SIGNAL); /* i#193/PR 287309: we need to NOT suppress further SIGSEGV, for decode faults, * for try/except, and for !HAVE_MEMINFO probes. * Just like SUSPEND_SIGNAL, if app sends repeated SEGV, could run out of * alt stack: seems too corner-case to be worth increasing stack size. */ kernel_sigdelset(&act->mask, SIGSEGV); if (sig == SUSPEND_SIGNAL || sig == SIGSEGV) act->flags |= SA_NODEFER; /* Sigset is a 1 or 2 elt array of longs on X64/X86. Treat as 2 elt of * uint32. */ IF_DEBUG(uint32 *mask_sig = (uint32 *)&act->mask.sig[0]); LOG(THREAD_GET, LOG_ASYNCH, 3, "mask for our handler is " PFX " " PFX "\n", mask_sig[0], mask_sig[1]); } static void set_our_handler_sigact(kernel_sigaction_t *act, int sig) { set_handler_sigact(act, sig, (handler_t)master_signal_handler); } static void set_handler_and_record_app(dcontext_t *dcontext, thread_sig_info_t *info, int sig, kernel_sigaction_t *act) { int rc; kernel_sigaction_t oldact; ASSERT(sig <= MAX_SIGNUM); /* arm the signal */ rc = sigaction_syscall(sig, act, &oldact); ASSERT(rc == 0 /* Workaround for PR 223720, which was fixed in ESX4.0 but * is present in ESX3.5 and earlier: vmkernel treats * 63 and 64 as invalid signal numbers. */ IF_VMX86(|| (sig >= 63 && rc == -EINVAL))); if (rc != 0) /* be defensive: app will probably still work */ return; if (oldact.handler != (handler_t)SIG_DFL && oldact.handler != (handler_t)master_signal_handler) { /* save the app's action for sig */ if (info->shared_app_sigaction) { /* app_sigaction structure is shared */ d_r_mutex_lock(info->shared_lock); } if (info->app_sigaction[sig] != NULL) { /* go ahead and toss the old one, it's up to the app to store * and then restore later if it wants to */ handler_free(dcontext, info->app_sigaction[sig], sizeof(kernel_sigaction_t)); } info->app_sigaction[sig] = (kernel_sigaction_t *)handler_alloc(dcontext, sizeof(kernel_sigaction_t)); memcpy(info->app_sigaction[sig], &oldact, sizeof(kernel_sigaction_t)); /* clear cache */ info->restorer_valid[sig] = -1; if (info->shared_app_sigaction) d_r_mutex_unlock(info->shared_lock); #ifdef DEBUG if (oldact.handler == (handler_t)SIG_IGN) { LOG(THREAD, LOG_ASYNCH, 2, "app already installed SIG_IGN as sigaction for signal %d\n", sig); } else { LOG(THREAD, LOG_ASYNCH, 2, "app already installed " PFX " as sigaction flags=0x%x for signal %d\n", oldact.handler, oldact.flags, sig); } #endif } else { LOG(THREAD, LOG_ASYNCH, 2, "prior handler is " PFX " vs master " PFX " with flags=0x%x for signal %d\n", oldact.handler, master_signal_handler, oldact.flags, sig); if (info->app_sigaction[sig] != NULL) { if (info->shared_app_sigaction) d_r_mutex_lock(info->shared_lock); handler_free(dcontext, info->app_sigaction[sig], sizeof(kernel_sigaction_t)); info->app_sigaction[sig] = NULL; if (info->shared_app_sigaction) d_r_mutex_unlock(info->shared_lock); } } LOG(THREAD, LOG_ASYNCH, 3, "\twe intercept signal %d\n", sig); } /* Set up master_signal_handler as the handler for signal "sig", * for the current thread. Since we deal with kernel data structures * in our interception of system calls, we use them here as well, * to avoid having to translate to/from libc data structures. */ static void intercept_signal(dcontext_t *dcontext, thread_sig_info_t *info, int sig) { kernel_sigaction_t act; ASSERT(sig <= MAX_SIGNUM); set_our_handler_sigact(&act, sig); set_handler_and_record_app(dcontext, info, sig, &act); } static void intercept_signal_ignore_initially(dcontext_t *dcontext, thread_sig_info_t *info, int sig) { kernel_sigaction_t act; ASSERT(sig <= MAX_SIGNUM); memset(&act, 0, sizeof(act)); act.handler = (handler_t)SIG_IGN; set_handler_and_record_app(dcontext, info, sig, &act); } static void intercept_signal_no_longer_ignore(dcontext_t *dcontext, thread_sig_info_t *info, int sig) { kernel_sigaction_t act; int rc; ASSERT(sig <= MAX_SIGNUM); set_our_handler_sigact(&act, sig); rc = sigaction_syscall(sig, &act, NULL); ASSERT(rc == 0); } /* i#1921: For proper single-threaded native execution with re-takeover we need * to propagate signals. For now we only support going completely native in * this thread but without a full detach, so we abandon our signal handlers w/o * freeing memory up front. * We also use this for the start/stop interface where we are going fully native * for all threads. */ void signal_remove_handlers(dcontext_t *dcontext) { thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field; int i; kernel_sigaction_t act; memset(&act, 0, sizeof(act)); act.handler = (handler_t)SIG_DFL; kernel_sigemptyset(&act.mask); for (i = 1; i <= MAX_SIGNUM; i++) { if (info->app_sigaction[i] != NULL) { LOG(THREAD, LOG_ASYNCH, 2, "\trestoring " PFX " as handler for %d\n", info->app_sigaction[i]->handler, i); sigaction_syscall(i, info->app_sigaction[i], NULL); } else if (info->we_intercept[i]) { /* restore to default */ LOG(THREAD, LOG_ASYNCH, 2, "\trestoring SIG_DFL as handler for %d\n", i); sigaction_syscall(i, &act, NULL); } } DODEBUG({ removed_sig_handler = true; }); } void signal_remove_alarm_handlers(dcontext_t *dcontext) { thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field; int i; for (i = 1; i <= MAX_SIGNUM; i++) { if (!info->we_intercept[i]) continue; if (sig_is_alarm_signal(i)) { set_ignore_signal_action(i); } } } /* For attaching mid-run, we assume regular POSIX with handlers global to just one * thread group in the process. * We also use this routine for the initial setup of our handlers, which we * split from signal_thread_inherit() to support start/stop. */ void signal_reinstate_handlers(dcontext_t *dcontext, bool ignore_alarm) { thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field; int i; for (i = 1; i <= MAX_SIGNUM; i++) { bool skip = false; if (!info->we_intercept[i]) { skip = true; if (signal_is_interceptable(i)) { /* We do have to intercept everything the app does. * If the app removes its handler, we'll never remove ours, which we * can live with. */ kernel_sigaction_t oldact; int rc = sigaction_syscall(i, NULL, &oldact); ASSERT(rc == 0); if (rc == 0 && oldact.handler != (handler_t)SIG_DFL && oldact.handler != (handler_t)master_signal_handler) { skip = false; } } } if (skip) continue; if (sig_is_alarm_signal(i) && ignore_alarm) { LOG(THREAD, LOG_ASYNCH, 2, "\tignoring %d initially\n", i); intercept_signal_ignore_initially(dcontext, info, i); } else { LOG(THREAD, LOG_ASYNCH, 2, "\trestoring DR handler for %d\n", i); intercept_signal(dcontext, info, i); } } DODEBUG({ removed_sig_handler = false; }); } void signal_reinstate_alarm_handlers(dcontext_t *dcontext) { thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field; int i; for (i = 1; i <= MAX_SIGNUM; i++) { if (!info->we_intercept[i] || !sig_is_alarm_signal(i)) continue; LOG(THREAD, LOG_ASYNCH, 2, "\trestoring DR handler for %d\n", i); intercept_signal_no_longer_ignore(dcontext, info, i); } } /**** system call handlers ***********************************************/ /* FIXME: invalid pointer passed to kernel will currently show up * probably as a segfault in our handlers below...need to make them * look like kernel, and pass error code back to os.c */ void handle_clone(dcontext_t *dcontext, uint flags) { thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field; if ((flags & CLONE_VM) == 0) { /* separate process not sharing memory */ if ((flags & CLONE_SIGHAND) != 0) { /* FIXME: how deal with this? * "man clone" says: "Since Linux 2.6.0-test6, flags must also * include CLONE_VM if CLONE_SIGHAND is specified" */ LOG(THREAD, LOG_ASYNCH, 1, "WARNING: !CLONE_VM but CLONE_SIGHAND!\n"); ASSERT_NOT_IMPLEMENTED(false); } return; } pre_second_thread(); if ((flags & CLONE_SIGHAND) != 0) { /* need to share table of handlers! */ LOG(THREAD, LOG_ASYNCH, 2, "handle_clone: CLONE_SIGHAND set!\n"); if (!info->shared_app_sigaction) { /* this is the start of a chain of sharing * no synch needed here, child not created yet */ info->shared_app_sigaction = true; info->shared_refcount = (int *)global_heap_alloc(sizeof(int) HEAPACCT(ACCT_OTHER)); *info->shared_refcount = 1; info->shared_lock = (mutex_t *)global_heap_alloc(sizeof(mutex_t) HEAPACCT(ACCT_OTHER)); ASSIGN_INIT_LOCK_FREE(*info->shared_lock, shared_lock); } /* else, some ancestor is already owner */ } else { /* child will inherit copy of current table -> cannot modify it * until child is scheduled! FIXME: any other way? */ d_r_mutex_lock(&info->child_lock); info->num_unstarted_children++; d_r_mutex_unlock(&info->child_lock); } if (TEST(CLONE_THREAD, flags) && os_itimers_thread_shared()) { if (!info->shared_itimer) { /* this is the start of a chain of sharing * no synch needed here, child not created yet */ info->shared_itimer = true; info->shared_itimer_refcount = (int *)global_heap_alloc(sizeof(int) HEAPACCT(ACCT_OTHER)); *info->shared_itimer_refcount = 1; info->shared_itimer_underDR = (int *)global_heap_alloc(sizeof(int) HEAPACCT(ACCT_OTHER)); *info->shared_itimer_underDR = 1; } /* else, some ancestor already created */ } } /* Returns false if should NOT issue syscall. * In such a case, the result is in "result". * If *result is non-zero, the syscall should fail. * We could instead issue the syscall and expect it to fail, which would have a more * accurate error code, but that risks missing a failure (e.g., RT on Android * which in some cases returns success on bugus params). * It seems better to err on the side of the wrong error code or failing when * we shouldn't, than to think it failed when it didn't, which is more complex * to deal with. */ bool handle_sigaction(dcontext_t *dcontext, int sig, const kernel_sigaction_t *act, prev_sigaction_t *oact, size_t sigsetsize, OUT uint *result) { thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field; kernel_sigaction_t *save; kernel_sigaction_t local_act; if (sigsetsize != sizeof(kernel_sigset_t)) { *result = EINVAL; return false; } if (act != NULL) { /* Linux checks readability before checking the signal number. */ if (!d_r_safe_read(act, sizeof(local_act), &local_act)) { *result = EFAULT; return false; } } /* i#1135: app may pass invalid signum to find MAX_SIGNUM */ if (sig <= 0 || sig > MAX_SIGNUM || (act != NULL && !signal_is_interceptable(sig))) { *result = EINVAL; return false; } if (act != NULL) { /* app is installing a new action */ while (info->num_unstarted_children > 0) { /* must wait for children to start and copy our state * before we modify it! */ os_thread_yield(); } info->sigaction_param = act; } if (info->shared_app_sigaction) { /* app_sigaction structure is shared */ d_r_mutex_lock(info->shared_lock); } if (oact != NULL) { /* Keep a copy of the prior one for post-syscall to hand to the app. */ info->use_kernel_prior_sigaction = false; if (info->app_sigaction[sig] == NULL) { if (info->we_intercept[sig]) { /* need to pretend there is no handler */ memset(&info->prior_app_sigaction, 0, sizeof(info->prior_app_sigaction)); info->prior_app_sigaction.handler = (handler_t)SIG_DFL; } else { info->use_kernel_prior_sigaction = true; } } else { memcpy(&info->prior_app_sigaction, info->app_sigaction[sig], sizeof(info->prior_app_sigaction)); } } if (act != NULL) { if (local_act.handler == (handler_t)SIG_IGN || local_act.handler == (handler_t)SIG_DFL) { LOG(THREAD, LOG_ASYNCH, 2, "app installed %s as sigaction for signal %d\n", (local_act.handler == (handler_t)SIG_IGN) ? "SIG_IGN" : "SIG_DFL", sig); if (!info->we_intercept[sig]) { /* let the SIG_IGN/SIG_DFL go through, we want to remove our * handler. we delete the stored app_sigaction in post_ */ if (info->shared_app_sigaction) d_r_mutex_unlock(info->shared_lock); return true; } } else { LOG(THREAD, LOG_ASYNCH, 2, "app installed " PFX " as sigaction for signal %d\n", local_act.handler, sig); DOLOG(2, LOG_ASYNCH, { LOG(THREAD, LOG_ASYNCH, 2, "signal mask for handler:\n"); dump_sigset(dcontext, (kernel_sigset_t *)&local_act.mask); }); } /* save app's entire sigaction struct */ save = (kernel_sigaction_t *)handler_alloc(dcontext, sizeof(kernel_sigaction_t)); memcpy(save, &local_act, sizeof(kernel_sigaction_t)); /* Remove the unblockable sigs */ kernel_sigdelset(&save->mask, SIGKILL); kernel_sigdelset(&save->mask, SIGSTOP); #ifdef X86 /* Remove flags not allowed to be passed to the kernel (this also zeroes * the top 32 bits, like the kernel does: i#3681). */ save->flags &= ~(SA_IA32_ABI | SA_X32_ABI); #endif if (info->app_sigaction[sig] != NULL) { /* go ahead and toss the old one, it's up to the app to store * and then restore later if it wants to */ handler_free(dcontext, info->app_sigaction[sig], sizeof(kernel_sigaction_t)); } info->app_sigaction[sig] = save; LOG(THREAD, LOG_ASYNCH, 3, "\tflags = " PFX ", %s = " PFX "\n", local_act.flags, IF_MACOS_ELSE("tramp", "restorer"), IF_MACOS_ELSE(local_act.tramp, local_act.restorer)); /* clear cache */ info->restorer_valid[sig] = -1; } if (info->shared_app_sigaction) d_r_mutex_unlock(info->shared_lock); if (info->we_intercept[sig]) { /* cancel the syscall */ *result = handle_post_sigaction(dcontext, true, sig, act, oact, sigsetsize); return false; } if (act != NULL) { /* Now hand kernel our master handler instead of app's. */ set_our_handler_sigact(&info->our_sigaction, sig); set_syscall_param(dcontext, 1, (reg_t)&info->our_sigaction); /* FIXME PR 297033: we don't support intercepting DEFAULT_STOP / * DEFAULT_CONTINUE signals b/c we can't generate the default * action: if the app registers a handler, though, we should work * properly if we never see SIG_DFL. */ } return true; } /* os.c thinks it's passing us struct_sigaction, really it's kernel_sigaction_t, * which has fields in different order. * Only called on success. * Returns the desired app return value (caller will negate if nec). */ uint handle_post_sigaction(dcontext_t *dcontext, bool success, int sig, const kernel_sigaction_t *act, prev_sigaction_t *oact, size_t sigsetsize) { thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field; if (act != NULL) { /* Restore app register value, in case we changed it. */ set_syscall_param(dcontext, 1, (reg_t)info->sigaction_param); } if (!success) return 0; /* don't change return value */ ASSERT(sig <= MAX_SIGNUM && sig > 0); if (oact != NULL) { if (info->use_kernel_prior_sigaction) { /* Real syscall succeeded with oact so it must be readable, barring races. */ ASSERT(oact->handler == (handler_t)SIG_IGN || oact->handler == (handler_t)SIG_DFL); } else { /* We may have skipped the syscall so we have to check writability */ #ifdef MACOS /* On MacOS prev_sigaction_t is a different type (i#2105) */ bool fault = true; TRY_EXCEPT(dcontext, { oact->handler = info->prior_app_sigaction.handler; oact->mask = info->prior_app_sigaction.mask; oact->flags = info->prior_app_sigaction.flags; fault = false; }, { /* EXCEPT */ /* nothing: fault is already true */ }); if (fault) return EFAULT; #else if (!safe_write_ex(oact, sizeof(*oact), &info->prior_app_sigaction, NULL)) { /* We actually don't have to undo installing any passed action * b/c the Linux kernel does that *before* checking oact perms. */ return EFAULT; } #endif } } /* If installing IGN or DFL, delete ours. * XXX: This is racy. We can't hold the lock across the syscall, though. * What we should do is just drop support for -no_intercept_all_signals, * which is off by default anyway and never turned off. */ if (act != NULL && /* De-ref here should work barring races: already racy and non-default so not * bothering with safe_read. */ ((act->handler == (handler_t)SIG_IGN || act->handler == (handler_t)SIG_DFL) && !info->we_intercept[sig]) && info->app_sigaction[sig] != NULL) { if (info->shared_app_sigaction) d_r_mutex_lock(info->shared_lock); /* remove old stored app action */ handler_free(dcontext, info->app_sigaction[sig], sizeof(kernel_sigaction_t)); info->app_sigaction[sig] = NULL; if (info->shared_app_sigaction) d_r_mutex_unlock(info->shared_lock); } return 0; } #ifdef LINUX static bool convert_old_sigaction_to_kernel(dcontext_t *dcontext, kernel_sigaction_t *ks, const old_sigaction_t *os) { bool res = false; TRY_EXCEPT(dcontext, { ks->handler = os->handler; ks->flags = os->flags; ks->restorer = os->restorer; kernel_sigemptyset(&ks->mask); ks->mask.sig[0] = os->mask; res = true; }, { /* EXCEPT */ /* nothing: res is already false */ }); return res; } static bool convert_kernel_sigaction_to_old(dcontext_t *dcontext, old_sigaction_t *os, const kernel_sigaction_t *ks) { bool res = false; TRY_EXCEPT(dcontext, { os->handler = ks->handler; os->flags = ks->flags; os->restorer = ks->restorer; os->mask = ks->mask.sig[0]; res = true; }, { /* EXCEPT */ /* nothing: res is already false */ }); return res; } /* Returns false (and "result") if should NOT issue syscall. */ bool handle_old_sigaction(dcontext_t *dcontext, int sig, const old_sigaction_t *act, old_sigaction_t *oact, OUT uint *result) { kernel_sigaction_t kact; kernel_sigaction_t okact; bool res; if (act != NULL) { if (!convert_old_sigaction_to_kernel(dcontext, &kact, act)) { *result = EFAULT; return false; } } res = handle_sigaction(dcontext, sig, act == NULL ? NULL : &kact, oact == NULL ? NULL : &okact, sizeof(kernel_sigset_t), result); if (!res) *result = handle_post_old_sigaction(dcontext, true, sig, act, oact); return res; } /* Returns the desired app return value (caller will negate if nec). */ uint handle_post_old_sigaction(dcontext_t *dcontext, bool success, int sig, const old_sigaction_t *act, old_sigaction_t *oact) { kernel_sigaction_t kact; kernel_sigaction_t okact; ptr_uint_t res; if (act != NULL && success) { if (!convert_old_sigaction_to_kernel(dcontext, &kact, act)) { ASSERT(!success); return EFAULT; } } if (oact != NULL && success) { if (!convert_old_sigaction_to_kernel(dcontext, &okact, oact)) { ASSERT(!success); return EFAULT; } } res = handle_post_sigaction(dcontext, success, sig, act == NULL ? NULL : &kact, oact == NULL ? NULL : &okact, sizeof(kernel_sigset_t)); if (res == 0 && oact != NULL) { if (!convert_kernel_sigaction_to_old(dcontext, oact, &okact)) { return EFAULT; } } return res; } #endif /* LINUX */ /* Returns false and sets *result if should NOT issue syscall. * If *result is non-zero, the syscall should fail. */ bool handle_sigaltstack(dcontext_t *dcontext, const stack_t *stack, stack_t *old_stack, reg_t cur_xsp, OUT uint *result) { thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field; stack_t local_stack; if (old_stack != NULL) { if (!safe_write_ex(old_stack, sizeof(*old_stack), &info->app_sigstack, NULL)) { *result = EFAULT; return false; } } if (stack != NULL) { /* Fail in the same way the kernel does. */ if (!d_r_safe_read(stack, sizeof(local_stack), &local_stack)) { *result = EFAULT; return false; } if (APP_HAS_SIGSTACK(info)) { /* The app is not allowed to set a new altstack while on the current one. */ reg_t cur_sigstk = (reg_t)info->app_sigstack.ss_sp; if (cur_xsp >= cur_sigstk && cur_xsp < cur_sigstk + info->app_sigstack.ss_size) { *result = EPERM; return false; } } uint key_flag = local_stack.ss_flags & ~SS_FLAG_BITS; if (key_flag != SS_DISABLE && key_flag != SS_ONSTACK && key_flag != 0) { *result = EINVAL; return false; } if (key_flag == SS_DISABLE) { /* Zero the other params and don't even check them. */ local_stack.ss_sp = NULL; local_stack.ss_size = 0; } else { if (local_stack.ss_size < MINSIGSTKSZ) { *result = ENOMEM; return false; } } info->app_sigstack = local_stack; LOG(THREAD, LOG_ASYNCH, 2, "Setting app signal stack to " PFX "-" PFX " %d=%s\n", local_stack.ss_sp, local_stack.ss_sp + local_stack.ss_size - 1, local_stack.ss_flags, (APP_HAS_SIGSTACK(info)) ? "enabled" : "disabled"); } *result = 0; return false; /* always cancel syscall */ } /* Blocked signals: * In general, we don't need to keep track of blocked signals. * We only need to do so for those signals we intercept ourselves. * Thus, info->app_sigblocked ONLY contains entries for signals * we intercept ourselves. * PR 304708: we now intercept all signals. */ static void set_blocked(dcontext_t *dcontext, kernel_sigset_t *set, bool absolute) { thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field; int i; if (absolute) { /* discard current blocked signals, re-set from new mask */ kernel_sigemptyset(&info->app_sigblocked); } /* else, OR in the new set */ for (i = 1; i <= MAX_SIGNUM; i++) { if (EMULATE_SIGMASK(info, i) && kernel_sigismember(set, i)) { kernel_sigaddset(&info->app_sigblocked, i); } } #ifdef DEBUG if (d_r_stats->loglevel >= 3 && (d_r_stats->logmask & LOG_ASYNCH) != 0) { LOG(THREAD, LOG_ASYNCH, 3, "blocked signals are now:\n"); dump_sigset(dcontext, &info->app_sigblocked); } #endif } void signal_set_mask(dcontext_t *dcontext, kernel_sigset_t *sigset) { set_blocked(dcontext, sigset, true /*absolute*/); } void signal_swap_mask(dcontext_t *dcontext, bool to_app) { thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field; if (to_app) { if (init_info.app_sigaction != NULL) { /* This is the first execution of the app. * We need to remove our own init-time handler and mask. */ unset_initial_crash_handlers(dcontext); return; } sigprocmask_syscall(SIG_SETMASK, &info->app_sigblocked, NULL, sizeof(info->app_sigblocked)); } else { unblock_all_signals(&info->app_sigblocked); DOLOG(2, LOG_ASYNCH, { LOG(THREAD, LOG_ASYNCH, 2, "thread %d's initial app signal mask:\n", d_r_get_thread_id()); dump_sigset(dcontext, &info->app_sigblocked); }); } } /* Scans over info->sigpending to see if there are any unblocked, pending * signals, and sets dcontext->signals_pending if there are. Do this after * modifying the set of signals blocked by the application. */ void check_signals_pending(dcontext_t *dcontext, thread_sig_info_t *info) { int i; if (dcontext->signals_pending != 0) return; for (i = 1; i <= MAX_SIGNUM; i++) { if (info->sigpending[i] != NULL && !kernel_sigismember(&info->app_sigblocked, i) && !dcontext->signals_pending) { /* We only update the application's set of blocked signals from * syscall handlers, so we know we'll go back to d_r_dispatch and see * this flag right away. */ LOG(THREAD, LOG_ASYNCH, 3, "\tsetting signals_pending flag\n"); dcontext->signals_pending = 1; break; } } } /* Returns whether to execute the syscall */ bool handle_sigprocmask(dcontext_t *dcontext, int how, kernel_sigset_t *app_set, kernel_sigset_t *oset, size_t sigsetsize) { thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field; int i; kernel_sigset_t safe_set; /* If we're intercepting all, we emulate the whole thing */ bool execute_syscall = !DYNAMO_OPTION(intercept_all_signals); LOG(THREAD, LOG_ASYNCH, 2, "handle_sigprocmask\n"); if (oset != NULL) info->pre_syscall_app_sigblocked = info->app_sigblocked; if (app_set != NULL && d_r_safe_read(app_set, sizeof(safe_set), &safe_set)) { if (execute_syscall) { /* The syscall will execute, so remove from the set passed * to it. We restore post-syscall. * XXX i#1187: we could crash here touching app memory -- could * use TRY, but the app could pass read-only memory and it * would work natively! Better to swap in our own * allocated data struct. There's a transparency issue w/ * races too if another thread looks at this memory. This * won't happen by default b/c -intercept_all_signals is * on by default so we don't try to solve all these * issues. */ info->pre_syscall_app_sigprocmask = safe_set; } if (how == SIG_BLOCK) { /* The set of blocked signals is the union of the current * set and the set argument. */ for (i = 1; i <= MAX_SIGNUM; i++) { if (EMULATE_SIGMASK(info, i) && kernel_sigismember(&safe_set, i)) { kernel_sigaddset(&info->app_sigblocked, i); if (execute_syscall) kernel_sigdelset(app_set, i); } } } else if (how == SIG_UNBLOCK) { /* The signals in set are removed from the current set of * blocked signals. */ for (i = 1; i <= MAX_SIGNUM; i++) { if (EMULATE_SIGMASK(info, i) && kernel_sigismember(&safe_set, i)) { kernel_sigdelset(&info->app_sigblocked, i); if (execute_syscall) kernel_sigdelset(app_set, i); } } } else if (how == SIG_SETMASK) { /* The set of blocked signals is set to the argument set. */ kernel_sigemptyset(&info->app_sigblocked); for (i = 1; i <= MAX_SIGNUM; i++) { if (EMULATE_SIGMASK(info, i) && kernel_sigismember(&safe_set, i)) { kernel_sigaddset(&info->app_sigblocked, i); if (execute_syscall) kernel_sigdelset(app_set, i); } } } #ifdef DEBUG if (d_r_stats->loglevel >= 3 && (d_r_stats->logmask & LOG_ASYNCH) != 0) { LOG(THREAD, LOG_ASYNCH, 3, "blocked signals are now:\n"); dump_sigset(dcontext, &info->app_sigblocked); } #endif /* make sure we deliver pending signals that are now unblocked * FIXME: consider signal #S, which we intercept ourselves. * If S arrives, then app blocks it prior to our delivering it, * we then won't deliver it until app unblocks it...is this a * problem? Could have arrived a little later and then we would * do same thing, but this way kernel may send one more than would * get w/o dynamo? This goes away if we deliver signals * prior to letting app do a syscall. */ check_signals_pending(dcontext, info); } if (!execute_syscall) { handle_post_sigprocmask(dcontext, how, app_set, oset, sigsetsize); return false; /* skip syscall */ } else return true; } /* need to add in our signals that the app thinks are blocked */ void handle_post_sigprocmask(dcontext_t *dcontext, int how, kernel_sigset_t *app_set, kernel_sigset_t *oset, size_t sigsetsize) { thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field; int i; if (!DYNAMO_OPTION(intercept_all_signals)) { /* Restore app memory */ safe_write_ex(app_set, sizeof(*app_set), &info->pre_syscall_app_sigprocmask, NULL); } if (oset != NULL) { if (DYNAMO_OPTION(intercept_all_signals)) safe_write_ex(oset, sizeof(*oset), &info->pre_syscall_app_sigblocked, NULL); else { /* the syscall wrote to oset already, so just add any additional */ for (i = 1; i <= MAX_SIGNUM; i++) { if (EMULATE_SIGMASK(info, i) && /* use the pre-syscall value: do not take into account changes * from this syscall itself! (PR 523394) */ kernel_sigismember(&info->pre_syscall_app_sigblocked, i)) { kernel_sigaddset(oset, i); } } } } } void handle_sigsuspend(dcontext_t *dcontext, kernel_sigset_t *set, size_t sigsetsize) { thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field; int i; ASSERT(set != NULL); LOG(THREAD, LOG_ASYNCH, 2, "handle_sigsuspend\n"); info->in_sigsuspend = true; info->app_sigblocked_save = info->app_sigblocked; kernel_sigemptyset(&info->app_sigblocked); for (i = 1; i <= MAX_SIGNUM; i++) { if (EMULATE_SIGMASK(info, i) && kernel_sigismember(set, i)) { kernel_sigaddset(&info->app_sigblocked, i); kernel_sigdelset(set, i); } } #ifdef DEBUG if (d_r_stats->loglevel >= 3 && (d_r_stats->logmask & LOG_ASYNCH) != 0) { LOG(THREAD, LOG_ASYNCH, 3, "in sigsuspend, blocked signals are now:\n"); dump_sigset(dcontext, &info->app_sigblocked); } #endif } /**** utility routines ***********************************************/ #ifdef DEBUG static void dump_sigset(dcontext_t *dcontext, kernel_sigset_t *set) { int sig; for (sig = 1; sig <= MAX_SIGNUM; sig++) { if (kernel_sigismember(set, sig)) LOG(THREAD, LOG_ASYNCH, 1, "\t%d = blocked\n", sig); } } #endif /* DEBUG */ /* PR 205795: to avoid lock problems w/ in_fcache (it grabs a lock, we * could have interrupted someone holding that), we first check * whereami --- if whereami is DR_WHERE_FCACHE we still check the pc * to distinguish generated routines, but at least we're certain * it's not in DR where it could own a lock. * We can't use is_on_dstack() here b/c we need to handle clean call * arg crashes -- which is too bad since checking client dll and DR dll is * not sufficient due to calls to ntdll, libc, or pc being in gencode. */ static bool safe_is_in_fcache(dcontext_t *dcontext, app_pc pc, app_pc xsp) { if (dcontext->whereami != DR_WHERE_FCACHE || IF_CLIENT_INTERFACE(is_in_client_lib(pc) ||) is_in_dynamo_dll(pc) || is_on_initstack(xsp)) return false; /* Reasonably certain not in DR code, so no locks should be held */ return in_fcache(pc); } static bool safe_is_in_coarse_stubs(dcontext_t *dcontext, app_pc pc, app_pc xsp) { if (dcontext->whereami != DR_WHERE_FCACHE || IF_CLIENT_INTERFACE(is_in_client_lib(pc) ||) is_in_dynamo_dll(pc) || is_on_initstack(xsp)) return false; /* Reasonably certain not in DR code, so no locks should be held */ return in_coarse_stubs(pc); } static bool is_on_alt_stack(dcontext_t *dcontext, byte *sp) { #ifdef HAVE_SIGALTSTACK thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field; return (sp >= (byte *)info->sigstack.ss_sp && /* deliberate equality check since stacks often init to top */ sp <= (byte *)(info->sigstack.ss_sp + info->sigstack.ss_size)); #else return false; #endif } /* The caller must initialize ucxt, including its fpstate pointer for x86 Linux. */ static void sig_full_initialize(sig_full_cxt_t *sc_full, kernel_ucontext_t *ucxt) { sc_full->sc = SIGCXT_FROM_UCXT(ucxt); #ifdef X86 sc_full->fp_simd_state = NULL; /* we have a ptr inside sigcontext_t */ #elif defined(ARM) sc_full->fp_simd_state = &ucxt->coproc.uc_vfp; #elif defined(AARCH64) sc_full->fp_simd_state = &ucxt->uc_mcontext.__reserved; #else ASSERT_NOT_IMPLEMENTED(false); #endif } void sigcontext_to_mcontext(priv_mcontext_t *mc, sig_full_cxt_t *sc_full, dr_mcontext_flags_t flags) { sigcontext_t *sc = sc_full->sc; ASSERT(mc != NULL && sc != NULL); #ifdef X86 if (TEST(DR_MC_INTEGER, flags)) { mc->xax = sc->SC_XAX; mc->xbx = sc->SC_XBX; mc->xcx = sc->SC_XCX; mc->xdx = sc->SC_XDX; mc->xsi = sc->SC_XSI; mc->xdi = sc->SC_XDI; mc->xbp = sc->SC_XBP; # ifdef X64 mc->r8 = sc->SC_FIELD(r8); mc->r9 = sc->SC_FIELD(r9); mc->r10 = sc->SC_FIELD(r10); mc->r11 = sc->SC_FIELD(r11); mc->r12 = sc->SC_FIELD(r12); mc->r13 = sc->SC_FIELD(r13); mc->r14 = sc->SC_FIELD(r14); mc->r15 = sc->SC_FIELD(r15); # endif /* X64 */ } if (TEST(DR_MC_CONTROL, flags)) { mc->xsp = sc->SC_XSP; mc->xflags = sc->SC_XFLAGS; mc->pc = (app_pc)sc->SC_XIP; } #elif defined(AARCH64) if (TEST(DR_MC_INTEGER, flags)) memcpy(&mc->r0, &sc->SC_FIELD(regs[0]), sizeof(mc->r0) * 31); if (TEST(DR_MC_CONTROL, flags)) { /* XXX i#2710: the link register should be under DR_MC_CONTROL */ mc->sp = sc->SC_FIELD(sp); mc->pc = (void *)sc->SC_FIELD(pc); mc->nzcv = sc->SC_FIELD(pstate); } #elif defined(ARM) if (TEST(DR_MC_INTEGER, flags)) { mc->r0 = sc->SC_FIELD(arm_r0); mc->r1 = sc->SC_FIELD(arm_r1); mc->r2 = sc->SC_FIELD(arm_r2); mc->r3 = sc->SC_FIELD(arm_r3); mc->r4 = sc->SC_FIELD(arm_r4); mc->r5 = sc->SC_FIELD(arm_r5); mc->r6 = sc->SC_FIELD(arm_r6); mc->r7 = sc->SC_FIELD(arm_r7); mc->r8 = sc->SC_FIELD(arm_r8); mc->r9 = sc->SC_FIELD(arm_r9); mc->r10 = sc->SC_FIELD(arm_r10); mc->r11 = sc->SC_FIELD(arm_fp); mc->r12 = sc->SC_FIELD(arm_ip); /* XXX i#2710: the link register should be under DR_MC_CONTROL */ mc->r14 = sc->SC_FIELD(arm_lr); } if (TEST(DR_MC_CONTROL, flags)) { mc->r13 = sc->SC_FIELD(arm_sp); mc->r15 = sc->SC_FIELD(arm_pc); mc->cpsr = sc->SC_FIELD(arm_cpsr); } # ifdef X64 # error NYI on AArch64 # endif /* X64 */ #endif /* X86/ARM */ if (TEST(DR_MC_MULTIMEDIA, flags)) sigcontext_to_mcontext_simd(mc, sc_full); } /* Note that unlike mcontext_to_context(), this routine does not fill in * any state that is not present in the mcontext: in particular, it assumes * the sigcontext already contains the native fpstate. If the caller * is generating a synthetic sigcontext, the caller should call * save_fpstate() before calling this routine. */ /* XXX: on ARM, sigreturn needs the T bit set in the sigcontext_t cpsr field in * order to return to Thumb mode. But, our mcontext doesn't have the T bit (b/c * usermode can't read it). Thus callers must either modify an mcontext * obtained from sigcontext_to_mcontext() or must call set_pc_mode_in_cpsr() in * order to create a proper sigcontext for sigreturn. All callers here do so. * The only external non-Windows caller of thread_set_mcontext() is * translate_from_synchall_to_dispatch() who first does a thread_get_mcontext() * and tweaks that context, so cpsr should be there. */ void mcontext_to_sigcontext(sig_full_cxt_t *sc_full, priv_mcontext_t *mc, dr_mcontext_flags_t flags) { sigcontext_t *sc = sc_full->sc; ASSERT(mc != NULL && sc != NULL); #ifdef X86 if (TEST(DR_MC_INTEGER, flags)) { sc->SC_XAX = mc->xax; sc->SC_XBX = mc->xbx; sc->SC_XCX = mc->xcx; sc->SC_XDX = mc->xdx; sc->SC_XSI = mc->xsi; sc->SC_XDI = mc->xdi; sc->SC_XBP = mc->xbp; # ifdef X64 sc->SC_FIELD(r8) = mc->r8; sc->SC_FIELD(r9) = mc->r9; sc->SC_FIELD(r10) = mc->r10; sc->SC_FIELD(r11) = mc->r11; sc->SC_FIELD(r12) = mc->r12; sc->SC_FIELD(r13) = mc->r13; sc->SC_FIELD(r14) = mc->r14; sc->SC_FIELD(r15) = mc->r15; # endif /* X64 */ } if (TEST(DR_MC_CONTROL, flags)) { sc->SC_XSP = mc->xsp; sc->SC_XFLAGS = mc->xflags; sc->SC_XIP = (ptr_uint_t)mc->pc; } #elif defined(AARCH64) if (TEST(DR_MC_INTEGER, flags)) { memcpy(&sc->SC_FIELD(regs[0]), &mc->r0, sizeof(mc->r0) * 31); } if (TEST(DR_MC_CONTROL, flags)) { /* XXX i#2710: the link register should be under DR_MC_CONTROL */ sc->SC_FIELD(sp) = mc->sp; sc->SC_FIELD(pc) = (ptr_uint_t)mc->pc; sc->SC_FIELD(pstate) = mc->nzcv; } #elif defined(ARM) if (TEST(DR_MC_INTEGER, flags)) { sc->SC_FIELD(arm_r0) = mc->r0; sc->SC_FIELD(arm_r1) = mc->r1; sc->SC_FIELD(arm_r2) = mc->r2; sc->SC_FIELD(arm_r3) = mc->r3; sc->SC_FIELD(arm_r4) = mc->r4; sc->SC_FIELD(arm_r5) = mc->r5; sc->SC_FIELD(arm_r6) = mc->r6; sc->SC_FIELD(arm_r7) = mc->r7; sc->SC_FIELD(arm_r8) = mc->r8; sc->SC_FIELD(arm_r9) = mc->r9; sc->SC_FIELD(arm_r10) = mc->r10; sc->SC_FIELD(arm_fp) = mc->r11; sc->SC_FIELD(arm_ip) = mc->r12; /* XXX i#2710: the link register should be under DR_MC_CONTROL */ sc->SC_FIELD(arm_lr) = mc->r14; } if (TEST(DR_MC_CONTROL, flags)) { sc->SC_FIELD(arm_sp) = mc->r13; sc->SC_FIELD(arm_pc) = mc->r15; sc->SC_FIELD(arm_cpsr) = mc->cpsr; } # ifdef X64 # error NYI on AArch64 # endif /* X64 */ #endif /* X86/ARM */ if (TEST(DR_MC_MULTIMEDIA, flags)) mcontext_to_sigcontext_simd(sc_full, mc); } static void ucontext_to_mcontext(priv_mcontext_t *mc, kernel_ucontext_t *uc) { sig_full_cxt_t sc_full; sig_full_initialize(&sc_full, uc); sigcontext_to_mcontext(mc, &sc_full, DR_MC_ALL); } static void mcontext_to_ucontext(kernel_ucontext_t *uc, priv_mcontext_t *mc) { sig_full_cxt_t sc_full; sig_full_initialize(&sc_full, uc); mcontext_to_sigcontext(&sc_full, mc, DR_MC_ALL); } #ifdef AARCHXX static void set_sigcxt_stolen_reg(sigcontext_t *sc, reg_t val) { *(&sc->SC_R0 + (dr_reg_stolen - DR_REG_R0)) = val; } static reg_t get_sigcxt_stolen_reg(sigcontext_t *sc) { return *(&sc->SC_R0 + (dr_reg_stolen - DR_REG_R0)); } # ifndef AARCH64 static dr_isa_mode_t get_pc_mode_from_cpsr(sigcontext_t *sc) { return TEST(EFLAGS_T, sc->SC_XFLAGS) ? DR_ISA_ARM_THUMB : DR_ISA_ARM_A32; } static void set_pc_mode_in_cpsr(sigcontext_t *sc, dr_isa_mode_t isa_mode) { if (isa_mode == DR_ISA_ARM_THUMB) sc->SC_XFLAGS |= EFLAGS_T; else sc->SC_XFLAGS &= ~EFLAGS_T; } # endif #endif /* Returns whether successful. If avoid_failure, tries to translate * at least pc if not successful. Pass f if known. */ static bool translate_sigcontext(dcontext_t *dcontext, kernel_ucontext_t *uc, bool avoid_failure, fragment_t *f) { bool success = false; priv_mcontext_t mcontext; sigcontext_t *sc = SIGCXT_FROM_UCXT(uc); ucontext_to_mcontext(&mcontext, uc); /* FIXME: if cannot find exact match, we're in trouble! * probably ok to delay, since that indicates not a synchronous * signal. */ /* FIXME : in_fcache() (called by recreate_app_state) grabs fcache * fcache_unit_areas.lock, we could deadlock! Also on initexit_lock * == PR 205795/1317 */ /* For safe recreation we need to either be couldbelinking or hold the * initexit lock (to keep someone from flushing current fragment), the * initexit lock is easier */ d_r_mutex_lock(&thread_initexit_lock); /* PR 214962: we assume we're going to relocate to this stored context, * so we restore memory now */ if (translate_mcontext(dcontext->thread_record, &mcontext, true /*restore memory*/, f)) { mcontext_to_ucontext(uc, &mcontext); success = true; } else { if (avoid_failure) { ASSERT_NOT_REACHED(); /* is ok to break things, is UNIX :) */ /* FIXME : what to do? reg state might be wrong at least get pc */ if (safe_is_in_fcache(dcontext, (cache_pc)sc->SC_XIP, (app_pc)sc->SC_XSP)) { sc->SC_XIP = (ptr_uint_t)recreate_app_pc(dcontext, mcontext.pc, f); ASSERT(sc->SC_XIP != (ptr_uint_t)NULL); } else { /* FIXME : can't even get pc right, what do we do here? */ sc->SC_XIP = 0; } } } d_r_mutex_unlock(&thread_initexit_lock); /* FIXME i#2095: restore the app's segment register value(s). */ LOG(THREAD, LOG_ASYNCH, 3, "\ttranslate_sigcontext: just set frame's eip to " PFX "\n", sc->SC_XIP); return success; } /* Takes an os-specific context */ void thread_set_self_context(void *cxt) { #ifdef X86 if (!INTERNAL_OPTION(use_sigreturn_setcontext)) { sigcontext_t *sc = (sigcontext_t *)cxt; dr_jmp_buf_t buf; buf.xbx = sc->SC_XBX; buf.xcx = sc->SC_XCX; buf.xdi = sc->SC_XDI; buf.xsi = sc->SC_XSI; buf.xbp = sc->SC_XBP; /* XXX: this is not fully transparent: it assumes the target stack * is valid and that we can clobber the slot beyond TOS. * Using this instead of sigreturn is meant mainly as a diagnostic * to help debug future issues with sigreturn (xref i#2080). */ buf.xsp = sc->SC_XSP - XSP_SZ; /* extra slot for retaddr */ buf.xip = sc->SC_XIP; # ifdef X64 buf.r8 = sc->SC_R8; buf.r9 = sc->SC_R9; buf.r10 = sc->SC_R10; buf.r11 = sc->SC_R11; buf.r12 = sc->SC_R12; buf.r13 = sc->SC_R13; buf.r14 = sc->SC_R14; buf.r15 = sc->SC_R15; # endif dr_longjmp(&buf, sc->SC_XAX); return; } #endif dcontext_t *dcontext = get_thread_private_dcontext(); /* Unlike Windows we can't say "only set this subset of the * full machine state", so we need to get the rest of the state, */ sigframe_rt_t frame; #if defined(LINUX) || defined(DEBUG) sigcontext_t *sc = (sigcontext_t *)cxt; #endif app_pc xsp_for_sigreturn; #ifdef VMX86_SERVER ASSERT_NOT_IMPLEMENTED(false); /* PR 405694: can't use regular sigreturn! */ #endif memset(&frame, 0, sizeof(frame)); #ifdef LINUX # ifdef X86 byte *xstate = get_xstate_buffer(dcontext); frame.uc.uc_mcontext.fpstate = &((kernel_xstate_t *)xstate)->fpstate; # endif /* X86 */ frame.uc.uc_mcontext = *sc; #endif save_fpstate(dcontext, &frame); /* The kernel calls do_sigaltstack on sys_rt_sigreturn primarily to ensure * the frame is ok, but the side effect is we can mess up our own altstack * settings if we're not careful. Having invalid ss_size looks good for * kernel 2.6.23.9 at least so we leave frame.uc.uc_stack as all zeros. */ /* make sure sigreturn's mask setting doesn't change anything */ sigprocmask_syscall(SIG_SETMASK, NULL, (kernel_sigset_t *)&frame.uc.uc_sigmask, sizeof(frame.uc.uc_sigmask)); LOG(THREAD_GET, LOG_ASYNCH, 2, "thread_set_self_context: pc=" PFX "\n", sc->SC_XIP); LOG(THREAD_GET, LOG_ASYNCH, 3, "full sigcontext\n"); DOLOG(LOG_ASYNCH, 3, { dump_sigcontext(dcontext, get_sigcontext_from_rt_frame(&frame)); }); /* set up xsp to point at &frame + sizeof(char*) */ xsp_for_sigreturn = ((app_pc)&frame) + sizeof(char *); #ifdef X86 asm("mov %0, %%" ASM_XSP : : "m"(xsp_for_sigreturn)); # ifdef MACOS ASSERT_NOT_IMPLEMENTED(false && "need to pass 2 params to SYS_sigreturn"); asm("jmp _dynamorio_sigreturn"); # else /* i#2632: recent clang for 32-bit annoyingly won't do the right thing for * "jmp dynamorio_sigreturn" and leaves relocs so we ensure it's PIC: */ void (*asm_jmp_tgt)() = dynamorio_sigreturn; asm("mov %0, %%" ASM_XCX : : "m"(asm_jmp_tgt)); asm("jmp *%" ASM_XCX); # endif /* MACOS/LINUX */ #elif defined(AARCH64) ASSERT_NOT_IMPLEMENTED(false); /* FIXME i#1569 */ #elif defined(ARM) asm("ldr " ASM_XSP ", %0" : : "m"(xsp_for_sigreturn)); asm("b dynamorio_sigreturn"); #endif /* X86/ARM */ ASSERT_NOT_REACHED(); } static void thread_set_segment_registers(sigcontext_t *sc) { #ifdef X86 /* Fill in the segment registers */ __asm__ __volatile__("mov %%cs, %%ax; mov %%ax, %0" : "=m"(sc->SC_FIELD(cs)) : : "eax"); # ifndef X64 __asm__ __volatile__("mov %%ss, %%ax; mov %%ax, %0" : "=m"(sc->SC_FIELD(ss)) : : "eax"); __asm__ __volatile__("mov %%ds, %%ax; mov %%ax, %0" : "=m"(sc->SC_FIELD(ds)) : : "eax"); __asm__ __volatile__("mov %%es, %%ax; mov %%ax, %0" : "=m"(sc->SC_FIELD(es)) : : "eax"); # endif __asm__ __volatile__("mov %%fs, %%ax; mov %%ax, %0" : "=m"(sc->SC_FIELD(fs)) : : "eax"); __asm__ __volatile__("mov %%gs, %%ax; mov %%ax, %0" : "=m"(sc->SC_FIELD(gs)) : : "eax"); #endif } /* Takes a priv_mcontext_t */ void thread_set_self_mcontext(priv_mcontext_t *mc) { kernel_ucontext_t ucxt; sig_full_cxt_t sc_full; sig_full_initialize(&sc_full, &ucxt); #if defined(LINUX) && defined(X86) sc_full.sc->fpstate = NULL; /* for mcontext_to_sigcontext */ #endif mcontext_to_sigcontext(&sc_full, mc, DR_MC_ALL); thread_set_segment_registers(sc_full.sc); /* sigreturn takes the mode from cpsr */ IF_ARM( set_pc_mode_in_cpsr(sc_full.sc, dr_get_isa_mode(get_thread_private_dcontext()))); /* thread_set_self_context will fill in the real fp/simd state for x86 */ thread_set_self_context((void *)sc_full.sc); ASSERT_NOT_REACHED(); } #ifdef LINUX static bool sig_has_restorer(thread_sig_info_t *info, int sig) { # ifdef VMX86_SERVER /* vmkernel ignores SA_RESTORER (PR 405694) */ return false; # endif if (info->app_sigaction[sig] == NULL) return false; if (TEST(SA_RESTORER, info->app_sigaction[sig]->flags)) return true; if (info->app_sigaction[sig]->restorer == NULL) return false; /* we cache the result due to the safe_read cost */ if (info->restorer_valid[sig] == -1) { /* With older kernels, don't seem to need flag: if sa_restorer != * NULL kernel will use it. But with newer kernels that's not * true, and sometimes libc does pass non-NULL. */ # ifdef X86 /* Signal restorer code for Ubuntu 7.04: * 0xffffe420 <__kernel_sigreturn+0>: pop %eax * 0xffffe421 <__kernel_sigreturn+1>: mov $0x77,%eax * 0xffffe426 <__kernel_sigreturn+6>: int $0x80 * * 0xffffe440 <__kernel_rt_sigreturn+0>: mov $0xad,%eax * 0xffffe445 <__kernel_rt_sigreturn+5>: int $0x80 */ static const byte SIGRET_NONRT[8] = { 0x58, 0xb8, 0x77, 0x00, 0x00, 0x00, 0xcd, 0x80 }; static const byte SIGRET_RT[8] = { 0xb8, 0xad, 0x00, 0x00, 0x00, 0xcd, 0x80 }; # elif defined(ARM) static const byte SIGRET_NONRT[8] = { 0x77, 0x70, 0xa0, 0xe3, 0x00, 0x00, 0x00, 0xef }; static const byte SIGRET_RT[8] = { 0xad, 0x70, 0xa0, 0xe3, 0x00, 0x00, 0x00, 0xef }; # elif defined(AARCH64) static const byte SIGRET_NONRT[8] = { 0 }; /* unused */ static const byte SIGRET_RT[8] = /* FIXME i#1569: untested */ /* mov w8, #139 ; svc #0 */ { 0x68, 0x11, 0x80, 0x52, 0x01, 0x00, 0x00, 0xd4 }; # endif byte buf[MAX(sizeof(SIGRET_NONRT), sizeof(SIGRET_RT))] = { 0 }; if (d_r_safe_read(info->app_sigaction[sig]->restorer, sizeof(buf), buf) && ((IS_RT_FOR_APP(info, sig) && memcmp(buf, SIGRET_RT, sizeof(SIGRET_RT)) == 0) || (!IS_RT_FOR_APP(info, sig) && memcmp(buf, SIGRET_NONRT, sizeof(SIGRET_NONRT)) == 0))) { LOG(THREAD_GET, LOG_ASYNCH, 2, "sig_has_restorer %d: " PFX " looks like restorer, using w/o flag\n", sig, info->app_sigaction[sig]->restorer); info->restorer_valid[sig] = 1; } else info->restorer_valid[sig] = 0; } return (info->restorer_valid[sig] == 1); } #endif /* Returns the size of the frame for delivering to the app. * For x64 this does NOT include kernel_fpstate_t. */ static uint get_app_frame_size(thread_sig_info_t *info, int sig) { if (IS_RT_FOR_APP(info, sig)) return sizeof(sigframe_rt_t); #ifdef LINUX else return sizeof(sigframe_plain_t); #endif } static kernel_ucontext_t * get_ucontext_from_rt_frame(sigframe_rt_t *frame) { #if defined(MACOS) && !defined(X64) /* Padding makes it unsafe to access uc on frame from kernel */ return frame->puc; #else return &frame->uc; #endif } sigcontext_t * get_sigcontext_from_rt_frame(sigframe_rt_t *frame) { return SIGCXT_FROM_UCXT(get_ucontext_from_rt_frame(frame)); } static sigcontext_t * get_sigcontext_from_app_frame(thread_sig_info_t *info, int sig, void *frame) { sigcontext_t *sc = NULL; /* initialize to satisfy Mac clang */ bool rtframe = IS_RT_FOR_APP(info, sig); if (rtframe) sc = get_sigcontext_from_rt_frame((sigframe_rt_t *)frame); #ifdef LINUX else { # ifdef X86 sc = (sigcontext_t *)&(((sigframe_plain_t *)frame)->sc); # elif defined(ARM) sc = SIGCXT_FROM_UCXT(&(((sigframe_plain_t *)frame)->uc)); # else ASSERT_NOT_REACHED(); # endif } #endif return sc; } static sigcontext_t * get_sigcontext_from_pending(thread_sig_info_t *info, int sig) { ASSERT(info->sigpending[sig] != NULL); return get_sigcontext_from_rt_frame(&info->sigpending[sig]->rt_frame); } /* Returns the address on the appropriate signal stack where we should copy * the frame. * If frame is NULL, assumes signal happened while in DR and has been delayed, * and thus we need to provide fpstate regardless of whether the original * had it. If frame is non-NULL, matches frame's amount of fpstate. */ static byte * get_sigstack_frame_ptr(dcontext_t *dcontext, int sig, sigframe_rt_t *frame) { thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field; sigcontext_t *sc = (frame == NULL) ? get_sigcontext_from_pending(info, sig) : get_sigcontext_from_rt_frame(frame); byte *sp; if (frame != NULL) { /* signal happened while in cache, grab interrupted xsp */ sp = (byte *)sc->SC_XSP; LOG(THREAD, LOG_ASYNCH, 3, "get_sigstack_frame_ptr: using frame's xsp " PFX "\n", sp); } else { /* signal happened while in DR, use stored xsp */ sp = (byte *)get_mcontext(dcontext)->xsp; LOG(THREAD, LOG_ASYNCH, 3, "get_sigstack_frame_ptr: using app xsp " PFX "\n", sp); } if (USE_APP_SIGSTACK(info, sig)) { /* app has own signal stack which is enabled for this handler */ LOG(THREAD, LOG_ASYNCH, 3, "get_sigstack_frame_ptr: app has own stack " PFX "\n", info->app_sigstack.ss_sp); LOG(THREAD, LOG_ASYNCH, 3, "\tcur sp=" PFX " vs app stack " PFX "-" PFX "\n", sp, info->app_sigstack.ss_sp, info->app_sigstack.ss_sp + info->app_sigstack.ss_size); if (sp > (byte *)info->app_sigstack.ss_sp && sp - (byte *)info->app_sigstack.ss_sp < info->app_sigstack.ss_size) { /* we're currently in the alt stack, so use current xsp */ LOG(THREAD, LOG_ASYNCH, 3, "\tinside alt stack, so using current xsp " PFX "\n", sp); } else { /* need to go to top, stack grows down */ sp = info->app_sigstack.ss_sp + info->app_sigstack.ss_size; LOG(THREAD, LOG_ASYNCH, 3, "\tnot inside alt stack, so using base xsp " PFX "\n", sp); } } /* now get frame pointer: need to go down to first field of frame */ sp -= get_app_frame_size(info, sig); #if defined(LINUX) && defined(X86) if (frame == NULL) { /* XXX i#641: we always include space for full xstate, * even if we don't use it all, which does not match what the * kernel does, but we're not tracking app actions to know whether * we can skip lazy fpstate on the delay */ sp -= signal_frame_extra_size(true); } else { if (sc->fpstate != NULL) { /* The kernel doesn't seem to lazily include avx, so we don't either, * which simplifies all our frame copying: if YMM_ENABLED() and the * fpstate pointer is non-NULL, then we assume there's space for * full xstate */ sp -= signal_frame_extra_size(true); DOCHECK(1, { if (YMM_ENABLED()) { ASSERT_CURIOSITY(sc->fpstate->sw_reserved.magic1 == FP_XSTATE_MAGIC1); ASSERT(sc->fpstate->sw_reserved.extended_size <= signal_frame_extra_size(true)); } }); } } #endif /* LINUX && X86 */ /* PR 369907: don't forget the redzone */ sp -= REDZONE_SIZE; /* Align to 16-bytes. The kernel does this for both 32 and 64-bit code * these days, so we do as well. */ sp = (byte *)ALIGN_BACKWARD(sp, 16); IF_X86(sp -= sizeof(reg_t)); /* Model retaddr. */ LOG(THREAD, LOG_ASYNCH, 3, "\tplacing frame at " PFX "\n", sp); return sp; } #if defined(LINUX) && !defined(X64) static void convert_rt_mask_to_nonrt(sigframe_plain_t *f_plain, kernel_sigset_t *sigmask) { # ifdef X86 f_plain->sc.oldmask = sigmask->sig[0]; memcpy(&f_plain->extramask, &sigmask->sig[1], (_NSIG_WORDS - 1) * sizeof(uint)); # elif defined(ARM) f_plain->uc.uc_mcontext.oldmask = sigmask->sig[0]; memcpy(&f_plain->uc.sigset_ex, &sigmask->sig[1], (_NSIG_WORDS - 1) * sizeof(uint)); # else # error NYI # endif } static void convert_frame_to_nonrt(dcontext_t *dcontext, int sig, sigframe_rt_t *f_old, sigframe_plain_t *f_new) { # ifdef X86 sigcontext_t *sc_old = get_sigcontext_from_rt_frame(f_old); f_new->pretcode = f_old->pretcode; f_new->sig = f_old->sig; memcpy(&f_new->sc, get_sigcontext_from_rt_frame(f_old), sizeof(sigcontext_t)); if (sc_old->fpstate != NULL) { /* up to caller to include enough space for fpstate at end */ byte *new_fpstate = (byte *)ALIGN_FORWARD(((byte *)f_new) + sizeof(*f_new), XSTATE_ALIGNMENT); memcpy(new_fpstate, sc_old->fpstate, signal_frame_extra_size(false)); f_new->sc.fpstate = (kernel_fpstate_t *)new_fpstate; } convert_rt_mask_to_nonrt(f_new, &f_old->uc.uc_sigmask); memcpy(&f_new->retcode, &f_old->retcode, RETCODE_SIZE); /* now fill in our extra field */ f_new->sig_noclobber = f_new->sig; # elif defined(ARM) memcpy(&f_new->uc, &f_old->uc, sizeof(f_new->uc)); memcpy(f_new->retcode, f_old->retcode, sizeof(f_new->retcode)); /* now fill in our extra field */ f_new->sig_noclobber = f_old->info.si_signo; # endif /* X86 */ LOG(THREAD, LOG_ASYNCH, 3, "\tconverted sig=%d rt frame to non-rt frame\n", f_new->sig_noclobber); } #endif /* Exported for call from master_signal_handler asm routine. * For the rt signal frame f_old that was copied to f_new, updates * the intra-frame absolute pointers to point to the new addresses * in f_new. * Only updates the pretcode to the stored app restorer if for_app. */ void fixup_rtframe_pointers(dcontext_t *dcontext, int sig, sigframe_rt_t *f_old, sigframe_rt_t *f_new, bool for_app) { if (dcontext == NULL) dcontext = get_thread_private_dcontext(); ASSERT(dcontext != NULL); #if defined(X86) && defined(LINUX) thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field; bool has_restorer = sig_has_restorer(info, sig); # ifdef DEBUG uint level = 3; # if !defined(HAVE_MEMINFO) /* avoid logging every single TRY probe fault */ if (!dynamo_initialized) level = 5; # endif # endif if (has_restorer && for_app) f_new->pretcode = (char *)info->app_sigaction[sig]->restorer; else { # ifdef VMX86_SERVER /* PR 404712: skip kernel's restorer code */ if (for_app) f_new->pretcode = (char *)dynamorio_sigreturn; # else # ifdef X64 ASSERT(!for_app || doing_detach); /* detach uses a frame to go native */ # else /* only point at retcode if old one was -- with newer OS, points at * vsyscall page and there is no restorer, yet stack restorer code left * there for gdb compatibility */ if (f_old->pretcode == f_old->retcode) f_new->pretcode = f_new->retcode; /* else, pointing at vsyscall, or we set it to dynamorio_sigreturn in * master_signal_handler */ LOG(THREAD, LOG_ASYNCH, level, "\tleaving pretcode with old value\n"); # endif # endif } # ifndef X64 f_new->pinfo = &(f_new->info); f_new->puc = &(f_new->uc); # endif if (f_old->uc.uc_mcontext.fpstate != NULL) { uint frame_size = get_app_frame_size(info, sig); byte *frame_end = ((byte *)f_new) + frame_size; byte *tgt = (byte *)ALIGN_FORWARD(frame_end, XSTATE_ALIGNMENT); ASSERT(tgt - frame_end <= signal_frame_extra_size(true)); memcpy(tgt, f_old->uc.uc_mcontext.fpstate, sizeof(kernel_fpstate_t)); f_new->uc.uc_mcontext.fpstate = (kernel_fpstate_t *)tgt; if (YMM_ENABLED()) { kernel_xstate_t *xstate_new = (kernel_xstate_t *)tgt; kernel_xstate_t *xstate_old = (kernel_xstate_t *)f_old->uc.uc_mcontext.fpstate; memcpy(&xstate_new->xstate_hdr, &xstate_old->xstate_hdr, sizeof(xstate_new->xstate_hdr)); memcpy(&xstate_new->ymmh, &xstate_old->ymmh, sizeof(xstate_new->ymmh)); } LOG(THREAD, LOG_ASYNCH, level + 1, "\tfpstate old=" PFX " new=" PFX "\n", f_old->uc.uc_mcontext.fpstate, f_new->uc.uc_mcontext.fpstate); } else { /* if fpstate is not set up, we're delivering signal immediately, * and we shouldn't need an fpstate since DR code won't modify it; * only if we delayed will we need it, and when delaying we make * room and set up the pointer in copy_frame_to_pending. * xref i#641. */ LOG(THREAD, LOG_ASYNCH, level + 1, "\tno fpstate needed\n"); } LOG(THREAD, LOG_ASYNCH, level, "\tretaddr = " PFX "\n", f_new->pretcode); # ifdef RETURN_AFTER_CALL info->signal_restorer_retaddr = (app_pc)f_new->pretcode; # endif /* 32-bit kernel copies to aligned buf first */ IF_X64(ASSERT(ALIGNED(f_new->uc.uc_mcontext.fpstate, 16))); #elif defined(MACOS) # ifdef X64 ASSERT_NOT_IMPLEMENTED(false); # else f_new->pinfo = &(f_new->info); f_new->puc = &(f_new->uc); f_new->puc->uc_mcontext = (IF_X64_ELSE(_STRUCT_MCONTEXT64, _STRUCT_MCONTEXT32) *)&f_new->mc; LOG(THREAD, LOG_ASYNCH, 3, "\tf_new=" PFX ", &handler=" PFX "\n", f_new, &f_new->handler); ASSERT(!for_app || ALIGNED(&f_new->handler, 16)); # endif #endif /* X86 && LINUX */ } /* Only operates on rt frames, so call before converting to plain. * Must be called *after* translating the sigcontext. */ static void fixup_siginfo(dcontext_t *dcontext, int sig, sigframe_rt_t *frame) { /* For some signals, si_addr is a PC which we must translate. */ if (sig != SIGILL && sig != SIGTRAP && sig != SIGFPE) return; /* nothing to do */ sigcontext_t *sc = get_sigcontext_from_rt_frame(frame); kernel_siginfo_t *siginfo = SIGINFO_FROM_RT_FRAME(frame); LOG(THREAD, LOG_ASYNCH, 3, "%s: updating si_addr from " PFX " to " PFX "\n", __FUNCTION__, siginfo->si_addr, sc->SC_XIP); siginfo->si_addr = (void *)sc->SC_XIP; #ifdef LINUX siginfo->si_addr_lsb = sc->SC_XIP & 0x1; #endif } static void memcpy_rt_frame(sigframe_rt_t *frame, byte *dst, bool from_pending) { #if defined(MACOS) && !defined(X64) if (!from_pending) { /* The kernel puts padding in the middle. We collapse that padding here * and re-align when we copy to the app stack. * We should not reference fields from mc onward in what the kernel put * on the stack, as our sigframe_rt_t layout does not match the kernel's * variable mid-struct padding. */ sigcontext_t *sc = SIGCXT_FROM_UCXT(frame->puc); memcpy(dst, frame, offsetof(sigframe_rt_t, puc) + sizeof(frame->puc)); memcpy(&((sigframe_rt_t *)dst)->mc, sc, sizeof(sigframe_rt_t) - offsetof(sigframe_rt_t, mc)); return; } #endif memcpy(dst, frame, sizeof(sigframe_rt_t)); } /* Copies frame to sp. * PR 304708: we now leave in rt form right up until we copy to the * app stack, so that we can deliver to a client at a safe spot * in rt form, so this routine now converts to a plain frame if necessary. * If no restorer, touches up pretcode * (and if rt_frame, touches up pinfo and puc) * Also touches up fpstate pointer */ static void copy_frame_to_stack(dcontext_t *dcontext, int sig, sigframe_rt_t *frame, byte *sp, bool from_pending) { thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field; bool rtframe = IS_RT_FOR_APP(info, sig); uint frame_size = get_app_frame_size(info, sig); #if defined(LINUX) && defined(X86_32) bool has_restorer = sig_has_restorer(info, sig); #endif byte *flush_pc; bool stack_unwritable = false; uint size = frame_size; #if defined(LINUX) && defined(X86) sigcontext_t *sc = get_sigcontext_from_rt_frame(frame); size += (sc->fpstate == NULL ? 0 : signal_frame_extra_size(true)); #endif /* LINUX && X86 */ LOG(THREAD, LOG_ASYNCH, 3, "copy_frame_to_stack: rt=%d, src=" PFX ", sp=" PFX "\n", rtframe, frame, sp); fixup_siginfo(dcontext, sig, frame); /* We avoid querying memory as it incurs global contended locks. */ flush_pc = is_executable_area_writable_overlap(sp, sp + size); if (flush_pc != NULL) { LOG(THREAD, LOG_ASYNCH, 2, "\tcopy_frame_to_stack: part of stack is unwritable-by-us @" PFX "\n", flush_pc); flush_fragments_and_remove_region(dcontext, flush_pc, sp + size - flush_pc, false /* don't own initexit_lock */, false /* keep futures */); } TRY_EXCEPT(dcontext, /* try */ { if (rtframe) { ASSERT(frame_size == sizeof(*frame)); memcpy_rt_frame(frame, sp, from_pending); } IF_NOT_X64( IF_LINUX(else convert_frame_to_nonrt(dcontext, sig, frame, (sigframe_plain_t *)sp);)); }, /* except */ { stack_unwritable = true; }); if (stack_unwritable) { /* Override the no-nested check in record_pending_signal(): it's ok b/c * receive_pending_signal() calls to here at a consistent point, * and we won't return there. */ info->nested_pending_ok = true; /* Just throw away this signal and deliver SIGSEGV instead with the * same sigcontext, like the kernel does. */ free_pending_signal(info, sig); os_forge_exception(0, UNREADABLE_MEMORY_EXECUTION_EXCEPTION); ASSERT_NOT_REACHED(); } kernel_sigset_t *mask_to_restore = NULL; if (info->pre_syscall_app_sigprocmask_valid) { mask_to_restore = &info->pre_syscall_app_sigprocmask; info->pre_syscall_app_sigprocmask_valid = false; } else { mask_to_restore = &info->app_sigblocked; } /* if !has_restorer we do NOT add the restorer code to the exec list here, * to avoid removal problems (if handler never returns) and consistency problems * (would have to mark as selfmod right now if on stack). * for PROGRAM_SHEPHERDING we recognize as a pattern, and for consistency we * allow entire region once try to execute -- not a performance worry since should * very rarely be on the stack: should either be libc restorer code or with recent * OS in rx vsyscall page. */ /* fix up pretcode, pinfo, puc, fpstate */ if (rtframe) { sigframe_rt_t *f_new = (sigframe_rt_t *)sp; fixup_rtframe_pointers(dcontext, sig, frame, f_new, true /*for app*/); #ifdef HAVE_SIGALTSTACK /* Make sure the frame's sigstack reflects the app stack, both for transparency * of the app examining it and for correctness if we detach mid-handler. */ LOG(THREAD, LOG_ASYNCH, 3, "updated uc_stack @" PFX " to " PFX "\n", &f_new->uc.uc_stack, info->app_sigstack.ss_sp); f_new->uc.uc_stack = info->app_sigstack; #endif /* Store the prior mask, for restoring in sigreturn. */ memcpy(&f_new->uc.uc_sigmask, mask_to_restore, sizeof(info->app_sigblocked)); } else { #ifdef X64 ASSERT_NOT_REACHED(); #endif #if defined(LINUX) && !defined(X64) sigframe_plain_t *f_new = (sigframe_plain_t *)sp; # ifdef X86 # ifndef VMX86_SERVER sigframe_plain_t *f_old = (sigframe_plain_t *)frame; # endif if (has_restorer) f_new->pretcode = (char *)info->app_sigaction[sig]->restorer; else { # ifdef VMX86_SERVER /* PR 404712: skip kernel's restorer code */ f_new->pretcode = (char *)dynamorio_nonrt_sigreturn; # else /* see comments in rt case above */ if (f_old->pretcode == f_old->retcode) f_new->pretcode = f_new->retcode; else { /* whether we set to dynamorio_sigreturn in master_signal_handler * or it's still vsyscall page, we have to convert to non-rt */ f_new->pretcode = (char *)dynamorio_nonrt_sigreturn; } /* else, pointing at vsyscall most likely */ LOG(THREAD, LOG_ASYNCH, 3, "\tleaving pretcode with old value\n"); # endif } /* convert_frame_to_nonrt*() should have updated fpstate pointer. * The inlined fpstate is no longer used on new kernels, and we do that * as well on older kernels. */ ASSERT(f_new->sc.fpstate != &f_new->fpstate); /* 32-bit kernel copies to aligned buf so no assert on fpstate alignment */ LOG(THREAD, LOG_ASYNCH, 3, "\tretaddr = " PFX "\n", f_new->pretcode); /* There is no stored alt stack in a plain frame to update. */ # ifdef RETURN_AFTER_CALL info->signal_restorer_retaddr = (app_pc)f_new->pretcode; # endif # endif /* X86 */ /* Store the prior mask, for restoring in sigreturn. */ convert_rt_mask_to_nonrt(f_new, mask_to_restore); #endif /* LINUX && !X64 */ } #ifdef MACOS # ifdef X64 ASSERT_NOT_IMPLEMENTED(false); # else /* Update handler field, which is passed to the libc trampoline, to app */ ASSERT(info->app_sigaction[sig] != NULL); ((sigframe_rt_t *)sp)->handler = (app_pc)info->app_sigaction[sig]->handler; # endif #endif } /* Copies frame to pending slot. * PR 304708: we now leave in rt form right up until we copy to the * app stack, so that we can deliver to a client at a safe spot * in rt form. */ static void copy_frame_to_pending(dcontext_t *dcontext, int sig, sigframe_rt_t *frame _IF_CLIENT(byte *access_address)) { thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field; sigframe_rt_t *dst = &(info->sigpending[sig]->rt_frame); memcpy_rt_frame(frame, (byte *)dst, false /*!already pending*/); #if defined(LINUX) && defined(X86) /* For lazy fpstate, it's possible there was no fpstate when the kernel * sent us the frame, but in between then and now the app executed some * fp or xmm/ymm instrs. Today we always add fpstate just in case. * XXX i#641 optimization: track whether any fp/xmm/ymm * instrs happened and avoid this. */ /* we'll fill in updated fpstate at delivery time, but we go ahead and * copy now in case our own retrieval somehow misses some fields */ if (frame->uc.uc_mcontext.fpstate != NULL) { memcpy(&info->sigpending[sig]->xstate, frame->uc.uc_mcontext.fpstate, /* XXX: assuming full xstate if avx is enabled */ signal_frame_extra_size(false)); } /* we must set the pointer now so that later save_fpstate, etc. work */ dst->uc.uc_mcontext.fpstate = (kernel_fpstate_t *)&info->sigpending[sig]->xstate; #endif /* LINUX && X86 */ #ifdef CLIENT_INTERFACE info->sigpending[sig]->access_address = access_address; #endif info->sigpending[sig]->use_sigcontext = false; #ifdef MACOS /* We rely on puc to find sc to we have to fix it up */ fixup_rtframe_pointers(dcontext, sig, frame, dst, false /*!for app*/); #endif LOG(THREAD, LOG_ASYNCH, 3, "copy_frame_to_pending from " PFX "\n", frame); DOLOG(3, LOG_ASYNCH, { LOG(THREAD, LOG_ASYNCH, 3, "sigcontext:\n"); dump_sigcontext(dcontext, get_sigcontext_from_rt_frame(dst)); }); } /**** real work ***********************************************/ /* transfer control from signal handler to fcache return routine */ static void transfer_from_sig_handler_to_fcache_return(dcontext_t *dcontext, kernel_ucontext_t *uc, sigcontext_t *sc_interrupted, int sig, app_pc next_pc, linkstub_t *last_exit, bool is_kernel_xfer) { sigcontext_t *sc = SIGCXT_FROM_UCXT(uc); #ifdef CLIENT_INTERFACE if (is_kernel_xfer) { sig_full_cxt_t sc_interrupted_full = { sc_interrupted, NULL /*not provided*/ }; sig_full_cxt_t sc_full; sig_full_initialize(&sc_full, uc); sc->SC_XIP = (ptr_uint_t)next_pc; if (instrument_kernel_xfer(dcontext, DR_XFER_SIGNAL_DELIVERY, sc_interrupted_full, NULL, NULL, next_pc, sc->SC_XSP, sc_full, NULL, sig)) next_pc = canonicalize_pc_target(dcontext, (app_pc)sc->SC_XIP); } #endif dcontext->next_tag = canonicalize_pc_target(dcontext, next_pc); IF_ARM(dr_set_isa_mode(dcontext, get_pc_mode_from_cpsr(sc), NULL)); /* Set our sigreturn context to point to fcache_return! * Then we'll go back through kernel, appear in fcache_return, * and go through d_r_dispatch & interp, without messing up dynamo stack. * Note that even if this is a write in the shared cache, we * still go to the private fcache_return for simplicity. */ sc->SC_XIP = (ptr_uint_t)fcache_return_routine(dcontext); #ifdef AARCHXX /* We do not have to set dr_reg_stolen in dcontext's mcontext here * because dcontext's mcontext is stale and we used the mcontext * created from recreate_app_state_internal with the original sigcontext. */ /* We restore dr_reg_stolen's app value in recreate_app_state_internal, * so now we need set dr_reg_stolen to hold DR's TLS before sigreturn * from DR's handler. */ ASSERT(get_sigcxt_stolen_reg(sc) != (reg_t)*get_dr_tls_base_addr()); set_sigcxt_stolen_reg(sc, (reg_t)*get_dr_tls_base_addr()); # ifndef AARCH64 /* We're going to our fcache_return gencode which uses DEFAULT_ISA_MODE */ set_pc_mode_in_cpsr(sc, DEFAULT_ISA_MODE); # endif #endif #if defined(X64) || defined(ARM) /* x64 always uses shared gencode */ get_local_state_extended()->spill_space.IF_X86_ELSE(xax, r0) = sc->IF_X86_ELSE(SC_XAX, SC_R0); # ifdef AARCH64 /* X1 needs to be spilled because of br x1 in exit stubs. */ get_local_state_extended()->spill_space.r1 = sc->SC_R1; # endif #else get_mcontext(dcontext)->IF_X86_ELSE(xax, r0) = sc->IF_X86_ELSE(SC_XAX, SC_R0); #endif LOG(THREAD, LOG_ASYNCH, 2, "\tsaved xax " PFX "\n", sc->IF_X86_ELSE(SC_XAX, SC_R0)); sc->IF_X86_ELSE(SC_XAX, SC_R0) = (ptr_uint_t)last_exit; LOG(THREAD, LOG_ASYNCH, 2, "\tset next_tag to " PFX ", resuming in fcache_return\n", next_pc); LOG(THREAD, LOG_ASYNCH, 3, "transfer_from_sig_handler_to_fcache_return\n"); DOLOG(3, LOG_ASYNCH, { LOG(THREAD, LOG_ASYNCH, 3, "sigcontext @" PFX ":\n", sc); dump_sigcontext(dcontext, sc); }); } #ifdef CLIENT_INTERFACE static dr_signal_action_t send_signal_to_client(dcontext_t *dcontext, int sig, sigframe_rt_t *frame, sigcontext_t *raw_sc, byte *access_address, bool blocked, fragment_t *fragment) { kernel_ucontext_t *uc = get_ucontext_from_rt_frame(frame); dr_siginfo_t si; dr_signal_action_t action; /* XXX #1615: we need a full ucontext to store pre-xl8 simd values. * Right now we share the same simd values with post-xl8. */ sig_full_cxt_t raw_sc_full; sig_full_initialize(&raw_sc_full, uc); raw_sc_full.sc = raw_sc; if (!dr_signal_hook_exists()) return DR_SIGNAL_DELIVER; LOG(THREAD, LOG_ASYNCH, 2, "sending signal to client\n"); si.sig = sig; si.drcontext = (void *)dcontext; /* It's safe to allocate since we do not send signals that interrupt DR. * With priv_mcontext_t x2 that's a little big for stack alloc. */ si.mcontext = heap_alloc(dcontext, sizeof(*si.mcontext) HEAPACCT(ACCT_OTHER)); si.raw_mcontext = heap_alloc(dcontext, sizeof(*si.raw_mcontext) HEAPACCT(ACCT_OTHER)); dr_mcontext_init(si.mcontext); dr_mcontext_init(si.raw_mcontext); /* i#207: fragment tag and fcache start pc on fault. */ si.fault_fragment_info.tag = NULL; si.fault_fragment_info.cache_start_pc = NULL; /* i#182/PR 449996: we provide the pre-translation context */ if (raw_sc != NULL) { fragment_t wrapper; si.raw_mcontext_valid = true; sigcontext_to_mcontext(dr_mcontext_as_priv_mcontext(si.raw_mcontext), &raw_sc_full, si.raw_mcontext->flags); /* i#207: fragment tag and fcache start pc on fault. */ /* FIXME: we should avoid the fragment_pclookup since it is expensive * and since we already did the work of a lookup when translating */ if (fragment == NULL) fragment = fragment_pclookup(dcontext, si.raw_mcontext->pc, &wrapper); if (fragment != NULL && !hide_tag_from_client(fragment->tag)) { si.fault_fragment_info.tag = fragment->tag; si.fault_fragment_info.cache_start_pc = FCACHE_ENTRY_PC(fragment); si.fault_fragment_info.is_trace = TEST(FRAG_IS_TRACE, fragment->flags); si.fault_fragment_info.app_code_consistent = !TESTANY(FRAG_WAS_DELETED | FRAG_SELFMOD_SANDBOXED, fragment->flags); } } else si.raw_mcontext_valid = false; /* The client has no way to calculate this when using * instrumentation that deliberately faults (to shift a rare event * out of the fastpath) so we provide it. When raw_mcontext is * available the client can calculate it, but we provide it as a * convenience anyway. */ si.access_address = access_address; si.blocked = blocked; ucontext_to_mcontext(dr_mcontext_as_priv_mcontext(si.mcontext), uc); /* We disallow the client calling dr_redirect_execution(), so we * will not leak si */ action = instrument_signal(dcontext, &si); if (action == DR_SIGNAL_DELIVER || action == DR_SIGNAL_REDIRECT) { /* propagate client changes */ CLIENT_ASSERT(si.mcontext->flags == DR_MC_ALL, "signal mcontext flags cannot be changed"); mcontext_to_ucontext(uc, dr_mcontext_as_priv_mcontext(si.mcontext)); } else if (action == DR_SIGNAL_SUPPRESS && raw_sc != NULL) { /* propagate client changes */ CLIENT_ASSERT(si.raw_mcontext->flags == DR_MC_ALL, "signal mcontext flags cannot be changed"); mcontext_to_sigcontext(&raw_sc_full, dr_mcontext_as_priv_mcontext(si.raw_mcontext), si.raw_mcontext->flags); } heap_free(dcontext, si.mcontext, sizeof(*si.mcontext) HEAPACCT(ACCT_OTHER)); heap_free(dcontext, si.raw_mcontext, sizeof(*si.raw_mcontext) HEAPACCT(ACCT_OTHER)); return action; } /* Returns false if caller should exit */ static bool handle_client_action_from_cache(dcontext_t *dcontext, int sig, dr_signal_action_t action, sigframe_rt_t *our_frame, sigcontext_t *sc_orig, sigcontext_t *sc_interrupted, bool blocked) { thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field; kernel_ucontext_t *uc = get_ucontext_from_rt_frame(our_frame); sigcontext_t *sc = SIGCXT_FROM_UCXT(uc); /* in order to pass to the client, we come all the way here for signals * the app has no handler for */ if (action == DR_SIGNAL_REDIRECT) { /* send_signal_to_client copied mcontext into our * master_signal_handler frame, so we set up for fcache_return w/ * our frame's state */ transfer_from_sig_handler_to_fcache_return( dcontext, uc, sc_interrupted, sig, (app_pc)sc->SC_XIP, (linkstub_t *)get_asynch_linkstub(), true); if (is_building_trace(dcontext)) { LOG(THREAD, LOG_ASYNCH, 3, "\tsquashing trace-in-progress\n"); trace_abort(dcontext); } return false; } else if (action == DR_SIGNAL_SUPPRESS || (!blocked && info->app_sigaction[sig] != NULL && info->app_sigaction[sig]->handler == (handler_t)SIG_IGN)) { LOG(THREAD, LOG_ASYNCH, 2, "%s: not delivering!\n", (action == DR_SIGNAL_SUPPRESS) ? "client suppressing signal" : "app signal handler is SIG_IGN"); /* restore original (untranslated) sc */ *get_sigcontext_from_rt_frame(our_frame) = *sc_orig; return false; } else if (!blocked && /* no BYPASS for blocked */ (action == DR_SIGNAL_BYPASS || (info->app_sigaction[sig] == NULL || info->app_sigaction[sig]->handler == (handler_t)SIG_DFL))) { LOG(THREAD, LOG_ASYNCH, 2, "%s: executing default action\n", (action == DR_SIGNAL_BYPASS) ? "client forcing default" : "app signal handler is SIG_DFL"); if (execute_default_from_cache(dcontext, sig, our_frame, sc_orig, false)) { /* if we haven't terminated, restore original (untranslated) sc * on request. */ *get_sigcontext_from_rt_frame(our_frame) = *sc_orig; LOG(THREAD, LOG_ASYNCH, 2, "%s: restored xsp=" PFX ", xip=" PFX "\n", __FUNCTION__, get_sigcontext_from_rt_frame(our_frame)->SC_XSP, get_sigcontext_from_rt_frame(our_frame)->SC_XIP); } return false; } CLIENT_ASSERT(action == DR_SIGNAL_DELIVER, "invalid signal event return value"); return true; } #endif static void abort_on_fault(dcontext_t *dcontext, uint dumpcore_flag, app_pc pc, byte *target, int sig, sigframe_rt_t *frame, const char *prefix, const char *signame, const char *where) { kernel_ucontext_t *ucxt = &frame->uc; sigcontext_t *sc = SIGCXT_FROM_UCXT(ucxt); bool stack_overflow = (sig == SIGSEGV && is_stack_overflow(dcontext, target)); #if defined(STATIC_LIBRARY) && defined(LINUX) thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field; uint orig_dumpcore_flag = dumpcore_flag; if (init_info.app_sigaction != NULL) info = &init_info; /* use init-time handler */ ASSERT(info->app_sigaction != NULL); #endif const char *fmt = "%s %s at PC " PFX "\n" "Received SIG%s at%s pc " PFX " in thread " TIDFMT "\n" "Base: " PFX "\n" "Registers:" #ifdef X86 "eax=" PFX " ebx=" PFX " ecx=" PFX " edx=" PFX "\n" "\tesi=" PFX " edi=" PFX " esp=" PFX " ebp=" PFX "\n" # ifdef X64 "\tr8 =" PFX " r9 =" PFX " r10=" PFX " r11=" PFX "\n" "\tr12=" PFX " r13=" PFX " r14=" PFX " r15=" PFX "\n" # endif /* X64 */ #elif defined(ARM) # ifndef X64 " r0 =" PFX " r1 =" PFX " r2 =" PFX " r3 =" PFX "\n" "\tr4 =" PFX " r5 =" PFX " r6 =" PFX " r7 =" PFX "\n" "\tr8 =" PFX " r9 =" PFX " r10=" PFX " r11=" PFX "\n" "\tr12=" PFX " r13=" PFX " r14=" PFX " r15=" PFX "\n" # else # error NYI on AArch64 # endif #endif /* X86/ARM */ "\teflags=" PFX; #if defined(STATIC_LIBRARY) && defined(LINUX) /* i#2119: if we're invoking an app handler, disable a fatal coredump. */ if (INTERNAL_OPTION(invoke_app_on_crash) && info->app_sigaction[sig] != NULL && IS_RT_FOR_APP(info, sig) && TEST(dumpcore_flag, DYNAMO_OPTION(dumpcore_mask)) && !DYNAMO_OPTION(live_dump)) dumpcore_flag = 0; #endif report_dynamorio_problem( dcontext, dumpcore_flag | (stack_overflow ? DUMPCORE_STACK_OVERFLOW : 0), pc, (app_pc)sc->SC_FP, fmt, prefix, stack_overflow ? STACK_OVERFLOW_NAME : CRASH_NAME, pc, signame, where, pc, d_r_get_thread_id(), get_dynamorio_dll_start(), #ifdef X86 sc->SC_XAX, sc->SC_XBX, sc->SC_XCX, sc->SC_XDX, sc->SC_XSI, sc->SC_XDI, sc->SC_XSP, sc->SC_XBP, # ifdef X64 sc->SC_FIELD(r8), sc->SC_FIELD(r9), sc->SC_FIELD(r10), sc->SC_FIELD(r11), sc->SC_FIELD(r12), sc->SC_FIELD(r13), sc->SC_FIELD(r14), sc->SC_FIELD(r15), # endif /* X86 */ #elif defined(ARM) # ifndef X64 sc->SC_FIELD(arm_r0), sc->SC_FIELD(arm_r1), sc->SC_FIELD(arm_r2), sc->SC_FIELD(arm_r3), sc->SC_FIELD(arm_r4), sc->SC_FIELD(arm_r5), sc->SC_FIELD(arm_r6), sc->SC_FIELD(arm_r7), sc->SC_FIELD(arm_r8), sc->SC_FIELD(arm_r9), sc->SC_FIELD(arm_r10), sc->SC_FIELD(arm_fp), sc->SC_FIELD(arm_ip), sc->SC_FIELD(arm_sp), sc->SC_FIELD(arm_lr), sc->SC_FIELD(arm_pc), # else # error NYI on AArch64 # endif /* X64 */ #endif /* X86/ARM */ sc->SC_XFLAGS); #if defined(STATIC_LIBRARY) && defined(LINUX) /* i#2119: For static DR, the surrounding app's handler may well be * safe to invoke even when DR state is messed up: it's worth a try, as it * likely has useful reporting features for users of the app. * We limit to Linux and RT for simplicity: it can be expanded later if static * library use expands. */ if (INTERNAL_OPTION(invoke_app_on_crash) && info->app_sigaction[sig] != NULL && IS_RT_FOR_APP(info, sig)) { SYSLOG(SYSLOG_WARNING, INVOKING_APP_HANDLER, 2, get_application_name(), get_application_pid()); (*info->app_sigaction[sig]->handler)(sig, &frame->info, ucxt); /* If the app handler didn't terminate, now get a fatal core. */ if (TEST(orig_dumpcore_flag, DYNAMO_OPTION(dumpcore_mask)) && !DYNAMO_OPTION(live_dump)) os_dump_core("post-app-handler attempt at core dump"); } #endif os_terminate(dcontext, TERMINATE_PROCESS); ASSERT_NOT_REACHED(); } static void abort_on_DR_fault(dcontext_t *dcontext, app_pc pc, byte *target, int sig, sigframe_rt_t *frame, const char *signame, const char *where) { abort_on_fault(dcontext, DUMPCORE_INTERNAL_EXCEPTION, pc, target, sig, frame, exception_label_core, signame, where); ASSERT_NOT_REACHED(); } /* Returns whether unlinked or mangled syscall. * Restored in receive_pending_signal. */ static bool unlink_fragment_for_signal(dcontext_t *dcontext, fragment_t *f, byte *pc /*interruption pc*/) { /* We only come here if we interrupted a fragment in the cache, * or interrupted transition gencode (i#2019), * which means that this thread's DR state is safe, and so it * should be ok to acquire a lock. xref PR 596069. * * There is a race where if two threads hit a signal in the same * shared fragment, the first could re-link after the second * un-links but before the second exits, and the second could then * execute the syscall, resulting in arbitrary delay prior to * signal delivery. We don't want to allocate global memory, * but we could use a static array of counters (since should * be small # of interrupted shared fragments at any one time) * used as refcounts so we only unlink when all are done. * Not bothering to implement now: going to live w/ chance of * long signal delays. xref PR 596069. */ bool changed = false; bool waslinking = is_couldbelinking(dcontext); if (!waslinking) enter_couldbelinking(dcontext, NULL, false); /* may not be linked if trace_relink or something */ if (TEST(FRAG_COARSE_GRAIN, f->flags)) { /* XXX PR 213040: we don't support unlinking coarse, so we try * not to come here, but for indirect branch and other spots * where we don't yet support translation (since can't fault) * we end up w/ no bound on delivery... */ } else if (TEST(FRAG_LINKED_OUTGOING, f->flags)) { LOG(THREAD, LOG_ASYNCH, 3, "\tunlinking outgoing for interrupted F%d\n", f->id); SHARED_FLAGS_RECURSIVE_LOCK(f->flags, acquire, change_linking_lock); // Double-check flags to ensure some other thread didn't unlink // while we waited for the change_linking_lock. if (TEST(FRAG_LINKED_OUTGOING, f->flags)) { unlink_fragment_outgoing(dcontext, f); changed = true; } SHARED_FLAGS_RECURSIVE_LOCK(f->flags, release, change_linking_lock); } else { LOG(THREAD, LOG_ASYNCH, 3, "\toutgoing already unlinked for interrupted F%d\n", f->id); } if (TEST(FRAG_HAS_SYSCALL, f->flags)) { /* Syscalls are signal barriers! * Make sure the next syscall (if any) in f is not executed! * instead go back to d_r_dispatch right before the syscall */ /* syscall mangling does a bunch of decodes but only one write, * changing the target of a short jmp, which is atomic * since a one-byte write, so we don't need the change_linking_lock. */ if (mangle_syscall_code(dcontext, f, pc, false /*do not skip exit cti*/)) changed = true; } if (!waslinking) enter_nolinking(dcontext, NULL, false); return changed; } static void relink_interrupted_fragment(dcontext_t *dcontext, thread_sig_info_t *info) { if (info->interrupted == NULL) return; /* i#2066: if we were building a trace, it may already be re-linked */ if (!TEST(FRAG_LINKED_OUTGOING, info->interrupted->flags)) { LOG(THREAD, LOG_ASYNCH, 3, "\tre-linking outgoing for interrupted F%d\n", info->interrupted->id); SHARED_FLAGS_RECURSIVE_LOCK(info->interrupted->flags, acquire, change_linking_lock); /* Double-check flags to ensure some other thread didn't link * while we waited for the change_linking_lock. */ if (!TEST(FRAG_LINKED_OUTGOING, info->interrupted->flags)) { link_fragment_outgoing(dcontext, info->interrupted, false); } SHARED_FLAGS_RECURSIVE_LOCK(info->interrupted->flags, release, change_linking_lock); } if (TEST(FRAG_HAS_SYSCALL, info->interrupted->flags)) { /* restore syscall (they're a barrier to signals, so signal * handler has cur frag exit before it does a syscall) */ if (info->interrupted_pc != NULL) { mangle_syscall_code(dcontext, info->interrupted, info->interrupted_pc, true /*skip exit cti*/); } } info->interrupted = NULL; info->interrupted_pc = NULL; } static bool interrupted_inlined_syscall(dcontext_t *dcontext, fragment_t *f, byte *pc /*interruption pc*/) { bool pre_or_post_syscall = false; if (TEST(FRAG_HAS_SYSCALL, f->flags)) { /* PR 596147: if the thread is currently in an inlined * syscall when a signal comes in, we can't delay and bound the * delivery time: we need to deliver now. Should decode * backward and see if syscall. We assume our translation of * the interruption state is fine to re-start: i.e., the syscall * is complete if kernel has pc at post-syscall point, and * kernel set EINTR in eax if necessary. */ /* Interrupted fcache, so ok to alloc memory for decode */ instr_t instr; byte *nxt_pc; instr_init(dcontext, &instr); nxt_pc = decode(dcontext, pc, &instr); if (nxt_pc != NULL && instr_valid(&instr) && instr_is_syscall(&instr)) { /* pre-syscall but post-jmp so can't skip syscall */ pre_or_post_syscall = true; } else { size_t syslen = syscall_instr_length(FRAG_ISA_MODE(f->flags)); instr_reset(dcontext, &instr); nxt_pc = decode(dcontext, pc - syslen, &instr); if (nxt_pc != NULL && instr_valid(&instr) && instr_is_syscall(&instr)) { #if defined(X86) && !defined(MACOS) /* decoding backward so check for exit cti jmp prior * to syscall to ensure no mismatch */ instr_reset(dcontext, &instr); nxt_pc = decode(dcontext, pc - syslen - JMP_LONG_LENGTH, &instr); if (nxt_pc != NULL && instr_valid(&instr) && instr_get_opcode(&instr) == OP_jmp) { /* post-inlined-syscall */ pre_or_post_syscall = true; } #else /* On Mac and ARM we have some TLS spills in between so we just * trust that this is a syscall (esp on ARM w/ aligned instrs). */ pre_or_post_syscall = true; #endif } } instr_free(dcontext, &instr); } return pre_or_post_syscall; } /* i#1145: auto-restart syscalls interrupted by signals */ static bool adjust_syscall_for_restart(dcontext_t *dcontext, thread_sig_info_t *info, int sig, sigcontext_t *sc, fragment_t *f, reg_t orig_retval_reg) { byte *pc = (byte *)sc->SC_XIP; int sys_inst_len; if (sc->IF_X86_ELSE(SC_XAX, SC_R0) != -EINTR) { /* The syscall succeeded, so no reason to interrupt. * Some syscalls succeed on a signal coming in. * E.g., SYS_wait4 on SIGCHLD, or reading from a slow device. * XXX: Now that we pass SA_RESTART we should never get here? */ return false; } /* Don't restart if the app's handler says not to */ if (info->app_sigaction[sig] != NULL && !TEST(SA_RESTART, info->app_sigaction[sig]->flags)) { return false; } /* XXX i#1145: some syscalls are never restarted when interrupted by a signal. * We check those that are simple to distinguish below, but not all are. We have * this under an option so it can be disabled if necessary. */ if (!DYNAMO_OPTION(restart_syscalls)) return false; /* Now that we use SA_RESTART we rely on that and ignore our own * inaccurate check sysnum_is_not_restartable(sysnum). * SA_RESTART also means we can just be passed in the register value to restore. */ LOG(THREAD, LOG_ASYNCH, 2, "%s: restored xax/r0 to %ld\n", __FUNCTION__, orig_retval_reg); #ifdef X86 sc->SC_XAX = orig_retval_reg; #elif defined(AARCHXX) sc->SC_R0 = orig_retval_reg; #else # error NYI #endif /* Now adjust the pc to point at the syscall instruction instead of after it, * so when we resume we'll go back to the syscall. * Adjusting solves transparency as well: natively the kernel adjusts * the pc before setting up the signal frame. * We don't pass in the post-syscall pc provided by the kernel because * we want the app pc, not the raw pc. */ dr_isa_mode_t isa_mode; if (is_after_syscall_address(dcontext, pc) || pc == vsyscall_sysenter_return_pc) { isa_mode = dr_get_isa_mode(dcontext); } else { /* We're going to walk back in the fragment, not gencode */ ASSERT(f != NULL); isa_mode = FRAG_ISA_MODE(f->flags); } sys_inst_len = syscall_instr_length(isa_mode); if (pc == vsyscall_sysenter_return_pc) { #ifdef X86 sc->SC_XIP = (ptr_uint_t)(vsyscall_syscall_end_pc - sys_inst_len); /* To restart sysenter we must re-copy xsp into xbp, as xbp is * clobbered by the kernel. * XXX: The kernel points at the int 0x80 in vsyscall on a restart * and so doesn't have to do this: should we do that too? If so we'll * have to avoid interpreting our own hook which is right after the * int 0x80. */ sc->SC_XBP = sc->SC_XSP; #else ASSERT_NOT_REACHED(); #endif } else if (is_after_syscall_address(dcontext, pc)) { /* We're at do_syscall: point at app syscall instr. We want an app * address b/c this signal will be delayed and the delivery will use * a direct app context: no translation from the cache. * The caller sets info->sigpending[sig]->use_sigcontext for us. */ sc->SC_XIP = (ptr_uint_t)(dcontext->asynch_target - sys_inst_len); DODEBUG({ instr_t instr; dr_isa_mode_t old_mode; dr_set_isa_mode(dcontext, isa_mode, &old_mode); instr_init(dcontext, &instr); ASSERT(decode(dcontext, (app_pc)sc->SC_XIP, &instr) != NULL && instr_is_syscall(&instr)); instr_free(dcontext, &instr); dr_set_isa_mode(dcontext, old_mode, NULL); }); } else { ASSERT_NOT_REACHED(); /* Inlined syscalls no longer come here. */ } LOG(THREAD, LOG_ASYNCH, 2, "%s: sigreturn pc is now " PFX "\n", __FUNCTION__, sc->SC_XIP); return true; } /* XXX: Better to get this code inside arch/ but we'd have to convert to an mcontext * which seems overkill. */ static fragment_t * find_next_fragment_from_gencode(dcontext_t *dcontext, sigcontext_t *sc) { fragment_t *f = NULL; fragment_t wrapper; byte *pc = (byte *)sc->SC_XIP; if (in_clean_call_save(dcontext, pc) || in_clean_call_restore(dcontext, pc)) { #ifdef AARCHXX f = fragment_pclookup(dcontext, (cache_pc)sc->SC_LR, &wrapper); #elif defined(X86) cache_pc retaddr = NULL; /* Get the retaddr. We assume this is the adjustment used by * insert_out_of_line_context_switch(). */ byte *ra_slot = dcontext->dstack - get_clean_call_switch_stack_size() - sizeof(retaddr); /* The extra x86 slot is only there for save. */ if (in_clean_call_save(dcontext, pc)) ra_slot -= get_clean_call_temp_stack_size(); if (d_r_safe_read(ra_slot, sizeof(retaddr), &retaddr)) f = fragment_pclookup(dcontext, retaddr, &wrapper); #else # error Unsupported arch. #endif } else if (in_indirect_branch_lookup_code(dcontext, pc)) { /* Try to find the target if the signal arrived in the IBL. * We could try to be a lot more precise by hardcoding the IBL * sequence here but that would make the code less maintainable. * Instead we try the registers that hold the target app address. */ /* First check for the jmp* on the hit path: that is the only place * in the ibl where the target tag is not sitting in a register. */ #if defined(X86) && defined(X64) /* Optimization for the common case of targeting a prefix on x86_64: * ff 61 08 jmp 0x08(%rcx)[8byte] * The tag is in 0x0(%rcx) so we avoid a decode and pclookup. */ if (*pc == 0xff && *(pc + 1) == 0x61 && *(pc + 2) == 0x08) { f = fragment_lookup(dcontext, *(app_pc *)sc->SC_XCX); } #endif if (f == NULL) { instr_t instr; instr_init(dcontext, &instr); decode_cti(dcontext, pc, &instr); if (instr_is_ibl_hit_jump(&instr)) { priv_mcontext_t mc; sig_full_cxt_t sc_full = { sc, NULL /*not provided*/ }; sigcontext_to_mcontext(&mc, &sc_full, DR_MC_INTEGER | DR_MC_CONTROL); byte *target; if (opnd_is_memory_reference(instr_get_target(&instr))) { target = instr_compute_address_priv(&instr, &mc); ASSERT(target != NULL); if (target != NULL) target = *(byte **)target; } else { ASSERT(opnd_is_reg(instr_get_target(&instr))); target = (byte *)reg_get_value_priv( opnd_get_reg(instr_get_target(&instr)), &mc); } ASSERT(target != NULL); if (target != NULL) f = fragment_pclookup(dcontext, target, &wrapper); /* I tried to hit this case running client.cleancallsig in a loop * and while I could on x86 and x86_64 I never did on ARM or * AArch64. We can remove this once someone hits it and it works. */ IF_AARCHXX(ASSERT_NOT_TESTED()); } instr_free(dcontext, &instr); } #ifdef AARCHXX /* The target is in r2 the whole time, w/ or w/o Thumb LSB. */ if (f == NULL && sc->SC_R2 != 0) f = fragment_lookup(dcontext, ENTRY_PC_TO_DECODE_PC(sc->SC_R2)); #elif defined(X86) /* The target is initially in xcx but is then copied to xbx. */ if (f == NULL && sc->SC_XBX != 0) f = fragment_lookup(dcontext, (app_pc)sc->SC_XBX); if (f == NULL && sc->SC_XCX != 0) f = fragment_lookup(dcontext, (app_pc)sc->SC_XCX); #else # error Unsupported arch. #endif } else { /* If in fcache_enter or do_syscall*, we stored the next_tag in asynch_target * in d_r_dispatch. But, we need to avoid using the asynch_target for the * fragment we just exited if we're in fcache_return. */ if (dcontext->asynch_target != NULL && !in_fcache_return(dcontext, pc)) f = fragment_lookup(dcontext, dcontext->asynch_target); } return f; } static void record_pending_signal(dcontext_t *dcontext, int sig, kernel_ucontext_t *ucxt, sigframe_rt_t *frame, bool forged _IF_CLIENT(byte *access_address)) { thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field; os_thread_data_t *ostd = (os_thread_data_t *)dcontext->os_field; sigcontext_t *sc = SIGCXT_FROM_UCXT(ucxt); /* XXX #1615: we need a full ucontext to store pre-xl8 simd values */ sigcontext_t sc_orig; byte *pc = (byte *)sc->SC_XIP; byte *xsp = (byte *)sc->SC_XSP; bool receive_now = false; bool blocked = false; bool handled = false; bool at_auto_restart_syscall = false; int syslen = 0; reg_t orig_retval_reg = sc->IF_X86_ELSE(SC_XAX, SC_R0); sigpending_t *pend; fragment_t *f = NULL; fragment_t wrapper; /* We no longer block SUSPEND_SIGNAL (i#184/PR 450670) or SIGSEGV (i#193/PR 287309). * But we can have re-entrancy issues in this routine if the app uses the same * SUSPEND_SIGNAL, or the nested SIGSEGV needs to be sent to the app. The * latter shouldn't happen unless the app sends SIGSEGV via SYS_kill(). */ if (ostd->processing_signal > 0 || /* If we interrupted receive_pending_signal() we can't prepend a new * pending or delete an old b/c we might mess up the state so we * just drop this one: should only happen for alarm signal */ (info->accessing_sigpending && !info->nested_pending_ok && /* we do want to report a crash in receive_pending_signal() */ (can_always_delay[sig] || is_sys_kill(dcontext, pc, (byte *)sc->SC_XSP, &frame->info)))) { LOG(THREAD, LOG_ASYNCH, 1, "nested signal %d\n", sig); ASSERT(ostd->processing_signal == 0 || sig == SUSPEND_SIGNAL || sig == SIGSEGV); ASSERT(can_always_delay[sig] || is_sys_kill(dcontext, pc, (byte *)sc->SC_XSP, &frame->info)); /* To avoid re-entrant execution of special_heap_alloc() and of * prepending to the pending list we just drop this signal. * FIXME i#194/PR 453996: do better. */ STATS_INC(num_signals_dropped); SYSLOG_INTERNAL_WARNING_ONCE("dropping nested signal"); return; } ostd->processing_signal++; /* no need for atomicity: thread-private */ /* First, check whether blocked, before we restore for sigsuspend (i#1340). */ if (kernel_sigismember(&info->app_sigblocked, sig)) blocked = true; if (info->in_sigsuspend) { /* sigsuspend ends when a signal is received, so restore the * old blocked set */ info->app_sigblocked = info->app_sigblocked_save; info->in_sigsuspend = false; /* update the set to restore to post-signal-delivery */ #ifdef MACOS ucxt->uc_sigmask = *(__darwin_sigset_t *)&info->app_sigblocked; #else ucxt->uc_sigmask = info->app_sigblocked; #endif #ifdef DEBUG if (d_r_stats->loglevel >= 3 && (d_r_stats->logmask & LOG_ASYNCH) != 0) { LOG(THREAD, LOG_ASYNCH, 3, "after sigsuspend, blocked signals are now:\n"); dump_sigset(dcontext, &info->app_sigblocked); } #endif } if (get_at_syscall(dcontext)) syslen = syscall_instr_length(dr_get_isa_mode(dcontext)); if (info->app_sigaction[sig] != NULL && info->app_sigaction[sig]->handler == (handler_t)SIG_IGN /* If a client registered a handler, put this in the queue. * Races between registering, queueing, and delivering are fine. */ IF_CLIENT_INTERFACE(&&!dr_signal_hook_exists())) { LOG(THREAD, LOG_ASYNCH, 3, "record_pending_signal (%d at pc " PFX "): action is SIG_IGN!\n", sig, pc); ostd->processing_signal--; return; } else if (blocked) { /* signal is blocked by app, so just record it, don't receive now */ LOG(THREAD, LOG_ASYNCH, 2, "record_pending_signal(%d at pc " PFX "): signal is currently blocked\n", sig, pc); IF_LINUX(handled = notify_signalfd(dcontext, info, sig, frame)); } else if (safe_is_in_fcache(dcontext, pc, xsp)) { LOG(THREAD, LOG_ASYNCH, 2, "record_pending_signal(%d) from cache pc " PFX "\n", sig, pc); if (forged || can_always_delay[sig]) { /* to make translation easier, want to delay if can until d_r_dispatch * unlink cur frag, wait for d_r_dispatch */ /* check for coarse first to avoid cost of coarse pclookup */ if (get_fcache_coarse_info(pc) != NULL) { /* PR 213040: we can't unlink coarse. If we fail to translate * we'll switch back to delaying, below. */ if (sig_is_alarm_signal(sig) && info->sigpending[sig] != NULL && info->sigpending[sig]->next != NULL && info->skip_alarm_xl8 > 0) { /* Translating coarse fragments is very expensive so we * avoid doing it when we're having trouble keeping up w/ * the alarm frequency (PR 213040), but we make sure we try * every once in a while to avoid unbounded signal delay */ info->skip_alarm_xl8--; STATS_INC(num_signals_coarse_delayed); } else { if (sig_is_alarm_signal(sig)) info->skip_alarm_xl8 = SKIP_ALARM_XL8_MAX; receive_now = true; LOG(THREAD, LOG_ASYNCH, 2, "signal interrupted coarse fragment so delivering now\n"); } } else { f = fragment_pclookup(dcontext, pc, &wrapper); ASSERT(f != NULL); ASSERT(!TEST(FRAG_COARSE_GRAIN, f->flags)); /* checked above */ LOG(THREAD, LOG_ASYNCH, 2, "\tdelaying until exit F%d\n", f->id); if (interrupted_inlined_syscall(dcontext, f, pc)) { /* PR 596147: if delayable signal arrives after syscall-skipping * jmp, either at syscall or post-syscall, we deliver * immediately, since we can't bound the delay */ receive_now = true; LOG(THREAD, LOG_ASYNCH, 2, "signal interrupted pre/post syscall itself so delivering now\n"); /* We don't set at_auto_restart_syscall because we just leave * the SA_RESTART kernel-supplied resumption point: with no * post-syscall handler to worry about we have no need to * change anything. */ } else { /* could get another signal but should be in same fragment */ ASSERT(info->interrupted == NULL || info->interrupted == f); if (info->interrupted != f) { /* Just in case there's a prior, avoid leaving it unlinked. */ relink_interrupted_fragment(dcontext, info); if (unlink_fragment_for_signal(dcontext, f, pc)) { info->interrupted = f; info->interrupted_pc = pc; } else { /* either was unlinked for trace creation, or we got another * signal before exiting cache to handle 1st */ ASSERT(info->interrupted == NULL || info->interrupted == f); } } } } } else { /* the signal interrupted code cache => run handler now! */ receive_now = true; LOG(THREAD, LOG_ASYNCH, 2, "\tnot certain can delay so handling now\n"); } } else if (in_generated_routine(dcontext, pc) || /* XXX: should also check fine stubs */ safe_is_in_coarse_stubs(dcontext, pc, xsp)) { /* Assumption: dynamo errors have been caught already inside * the master_signal_handler, thus any error in a generated routine * is an asynch signal that can be delayed */ LOG(THREAD, LOG_ASYNCH, 2, "record_pending_signal(%d) from gen routine or stub " PFX "\n", sig, pc); if (get_at_syscall(dcontext)) { /* i#1206: the syscall was interrupted, so we can go back to d_r_dispatch * and don't need to receive it now (which complicates post-syscall handling) * w/o any extra delay. */ /* i#2659: we now use SA_RESTART to handle interrupting native * auto-restart syscalls. That means we have to adjust do_syscall * interruption to give us control so we can deliver the signal. Due to * needing to run post-syscall handlers (we don't want to get into nested * dcontexts like on Windows) it's simplest to go back to d_r_dispatch, which * is most easily done by emulating the non-SA_RESTART behavior. * XXX: This all seems backward: we should revisit this model and see if * we can get rid of this emulation and the auto-restart emulation. */ /* The get_at_syscall() check above distinguishes from just having * arrived at the syscall instr, but with SA_RESTART we can't distinguish * not-yet-executed-syscall from syscall-was-interrupted-in-the-kernel. * This matters for sigreturn (i#2995), whose asynch_target points somewhere * other than right after the syscall, so we exclude it (it can't be * interrupted so we know we haven't executed it yet). */ if (is_after_syscall_address(dcontext, pc + syslen) && !is_sigreturn_syscall_number(sc->SC_SYSNUM_REG)) { LOG(THREAD, LOG_ASYNCH, 2, "Adjusting interrupted auto-restart syscall from " PFX " to " PFX "\n", pc, pc + syslen); at_auto_restart_syscall = true; sc->SC_XIP += syslen; sc->IF_X86_ELSE(SC_XAX, SC_R0) = -EINTR; pc = (byte *)sc->SC_XIP; } } /* This could come from another thread's SYS_kill (via our gen do_syscall) */ DOLOG(1, LOG_ASYNCH, { if (!is_after_syscall_address(dcontext, pc) && !forged && !can_always_delay[sig]) { LOG(THREAD, LOG_ASYNCH, 1, "WARNING: signal %d in gen routine: may cause problems!\n", sig); } }); /* i#2019: for a signal arriving in gencode before entry to a fragment, * we need to unlink the fragment just like for a signal arriving inside * the fragment itself. * Multiple signals should all have the same asynch_target so we should * only need a single info->interrupted. */ if (info->interrupted == NULL && !get_at_syscall(dcontext)) { f = find_next_fragment_from_gencode(dcontext, sc); if (f != NULL && !TEST(FRAG_COARSE_GRAIN, f->flags)) { if (unlink_fragment_for_signal(dcontext, f, FCACHE_ENTRY_PC(f))) { info->interrupted = f; info->interrupted_pc = FCACHE_ENTRY_PC(f); } } } } else if (get_at_syscall(dcontext) && pc == vsyscall_sysenter_return_pc - syslen && /* See i#2995 comment above: rule out sigreturn */ !is_sigreturn_syscall_number(sc->SC_SYSNUM_REG)) { LOG(THREAD, LOG_ASYNCH, 2, "record_pending_signal(%d) from restart-vsyscall " PFX "\n", sig, pc); /* While the kernel points at int 0x80 for a restart, we leverage our * existing sysenter restart mechanism. */ at_auto_restart_syscall = true; sc->SC_XIP = (reg_t)vsyscall_sysenter_return_pc; sc->IF_X86_ELSE(SC_XAX, SC_R0) = -EINTR; pc = (byte *)sc->SC_XIP; } else if (pc == vsyscall_sysenter_return_pc) { LOG(THREAD, LOG_ASYNCH, 2, "record_pending_signal(%d) from vsyscall " PFX "\n", sig, pc); /* i#1206: the syscall was interrupted but is not auto-restart, so we can go * back to d_r_dispatch and don't need to receive it now (which complicates * post-syscall handling) */ } else if (thread_synch_check_state(dcontext, THREAD_SYNCH_NO_LOCKS) && /* Avoid grabbing locks for xl8 while in a suspended state (i#3026). */ ksynch_get_value(&ostd->suspended) == 0) { /* The signal interrupted DR or the client but it's at a safe spot so * deliver it now. */ receive_now = true; } else { /* the signal interrupted DR itself => do not run handler now! */ LOG(THREAD, LOG_ASYNCH, 2, "record_pending_signal(%d) from DR at pc " PFX "\n", sig, pc); if (!forged && !can_always_delay[sig] && !is_sys_kill(dcontext, pc, (byte *)sc->SC_XSP, &frame->info)) { /* i#195/PR 453964: don't re-execute if will just re-fault. * Our checks for dstack, etc. in master_signal_handler should * have accounted for everything */ ASSERT_NOT_REACHED(); abort_on_DR_fault(dcontext, pc, NULL, sig, frame, (sig == SIGSEGV) ? "SEGV" : "other", " unknown"); } } LOG(THREAD, LOG_ASYNCH, 3, "\taction is not SIG_IGN\n"); #if defined(X86) && defined(LINUX) LOG(THREAD, LOG_ASYNCH, 3, "\tretaddr = " PFX "\n", frame->pretcode); /* pretcode has same offs for plain */ #endif if (receive_now) { /* we need to translate sc before we know whether client wants to * suppress, so we need a backup copy */ bool xl8_success; ASSERT(!at_auto_restart_syscall); /* only used for delayed delivery */ sc_orig = *sc; ASSERT(!forged); /* cache the fragment since pclookup is expensive for coarse (i#658) */ f = fragment_pclookup(dcontext, (cache_pc)sc->SC_XIP, &wrapper); xl8_success = translate_sigcontext(dcontext, ucxt, !can_always_delay[sig], f); if (can_always_delay[sig] && !xl8_success) { /* delay: we expect this for coarse fragments if alarm arrives * in middle of ind branch region or sthg (PR 213040) */ LOG(THREAD, LOG_ASYNCH, 2, "signal is in un-translatable spot in coarse fragment: delaying\n"); receive_now = false; } } if (receive_now) { /* N.B.: since we abandon the old context for synchronous signals, * we do not need to mark this fragment as FRAG_CANNOT_DELETE */ #ifdef DEBUG if (d_r_stats->loglevel >= 2 && (d_r_stats->logmask & LOG_ASYNCH) != 0 && safe_is_in_fcache(dcontext, pc, xsp)) { ASSERT(f != NULL); LOG(THREAD, LOG_ASYNCH, 2, "Got signal at pc " PFX " in this fragment:\n", pc); disassemble_fragment(dcontext, f, false); } #endif LOG(THREAD, LOG_ASYNCH, 2, "Going to receive signal now\n"); /* If we end up executing the default action, we'll go native * since we translated the context. If there's a handler, * we'll copy the context to the app stack and then adjust the * original on our stack so we take over. */ execute_handler_from_cache(dcontext, sig, frame, &sc_orig, f _IF_CLIENT(access_address)); } else if (!handled) { #ifdef CLIENT_INTERFACE /* i#182/PR 449996: must let client act on blocked non-delayable signals to * handle instrumentation faults. Make sure we're at a safe spot: i.e., * only raise for in-cache faults. Checking forged and no-delay * to avoid the in-cache check for delayable signals => safer. */ if (blocked && !forged && !can_always_delay[sig] && safe_is_in_fcache(dcontext, pc, xsp)) { dr_signal_action_t action; /* cache the fragment since pclookup is expensive for coarse (i#658) */ f = fragment_pclookup(dcontext, (cache_pc)sc->SC_XIP, &wrapper); sc_orig = *sc; translate_sigcontext(dcontext, ucxt, true /*shouldn't fail*/, f); /* make a copy before send_signal_to_client() tweaks it */ sigcontext_t sc_interrupted = *sc; action = send_signal_to_client(dcontext, sig, frame, &sc_orig, access_address, true /*blocked*/, f); /* For blocked signal early event we disallow BYPASS (xref i#182/PR 449996) */ CLIENT_ASSERT(action != DR_SIGNAL_BYPASS, "cannot bypass a blocked signal event"); if (!handle_client_action_from_cache(dcontext, sig, action, frame, &sc_orig, &sc_interrupted, true /*blocked*/)) { ostd->processing_signal--; return; } /* restore original (untranslated) sc */ *get_sigcontext_from_rt_frame(frame) = sc_orig; } #endif /* i#196/PR 453847: avoid infinite loop of signals if try to re-execute */ if (blocked && !can_always_delay[sig] && !is_sys_kill(dcontext, pc, (byte *)sc->SC_XSP, &frame->info)) { ASSERT(default_action[sig] == DEFAULT_TERMINATE || default_action[sig] == DEFAULT_TERMINATE_CORE); LOG(THREAD, LOG_ASYNCH, 1, "blocked fatal signal %d cannot be delayed: terminating\n", sig); sc_orig = *sc; /* If forged we're likely couldbelinking, and we don't need to xl8. */ if (forged) ASSERT(is_couldbelinking(dcontext)); else translate_sigcontext(dcontext, ucxt, true /*shouldn't fail*/, NULL); /* the process should be terminated */ execute_default_from_cache(dcontext, sig, frame, &sc_orig, forged); ASSERT_NOT_REACHED(); } /* Happened in DR, do not translate context. Record for later processing * at a safe point with a clean app state. */ if (!blocked || sig >= OFFS_RT || (blocked && info->sigpending[sig] == NULL)) { /* only have 1 pending for blocked non-rt signals */ /* to avoid accumulating signals if we're slow in presence of * a high-rate itimer we only keep 2 alarm signals (PR 596768) */ if (sig_is_alarm_signal(sig)) { if (info->sigpending[sig] != NULL && info->sigpending[sig]->next != NULL) { ASSERT(info->sigpending[sig]->next->next == NULL); /* keep the oldest, replace newer w/ brand-new one, for * more spread-out alarms */ sigpending_t *temp = info->sigpending[sig]; info->sigpending[sig] = temp->next; special_heap_free(info->sigheap, temp); info->num_pending--; LOG(THREAD, LOG_ASYNCH, 2, "3rd pending alarm %d => dropping 2nd\n", sig); STATS_INC(num_signals_dropped); SYSLOG_INTERNAL_WARNING_ONCE("dropping 3rd pending alarm signal"); } } /* special heap alloc always uses sizeof(sigpending_t) blocks */ pend = special_heap_alloc(info->sigheap); ASSERT(sig > 0 && sig <= MAX_SIGNUM); info->num_pending++; if (info->num_pending > DYNAMO_OPTION(max_pending_signals) && !info->multiple_pending_units) info->multiple_pending_units = true; if (info->num_pending >= DYNAMO_OPTION(max_pending_signals)) { /* We're at the limit of our special heap: one more and it will try to * allocate a new unit, which is unsafe as it acquires locks. We take * several steps: we notify the user; we check for this on delivery as * well and proactively allocate a new unit in a safer context. * XXX: Perhaps we should drop some signals here? */ DO_ONCE({ char max_string[32]; snprintf(max_string, BUFFER_SIZE_ELEMENTS(max_string), "%d", DYNAMO_OPTION(max_pending_signals)); NULL_TERMINATE_BUFFER(max_string); SYSLOG(SYSLOG_WARNING, MAX_PENDING_SIGNALS, 3, get_application_name(), get_application_pid(), max_string); }); } pend->next = info->sigpending[sig]; info->sigpending[sig] = pend; pend->unblocked = !blocked; /* FIXME: note that for asynchronous signals we don't need to * bother to record exact machine context, even entire frame, * since don't want to pass dynamo pc context to app handler. * only copy frame for synchronous signals? those only * happen while in cache? but for asynch, we would have to * construct our own frame...kind of a pain. */ copy_frame_to_pending(dcontext, sig, frame _IF_CLIENT(access_address)); /* i#1145: check whether we should auto-restart an interrupted syscall */ if (at_auto_restart_syscall) { /* Adjust the pending frame to restart the syscall, if applicable */ sigframe_rt_t *frame = &(info->sigpending[sig]->rt_frame); sigcontext_t *sc_pend = get_sigcontext_from_rt_frame(frame); if (adjust_syscall_for_restart(dcontext, info, sig, sc_pend, f, orig_retval_reg)) { /* We're going to re-start this syscall after we go * back to d_r_dispatch, run the post-syscall handler (for -EINTR), * and deliver the signal. We've adjusted the sigcontext * for re-start on the sigreturn, but we need to tell * execute_handler_from_dispatch() to use our sigcontext * and not the mcontext. * A client will see a second set of pre + post handlers for * the restart, which seems reasonable, given the signal in * between. */ info->sigpending[sig]->use_sigcontext = true; } } } else { /* For clients, we document that we do not pass to them * unless we're prepared to deliver to app. We would have * to change our model to pass them non-final-translated * contexts for delayable signals in order to give them * signals as soon as they come in. Xref i#182/PR 449996. */ LOG(THREAD, LOG_ASYNCH, 3, "\tnon-rt signal already in queue, ignoring this one!\n"); } if (!blocked && !dcontext->signals_pending) dcontext->signals_pending = 1; } ostd->processing_signal--; } /* Distinguish SYS_kill-generated from instruction-generated signals. * If sent from another process we can't tell, but if sent from this * thread the interruption point should be our own post-syscall. * FIXME PR 368277: for other threads in same process we should set a flag * and identify them as well. * FIXME: for faults like SIGILL we could examine the interrupted pc * to see whether it is capable of generating such a fault (see code * used in handle_nudge_signal()). */ static bool is_sys_kill(dcontext_t *dcontext, byte *pc, byte *xsp, kernel_siginfo_t *info) { #if !defined(VMX86_SERVER) && !defined(MACOS) /* does not use SI_KERNEL */ /* i#133: use si_code to distinguish user-sent signals. * Even 2.2 Linux kernel supports <=0 meaning user-sent (except * SIGIO) so we assume we can rely on it. */ if (info->si_code <= 0) return true; #endif return (is_at_do_syscall(dcontext, pc, xsp) && (dcontext->sys_num == SYS_kill || #ifdef LINUX dcontext->sys_num == SYS_tkill || dcontext->sys_num == SYS_tgkill || dcontext->sys_num == SYS_rt_sigqueueinfo #elif defined(MACOS) dcontext->sys_num == SYS___pthread_kill #endif )); } static byte * compute_memory_target(dcontext_t *dcontext, cache_pc instr_cache_pc, kernel_ucontext_t *uc, kernel_siginfo_t *si, bool *write) { sigcontext_t *sc = SIGCXT_FROM_UCXT(uc); byte *target = NULL; instr_t instr; priv_mcontext_t mc; uint memopidx, memoppos, memopsize; opnd_t memop; bool found_target = false; bool in_maps; bool use_allmem = false; uint prot; IF_ARM(dr_isa_mode_t old_mode;) LOG(THREAD, LOG_ALL, 2, "computing memory target for " PFX " causing SIGSEGV, kernel claims it is " PFX "\n", instr_cache_pc, (byte *)si->si_addr); /* ARM's sigcontext_t has a "fault_address" field but it also seems unreliable */ IF_ARM(LOG(THREAD, LOG_ALL, 2, "fault_address: " PFX "\n", sc->fault_address)); /* We used to do a memory query to check if instr_cache_pc is readable, but * now we use TRY/EXCEPT because we don't have the instr length and the OS * query is expensive. If decoding faults, the signal handler will longjmp * out before it calls us recursively. */ instr_init(dcontext, &instr); IF_ARM({ /* Be sure to use the interrupted mode and not the last-dispatch mode */ dr_set_isa_mode(dcontext, get_pc_mode_from_cpsr(sc), &old_mode); }); TRY_EXCEPT(dcontext, { decode(dcontext, instr_cache_pc, &instr); }, { return NULL; /* instr_cache_pc was unreadable */ }); IF_ARM(dr_set_isa_mode(dcontext, old_mode, NULL)); if (!instr_valid(&instr)) { LOG(THREAD, LOG_ALL, 2, "WARNING: got SIGSEGV for invalid instr at cache pc " PFX "\n", instr_cache_pc); ASSERT_NOT_REACHED(); instr_free(dcontext, &instr); return NULL; } ucontext_to_mcontext(&mc, uc); ASSERT(write != NULL); /* i#1009: If si_addr is plausibly one of the memory operands of the * faulting instruction, assume the target was si_addr. If none of the * memops match, fall back to checking page protections, which can be racy. * For si_addr == NULL, we fall back to the protection check because it's * too likely to be a valid memop and we can live with a race on a page that * is typically unmapped. */ if (si->si_code == SEGV_ACCERR && si->si_addr != NULL) { for (memopidx = 0; instr_compute_address_ex_priv(&instr, &mc, memopidx, &target, write, &memoppos); memopidx++) { /* i#1045: check whether operand and si_addr overlap */ memop = *write ? instr_get_dst(&instr, memoppos) : instr_get_src(&instr, memoppos); memopsize = opnd_size_in_bytes(opnd_get_size(memop)); LOG(THREAD, LOG_ALL, 2, "memory operand %u has address " PFX " and size %u\n", memopidx, target, memopsize); if ((byte *)si->si_addr >= target && (byte *)si->si_addr < target + memopsize) { target = (byte *)si->si_addr; found_target = true; break; } } } /* For fcache faults, use all_memory_areas, which is faster but acquires * locks. If it's possible we're in DR, go to the OS to avoid deadlock. */ if (DYNAMO_OPTION(use_all_memory_areas)) { use_allmem = safe_is_in_fcache(dcontext, instr_cache_pc, (byte *)sc->SC_XSP); } if (!found_target) { if (si->si_addr != NULL) { LOG(THREAD, LOG_ALL, 3, "%s: falling back to racy protection checks\n", __FUNCTION__); } /* i#115/PR 394984: consider all memops */ for (memopidx = 0; instr_compute_address_ex_priv(&instr, &mc, memopidx, &target, write, NULL); memopidx++) { if (use_allmem) { in_maps = get_memory_info(target, NULL, NULL, &prot); } else { in_maps = get_memory_info_from_os(target, NULL, NULL, &prot); } if ((!in_maps || !TEST(MEMPROT_READ, prot)) || (*write && !TEST(MEMPROT_WRITE, prot))) { found_target = true; break; } } } if (!found_target) { /* probably an NX fault: how tell whether kernel enforcing? */ in_maps = get_memory_info_from_os(instr_cache_pc, NULL, NULL, &prot); if (!in_maps || !TEST(MEMPROT_EXEC, prot)) { target = instr_cache_pc; found_target = true; } } /* we may still not find target, e.g. for SYS_kill(SIGSEGV) */ if (!found_target) target = NULL; DOLOG(2, LOG_ALL, { LOG(THREAD, LOG_ALL, 2, "For SIGSEGV at cache pc " PFX ", computed target %s " PFX "\n", instr_cache_pc, *write ? "write" : "read", target); d_r_loginst(dcontext, 2, &instr, "\tfaulting instr"); }); instr_free(dcontext, &instr); return target; } /* If native_state is true, assumes the fault is not in the cache and thus * does not need translation but rather should always be re-executed. */ static bool check_for_modified_code(dcontext_t *dcontext, cache_pc instr_cache_pc, kernel_ucontext_t *uc, byte *target, bool native_state) { /* special case: we expect a seg fault for executable regions * that were writable and marked read-only by us. * have to figure out the target address! * unfortunately the OS doesn't tell us, nor whether it's a write. * FIXME: if sent from SYS_kill(SIGSEGV), the pc will be post-syscall, * and if that post-syscall instr is a write that could have faulted, * how can we tell the difference? */ if (was_executable_area_writable(target)) { /* translate instr_cache_pc to original app pc * DO NOT use translate_sigcontext, don't want to change the * signal frame or else we'll lose control when we try to * return to signal pc! */ app_pc next_pc, translated_pc = NULL; fragment_t *f = NULL; fragment_t wrapper; ASSERT((cache_pc)SIGCXT_FROM_UCXT(uc)->SC_XIP == instr_cache_pc); if (!native_state) { /* For safe recreation we need to either be couldbelinking or hold * the initexit lock (to keep someone from flushing current * fragment), the initexit lock is easier */ d_r_mutex_lock(&thread_initexit_lock); /* cache the fragment since pclookup is expensive for coarse units (i#658) */ f = fragment_pclookup(dcontext, instr_cache_pc, &wrapper); translated_pc = recreate_app_pc(dcontext, instr_cache_pc, f); ASSERT(translated_pc != NULL); d_r_mutex_unlock(&thread_initexit_lock); } next_pc = handle_modified_code(dcontext, instr_cache_pc, translated_pc, target, f); if (!native_state) { /* going to exit from middle of fragment (at the write) so will mess up * trace building */ if (is_building_trace(dcontext)) { LOG(THREAD, LOG_ASYNCH, 3, "\tsquashing trace-in-progress\n"); trace_abort(dcontext); } } if (next_pc == NULL) { /* re-execute the write -- just have master_signal_handler return */ return true; } else { ASSERT(!native_state); /* Do not resume execution in cache, go back to d_r_dispatch. */ transfer_from_sig_handler_to_fcache_return( dcontext, uc, NULL, SIGSEGV, next_pc, (linkstub_t *)get_selfmod_linkstub(), false); /* now have master_signal_handler return */ return true; } } return false; } #ifndef HAVE_SIGALTSTACK /* The exact layout of this struct is relied on in master_signal_handler() * in x86.asm. */ struct clone_and_swap_args { byte *stack; byte *tos; }; /* Helper function for swapping handler to dstack */ bool sig_should_swap_stack(struct clone_and_swap_args *args, kernel_ucontext_t *ucxt) { byte *cur_esp; dcontext_t *dcontext = get_thread_private_dcontext(); if (dcontext == NULL) return false; GET_STACK_PTR(cur_esp); if (!is_on_dstack(dcontext, cur_esp)) { sigcontext_t *sc = SIGCXT_FROM_UCXT(ucxt); /* Pass back the proper args to clone_and_swap_stack: we want to * copy to dstack from the tos at the signal interruption point. */ args->stack = dcontext->dstack; /* leave room for fpstate */ args->stack -= signal_frame_extra_size(true); args->stack = (byte *)ALIGN_BACKWARD(args->stack, XSTATE_ALIGNMENT); args->tos = (byte *)sc->SC_XSP; return true; } else return false; } #endif /* Helper that takes over the current thread signaled via SUSPEND_SIGNAL. Kept * separate mostly to keep the priv_mcontext_t allocation out of * master_signal_handler_C. * If it returns, it returns false, and the signal should be squashed. */ static bool sig_take_over(kernel_ucontext_t *uc) { priv_mcontext_t mc; ucontext_to_mcontext(&mc, uc); /* We don't want our own blocked signals: we want the app's, stored in the frame. */ if (!os_thread_take_over(&mc, SIGMASK_FROM_UCXT(uc))) return false; ASSERT_NOT_REACHED(); /* shouldn't return */ return true; /* make compiler happy */ } static bool is_safe_read_ucxt(kernel_ucontext_t *ucxt) { app_pc pc = (app_pc)SIGCXT_FROM_UCXT(ucxt)->SC_XIP; return is_safe_read_pc(pc); } /* the master signal handler * WARNING: behavior varies with different versions of the kernel! * sigaction support was only added with 2.2 */ #ifndef X86_32 /* stub in x86.asm passes our xsp to us */ # ifdef MACOS void master_signal_handler_C(handler_t handler, int style, int sig, kernel_siginfo_t *siginfo, kernel_ucontext_t *ucxt, byte *xsp) # else void master_signal_handler_C(int sig, kernel_siginfo_t *siginfo, kernel_ucontext_t *ucxt, byte *xsp) # endif #else /* On ia32, adding a parameter disturbs the frame we're trying to capture, so we * add an intermediate frame and read the normal params off the stack directly. */ void master_signal_handler_C(byte *xsp) #endif { sigframe_rt_t *frame = (sigframe_rt_t *)xsp; #ifdef X86_32 /* Read the normal arguments from the frame. */ int sig = frame->sig; kernel_siginfo_t *siginfo = frame->pinfo; kernel_ucontext_t *ucxt = frame->puc; #endif /* !X64 */ sigcontext_t *sc = SIGCXT_FROM_UCXT(ucxt); thread_record_t *tr; #ifdef DEBUG uint level = 2; # if !defined(HAVE_MEMINFO) /* avoid logging every single TRY probe fault */ if (!dynamo_initialized) level = 5; # endif #endif bool local; #if defined(MACOS) && !defined(X64) /* The kernel clears fs, so we have to re-instate our selector, if * it was set in the first place. */ if (sc->__ss.__fs != 0) tls_reinstate_selector(sc->__ss.__fs); #endif #ifdef X86 /* i#2089: For is_thread_tls_initialized() we need a safe_read path that does not * do any logging or call get_thread_private_dcontext() as those will recurse. * This path is global so there's no SELF_PROTECT_LOCAL and we also bypass * the ENTERING_DR() for this short path. */ if (sig == SIGSEGV && sc->SC_XIP == (ptr_uint_t)safe_read_tls_magic) { sc->SC_RETURN_REG = 0; sc->SC_XIP = (reg_t)safe_read_tls_magic_recover; return; } else if (sig == SIGSEGV && sc->SC_XIP == (ptr_uint_t)safe_read_tls_self) { sc->SC_RETURN_REG = 0; sc->SC_XIP = (reg_t)safe_read_tls_self_recover; return; } else if (sig == SIGSEGV && sc->SC_XIP == (ptr_uint_t)safe_read_tls_app_self) { sc->SC_RETURN_REG = 0; sc->SC_XIP = (reg_t)safe_read_tls_app_self_recover; return; } #endif /* We are dropping asynchronous signals during detach. The thread may already have * lost its TLS (xref i#3535). A safe read may result in a crash if DR's SIGSEGV * handler is removed before the safe read's SIGSEGV is delivered. * * Note that besides dropping potentially important signals, there is still a small * race window if the signal gets delivered after the detach has finished, i.e. * doing detach is false. This is an issue in particular if the app has started * re-attaching. * * Signals that are not clearly asynchronous may hit corner case(s) of i#3535. * (xref i#26). */ if (doing_detach && can_always_delay[sig]) { DOLOG(1, LOG_ASYNCH, { dump_sigcontext(GLOBAL_DCONTEXT, sc); }); SYSLOG_INTERNAL_ERROR("ERROR: master_signal_handler with unreliable dcontext " "during detach. Signal will be dropped and we're continuing" " (i#3535?): tid=%d, sig=%d", get_sys_thread_id(), sig); return; } dcontext_t *dcontext = get_thread_private_dcontext(); #ifdef MACOS # ifdef X64 ASSERT((YMM_ENABLED() && ucxt->uc_mcsize == sizeof(_STRUCT_MCONTEXT_AVX64)) || (!YMM_ENABLED() && ucxt->uc_mcsize == sizeof(_STRUCT_MCONTEXT64))); # else ASSERT((YMM_ENABLED() && ucxt->uc_mcsize == sizeof(_STRUCT_MCONTEXT_AVX32)) || (!YMM_ENABLED() && ucxt->uc_mcsize == sizeof(_STRUCT_MCONTEXT))); # endif #endif /* i#350: To support safe_read or TRY_EXCEPT without a dcontext, use the * global dcontext * when handling safe_read faults. This lets us pass the check for a * dcontext below and causes us to use the global log. */ if (dcontext == NULL && (sig == SIGSEGV || sig == SIGBUS) && (is_safe_read_ucxt(ucxt) || (!dynamo_initialized && global_try_except.try_except_state != NULL))) { dcontext = GLOBAL_DCONTEXT; } if (dynamo_exited && d_r_get_num_threads() > 1 && sig == SIGSEGV) { /* PR 470957: this is almost certainly a race so just squelch it. * We live w/ the risk that it was holding a lock our release-build * exit code needs. */ exit_thread_syscall(1); } /* FIXME: ensure the path for recording a pending signal does not grab any DR locks * that could have been interrupted * e.g., synchronize_dynamic_options grabs the stats_lock! */ if (sig == SUSPEND_SIGNAL) { if (proc_get_vendor() == VENDOR_AMD) { /* i#3356: Work around an AMD processor bug where it does not clear the * hidden gs base when the gs selector is written. Pre-4.7 Linux kernels * leave the prior thread's base in place on a switch due to this. * We can thus come here and get the wrong dcontext on attach; worse, * we can get NULL here but the wrong one later during init. It's * safest to just set a non-zero value (the kernel ignores zero) for all * unknown threads here. There are no problems for non-attach takeover. */ if (dcontext == NULL || dcontext->owning_thread != get_sys_thread_id()) { /* tls_thread_preinit() further rules out a temp-native dcontext * and avoids clobbering it, to preserve the thread_lookup() case * below (which we do not want to run first as we could swap to * the incorrect dcontext midway through it). */ if (!tls_thread_preinit()) { SYSLOG_INTERNAL_ERROR_ONCE("ERROR: Failed to work around AMD context " "switch bug #3356: crashes or " "hangs may ensue..."); } dcontext = NULL; } } } if (dcontext == NULL && /* Check for a temporarily-native thread we're synch-ing with. */ (sig == SUSPEND_SIGNAL #ifdef X86 || (INTERNAL_OPTION(safe_read_tls_init) && /* Check for whether this is a thread with its invalid sentinel magic set. * In this case, we assume that it is either a thread that is currently * temporarily-native via API like DR_EMIT_GO_NATIVE, or a thread in the * clone window. We know by inspection of our own code that it is safe to * call thread_lookup for either case thread makes a clone or was just * cloned. i.e. thread_lookup requires a lock that must not be held by the * calling thread (i#2921). * XXX: what is ARM doing, any special case w/ dcontext == NULL? */ safe_read_tls_magic() == TLS_MAGIC_INVALID) #endif )) { tr = thread_lookup(get_sys_thread_id()); if (tr != NULL) dcontext = tr->dcontext; } if (dcontext == NULL || (dcontext != GLOBAL_DCONTEXT && (dcontext->signal_field == NULL || !((thread_sig_info_t *)dcontext->signal_field)->fully_initialized))) { /* FIXME: || !intercept_asynch, or maybe !under_our_control */ /* FIXME i#26: this could be a signal arbitrarily sent to this thread. * We could try to route it to another thread, using a global queue * of pending signals. But what if it was targeted to this thread * via SYS_{tgkill,tkill}? Can we tell the difference, even if * we watch the kill syscalls: could come from another process? */ if (sig_is_alarm_signal(sig)) { /* assuming an alarm during thread exit or init (xref PR 596127, * i#359): suppressing is fine */ } else if (sig == SUSPEND_SIGNAL && dcontext == NULL) { /* We sent SUSPEND_SIGNAL to a thread we don't control (no * dcontext), which means we want to take over. */ ASSERT(!doing_detach); if (!sig_take_over(ucxt)) return; ASSERT_NOT_REACHED(); /* else, shouldn't return */ } else { /* Using global dcontext because dcontext is NULL here. */ DOLOG(1, LOG_ASYNCH, { dump_sigcontext(GLOBAL_DCONTEXT, sc); }); SYSLOG_INTERNAL_ERROR("ERROR: master_signal_handler with no siginfo " "(i#26?): tid=%d, sig=%d", get_sys_thread_id(), sig); } /* see FIXME comments above. * workaround for now: suppressing is better than dying. */ if (can_always_delay[sig]) return; REPORT_FATAL_ERROR_AND_EXIT(FAILED_TO_HANDLE_SIGNAL, 2, get_application_name(), get_application_pid()); } /* we may be entering dynamo from code cache! */ /* Note that this is unsafe if -single_thread_in_DR => we grab a lock => * hang if signal interrupts DR: but we don't really support that option */ ENTERING_DR(); if (dcontext == GLOBAL_DCONTEXT) { local = false; tr = thread_lookup(get_sys_thread_id()); } else { tr = dcontext->thread_record; local = local_heap_protected(dcontext); if (local) SELF_PROTECT_LOCAL(dcontext, WRITABLE); } /* i#1921: For proper native execution with re-takeover we need to propagate * signals to app handlers while native. For now we do not support re-takeover * and we give up our handlers via signal_remove_handlers(). */ ASSERT(tr == NULL || tr->under_dynamo_control || IS_CLIENT_THREAD(dcontext) || sig == SUSPEND_SIGNAL); LOG(THREAD, LOG_ASYNCH, level, "\nmaster_signal_handler: thread=%d, sig=%d, xsp=" PFX ", retaddr=" PFX "\n", get_sys_thread_id(), sig, xsp, *((byte **)xsp)); LOG(THREAD, LOG_ASYNCH, level + 1, "siginfo: sig = %d, pid = %d, status = %d, errno = %d, si_code = %d\n", siginfo->si_signo, siginfo->si_pid, siginfo->si_status, siginfo->si_errno, siginfo->si_code); DOLOG(level + 1, LOG_ASYNCH, { dump_sigcontext(dcontext, sc); }); #if defined(X86_32) && !defined(VMX86_SERVER) && defined(LINUX) /* FIXME case 6700: 2.6.9 (FC3) kernel sets up our frame with a pretcode * of 0x440. This happens if our restorer is unspecified (though 2.6.9 * src code shows setting the restorer to a default value in that case...) * or if we explicitly point at dynamorio_sigreturn. I couldn't figure * out why it kept putting 0x440 there. So we fix the issue w/ this * hardcoded return. * This hack causes vmkernel to kill the process on sigreturn due to * vmkernel's non-standard sigreturn semantics. PR 404712. */ *((byte **)xsp) = (byte *)dynamorio_sigreturn; #endif /* N.B.: * ucontext_t is defined in two different places. The one we get * included is /usr/include/sys/ucontext.h, which would have us * doing this: * void *pc = (void *) ucxt->uc_mcontext.gregs[EIP]; * However, EIP is not defined for us (used to be in older * RedHat version) unless we define __USE_GNU, which we don't want to do * for other reasons, so we'd have to also say: * #define EIP 14 * Instead we go by the ucontext_t definition in * /usr/include/asm/ucontext.h, which has it containing a sigcontext struct, * defined in /usr/include/asm/sigcontext.h. This is the definition used * by the kernel. The two definitions are field-for-field * identical except that the sys one has an fpstate struct at the end -- * but the next field in the frame is an fpstate. The only mystery * is why the rt frame is declared as ucontext instead of sigcontext. * The kernel's version of ucontext must be the asm one! * And the sys one grabs the next field of the frame. * Also note that mcontext_t.fpregs == sigcontext.fpstate is NULL if * floating point operations have not been used (lazy fp state saving). * Also, sigset_t has different sizes according to kernel (8 bytes) vs. * glibc (128 bytes?). */ switch (sig) { case SIGBUS: /* PR 313665: look for DR crashes on unaligned memory or mmap bounds */ case SIGSEGV: { /* Older kernels do NOT fill out the signal-specific fields of siginfo, * except for SIGCHLD. Thus we cannot do this: * void *pc = (void*) siginfo->si_addr; * Thus we must use the third argument, which is a ucontext_t (see above) */ void *pc = (void *)sc->SC_XIP; bool syscall_signal = false; /* signal came from syscall? */ bool is_write = false; byte *target; bool is_DR_exception = false; #ifdef SIDELINE if (dcontext == NULL) { SYSLOG_INTERNAL_ERROR("seg fault in sideline thread -- NULL dcontext!"); ASSERT_NOT_REACHED(); } #endif if (is_safe_read_ucxt(ucxt) || (!dynamo_initialized && global_try_except.try_except_state != NULL) || dcontext->try_except.try_except_state != NULL) { /* handle our own TRY/EXCEPT */ try_except_context_t *try_cxt; #ifdef HAVE_MEMINFO /* our probe produces many of these every run */ /* since we use for safe_*, making a _ONCE */ SYSLOG_INTERNAL_WARNING_ONCE("(1+x) Handling our fault in a TRY at " PFX, pc); #endif LOG(THREAD, LOG_ALL, level, "TRY fault at " PFX "\n", pc); if (TEST(DUMPCORE_TRY_EXCEPT, DYNAMO_OPTION(dumpcore_mask))) os_dump_core("try/except fault"); if (is_safe_read_ucxt(ucxt)) { sc->SC_XIP = (reg_t)safe_read_resume_pc(); /* Break out to log the normal return from the signal handler. */ break; } try_cxt = (dcontext != NULL) ? dcontext->try_except.try_except_state : global_try_except.try_except_state; ASSERT(try_cxt != NULL); /* The exception interception code did an ENTER so we must EXIT here */ EXITING_DR(); /* Since we have no sigreturn we have to restore the mask * manually, just like siglongjmp(). i#226/PR 492568: we rely * on the kernel storing the prior mask in ucxt, so we do not * need to store it on every setjmp. */ /* Verify that there's no scenario where the mask gets changed prior * to a fault inside a try. This relies on dr_setjmp_sigmask() filling * in the mask, which we only bother to do in debug build. */ ASSERT(memcmp(&try_cxt->context.sigmask, &ucxt->uc_sigmask, sizeof(ucxt->uc_sigmask)) == 0); sigprocmask_syscall(SIG_SETMASK, SIGMASK_FROM_UCXT(ucxt), NULL, sizeof(ucxt->uc_sigmask)); DR_LONGJMP(&try_cxt->context, LONGJMP_EXCEPTION); ASSERT_NOT_REACHED(); } target = compute_memory_target(dcontext, pc, ucxt, siginfo, &is_write); #ifdef CLIENT_INTERFACE if (CLIENTS_EXIST() && is_in_client_lib(pc)) { /* i#1354: client might write to a page we made read-only. * If so, handle the fault and re-execute it, if it's safe to do so * (we document these criteria under DR_MEMPROT_PRETEND_WRITE). */ if (is_write && !is_couldbelinking(dcontext) && OWN_NO_LOCKS(dcontext) && check_for_modified_code(dcontext, pc, ucxt, target, true /*native*/)) break; abort_on_fault(dcontext, DUMPCORE_CLIENT_EXCEPTION, pc, target, sig, frame, exception_label_client, (sig == SIGSEGV) ? "SEGV" : "BUS", " client library"); ASSERT_NOT_REACHED(); } #endif /* For !HAVE_MEMINFO, we cannot compute the target until * after the try/except check b/c compute_memory_target() * calls get_memory_info_from_os() which does a probe: and the * try/except could be from a probe itself. A try/except that * triggers a stack overflow should recover on the longjmp, so * this order should be fine. */ /* FIXME: share code with Windows callback.c */ /* FIXME PR 205795: in_fcache and is_dynamo_address do grab locks! */ if ((is_on_dstack(dcontext, (byte *)sc->SC_XSP) /* PR 302951: clean call arg processing => pass to app/client. * Rather than call the risky in_fcache we check whereami. */ IF_CLIENT_INTERFACE(&&(dcontext->whereami != DR_WHERE_FCACHE))) || is_on_alt_stack(dcontext, (byte *)sc->SC_XSP) || is_on_initstack((byte *)sc->SC_XSP)) { /* Checks here need to cover everything that record_pending_signal() * thinks is non-fcache, non-gencode: else that routine will kill * process since can't delay or re-execute (i#195/PR 453964). */ is_DR_exception = true; } else if (!safe_is_in_fcache(dcontext, pc, (byte *)sc->SC_XSP) && (in_generated_routine(dcontext, pc) || is_at_do_syscall(dcontext, pc, (byte *)sc->SC_XSP) || is_dynamo_address(pc))) { #ifdef CLIENT_INTERFACE if (!in_generated_routine(dcontext, pc) && !is_at_do_syscall(dcontext, pc, (byte *)sc->SC_XSP)) { /* PR 451074: client needs a chance to handle exceptions in its * own gencode. client_exception_event() won't return if client * wants to re-execute faulting instr. */ sigcontext_t sc_interrupted = *get_sigcontext_from_rt_frame(frame); dr_signal_action_t action = send_signal_to_client( dcontext, sig, frame, sc, target, false /*!blocked*/, NULL); if (action != DR_SIGNAL_DELIVER && /* for delivery, continue below */ !handle_client_action_from_cache(dcontext, sig, action, frame, sc, &sc_interrupted, false /*!blocked*/)) { /* client handled fault */ break; } } #endif is_DR_exception = true; } if (is_DR_exception) { /* kill(getpid(), SIGSEGV) looks just like a SIGSEGV in the store of eax * to mcontext after the syscall instr in do_syscall -- try to distinguish: */ if (is_sys_kill(dcontext, pc, (byte *)sc->SC_XSP, siginfo)) { LOG(THREAD, LOG_ALL, 2, "assuming SIGSEGV at post-do-syscall is kill, not our write fault\n"); syscall_signal = true; } if (!syscall_signal) { if (check_in_last_thread_vm_area(dcontext, target)) { /* See comments in callback.c as well. * FIXME: try to share code */ SYSLOG_INTERNAL_WARNING("(decode) exception in last area, " "DR pc=" PFX ", app pc=" PFX, pc, target); STATS_INC(num_exceptions_decode); if (is_building_trace(dcontext)) { LOG(THREAD, LOG_ASYNCH, 2, "intercept_exception: " "squashing old trace\n"); trace_abort(dcontext); } /* we do get faults when not building a bb: e.g., * ret_after_call_check does decoding (case 9396) */ if (dcontext->bb_build_info != NULL) { /* must have been building a bb at the time */ bb_build_abort(dcontext, true /*clean vm area*/, true /*unlock*/); } /* Since we have no sigreturn we have to restore the mask manually */ unblock_all_signals(NULL); /* Let's pass it back to the application - memory is unreadable */ if (TEST(DUMPCORE_FORGE_UNREAD_EXEC, DYNAMO_OPTION(dumpcore_mask))) os_dump_core("Warning: Racy app execution (decode unreadable)"); os_forge_exception(target, UNREADABLE_MEMORY_EXECUTION_EXCEPTION); ASSERT_NOT_REACHED(); } else { abort_on_DR_fault(dcontext, pc, target, sig, frame, (sig == SIGSEGV) ? "SEGV" : "BUS", in_generated_routine(dcontext, pc) ? " generated" : ""); } } } /* if get here, pass the signal to the app */ ASSERT(pc != 0); /* shouldn't get here */ if (sig == SIGSEGV && !syscall_signal /*only for in-cache signals*/) { /* special case: we expect a seg fault for executable regions * that were writable and marked read-only by us. */ if (is_write && check_for_modified_code(dcontext, pc, ucxt, target, false /*!native*/)) { /* it was our signal, so don't pass to app -- return now */ break; } } /* pass it to the application (or client) */ LOG(THREAD, LOG_ALL, 1, "** Received SIG%s at cache pc " PFX " in thread " TIDFMT "\n", (sig == SIGSEGV) ? "SEGV" : "BUS", pc, d_r_get_thread_id()); ASSERT(syscall_signal || safe_is_in_fcache(dcontext, pc, (byte *)sc->SC_XSP)); /* we do not call trace_abort() here since we may need to * translate from a temp private bb (i#376): but all paths * that deliver the signal or redirect will call it */ record_pending_signal(dcontext, sig, ucxt, frame, false _IF_CLIENT(target)); break; } /* PR 212090: the signal we use to suspend threads */ case SUSPEND_SIGNAL: if (handle_suspend_signal(dcontext, ucxt, frame)) { /* i#1921: see comment above */ ASSERT(tr == NULL || tr->under_dynamo_control || IS_CLIENT_THREAD(dcontext)); record_pending_signal(dcontext, sig, ucxt, frame, false _IF_CLIENT(NULL)); } /* else, don't deliver to app */ break; /* i#61/PR 211530: the signal we use for nudges */ case NUDGESIG_SIGNUM: if (handle_nudge_signal(dcontext, siginfo, ucxt)) record_pending_signal(dcontext, sig, ucxt, frame, false _IF_CLIENT(NULL)); /* else, don't deliver to app */ break; case SIGALRM: case SIGVTALRM: case SIGPROF: if (handle_alarm(dcontext, sig, ucxt)) record_pending_signal(dcontext, sig, ucxt, frame, false _IF_CLIENT(NULL)); /* else, don't deliver to app */ break; #ifdef SIDELINE case SIGCHLD: { int status = siginfo->si_status; if (siginfo->si_pid == 0) { /* FIXME: with older versions of linux the sigchld fields of * siginfo are not filled in properly! * This is my attempt to handle that, pid seems to be 0 */ break; } if (status != 0) { LOG(THREAD, LOG_ALL, 0, "*** Child thread died with error %d\n", status); ASSERT_NOT_REACHED(); } break; } #endif default: { record_pending_signal(dcontext, sig, ucxt, frame, false _IF_CLIENT(NULL)); break; } } /* end switch */ LOG(THREAD, LOG_ASYNCH, level, "\tmaster_signal_handler %d returning now to " PFX "\n\n", sig, sc->SC_XIP); /* Ensure we didn't get the app's sigstack into our frame. On Mac, the kernel * doesn't use the frame's uc_stack, so we limit this to Linux. * The pointers may be different if a thread is on its way to exit, and the app's * sigstack was already restored (i#3369). */ IF_LINUX(ASSERT(dcontext == NULL || dcontext == GLOBAL_DCONTEXT || dcontext->is_exiting || frame->uc.uc_stack.ss_sp == ((thread_sig_info_t *)dcontext->signal_field)->sigstack.ss_sp)); /* restore protections */ if (local) SELF_PROTECT_LOCAL(dcontext, READONLY); EXITING_DR(); } static bool execute_handler_from_cache(dcontext_t *dcontext, int sig, sigframe_rt_t *our_frame, sigcontext_t *sc_orig, fragment_t *f _IF_CLIENT(byte *access_address)) { thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field; /* we want to modify the sc in DR's frame */ kernel_ucontext_t *uc = get_ucontext_from_rt_frame(our_frame); sigcontext_t *sc = SIGCXT_FROM_UCXT(uc); kernel_sigset_t blocked; /* Need to get xsp now before get new dcontext. * This is the translated xsp, so we avoid PR 306410 (cleancall arg fault * on dstack => handler run on dstack) that Windows hit. */ byte *xsp = get_sigstack_frame_ptr(dcontext, sig, our_frame/* take xsp from (translated) * interruption point */); #ifdef CLIENT_INTERFACE sigcontext_t sc_interrupted = *sc; dr_signal_action_t action = send_signal_to_client( dcontext, sig, our_frame, sc_orig, access_address, false /*not blocked*/, f); if (!handle_client_action_from_cache(dcontext, sig, action, our_frame, sc_orig, &sc_interrupted, false /*!blocked*/)) return false; #else if (info->app_sigaction[sig] == NULL || info->app_sigaction[sig]->handler == (handler_t)SIG_DFL) { LOG(THREAD, LOG_ASYNCH, 3, "\taction is SIG_DFL\n"); if (execute_default_from_cache(dcontext, sig, our_frame, sc_orig, false)) { /* if we haven't terminated, restore original (untranslated) sc * on request. * XXX i#1615: this doesn't restore SIMD regs, if client translated them! */ *get_sigcontext_from_rt_frame(our_frame) = *sc_orig; } return false; } ASSERT(info->app_sigaction[sig] != NULL && info->app_sigaction[sig]->handler != (handler_t)SIG_IGN && info->app_sigaction[sig]->handler != (handler_t)SIG_DFL); #endif LOG(THREAD, LOG_ASYNCH, 2, "execute_handler_from_cache for signal %d\n", sig); RSTATS_INC(num_signals); /* now that we know it's not a client-involved fault, dump as app fault */ report_app_problem(dcontext, APPFAULT_FAULT, (byte *)sc->SC_XIP, (byte *)sc->SC_FP, "\nSignal %d delivered to application handler.\n", sig); LOG(THREAD, LOG_ASYNCH, 3, "\txsp is " PFX "\n", xsp); /* copy frame to appropriate stack and convert to non-rt if necessary */ copy_frame_to_stack(dcontext, sig, our_frame, (void *)xsp, false /*!pending*/); LOG(THREAD, LOG_ASYNCH, 3, "\tcopied frame from " PFX " to " PFX "\n", our_frame, xsp); sigcontext_t *app_sc = get_sigcontext_from_app_frame(info, sig, (void *)xsp); /* Because of difficulties determining when/if a signal handler * returns, we do what the kernel does: abandon all of our current * state, copy what we might need to the handler frame if we come back, * and then it's ok if the handler doesn't return. * If it does, we start interpreting afresh when we see sigreturn(). * This routine assumes anything needed to return has been put in the * frame (only needed for signals queued up while in dynamo), and goes * ahead and trashes the current dcontext. */ /* if we were building a trace, kill it */ if (is_building_trace(dcontext)) { LOG(THREAD, LOG_ASYNCH, 3, "\tsquashing trace-in-progress\n"); trace_abort(dcontext); } /* add to set of blocked signals those in sigaction mask */ blocked = info->app_sigaction[sig]->mask; /* SA_NOMASK says whether to block sig itself or not */ if ((info->app_sigaction[sig]->flags & SA_NOMASK) == 0) kernel_sigaddset(&blocked, sig); set_blocked(dcontext, &blocked, false /*relative: OR these in*/); /* Doesn't matter what most app registers are, signal handler doesn't * expect anything except the frame on the stack. We do need to set xsp, * only because if app wants special signal stack we need to point xsp * there. (If no special signal stack, this is a nop.) */ sc->SC_XSP = (ptr_uint_t)xsp; /* Set up args to handler: int sig, kernel_siginfo_t *siginfo, * kernel_ucontext_t *ucxt. */ #ifdef X86_64 sc->SC_XDI = sig; sc->SC_XSI = (reg_t) & ((sigframe_rt_t *)xsp)->info; sc->SC_XDX = (reg_t) & ((sigframe_rt_t *)xsp)->uc; #elif defined(AARCHXX) sc->SC_R0 = sig; if (IS_RT_FOR_APP(info, sig)) { sc->SC_R1 = (reg_t) & ((sigframe_rt_t *)xsp)->info; sc->SC_R2 = (reg_t) & ((sigframe_rt_t *)xsp)->uc; } if (sig_has_restorer(info, sig)) sc->SC_LR = (reg_t)info->app_sigaction[sig]->restorer; else sc->SC_LR = (reg_t)dynamorio_sigreturn; # ifndef AARCH64 /* We're going to our fcache_return gencode which uses DEFAULT_ISA_MODE */ set_pc_mode_in_cpsr(sc, DEFAULT_ISA_MODE); # endif #endif /* Set our sigreturn context (NOT for the app: we already copied the * translated context to the app stack) to point to fcache_return! * Then we'll go back through kernel, appear in fcache_return, * and go through d_r_dispatch & interp, without messing up DR stack. */ transfer_from_sig_handler_to_fcache_return( dcontext, uc, app_sc, sig, /* Make sure handler is next thing we execute */ (app_pc)SIGACT_PRIMARY_HANDLER(info->app_sigaction[sig]), (linkstub_t *)get_asynch_linkstub(), true); if ((info->app_sigaction[sig]->flags & SA_ONESHOT) != 0) { /* clear handler now -- can't delete memory since sigreturn, * others may look at sigaction struct, so we just set to default */ info->app_sigaction[sig]->handler = (handler_t)SIG_DFL; } LOG(THREAD, LOG_ASYNCH, 3, "\tset next_tag to handler " PFX ", xsp to " PFX "\n", SIGACT_PRIMARY_HANDLER(info->app_sigaction[sig]), xsp); return true; } static bool execute_handler_from_dispatch(dcontext_t *dcontext, int sig) { thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field; byte *xsp = get_sigstack_frame_ptr(dcontext, sig, NULL); sigframe_rt_t *frame = &(info->sigpending[sig]->rt_frame); priv_mcontext_t *mcontext = get_mcontext(dcontext); sigcontext_t *sc; kernel_ucontext_t *uc; kernel_sigset_t blocked; #ifdef CLIENT_INTERFACE dr_signal_action_t action; #else if (info->app_sigaction[sig] == NULL || info->app_sigaction[sig]->handler == (handler_t)SIG_DFL) { LOG(THREAD, LOG_ASYNCH, 3, "\taction is SIG_DFL\n"); execute_default_from_dispatch(dcontext, sig, frame); return true; } ASSERT(info->app_sigaction[sig] != NULL && info->app_sigaction[sig]->handler != (handler_t)SIG_IGN && info->app_sigaction[sig]->handler != (handler_t)SIG_DFL); #endif LOG(THREAD, LOG_ASYNCH, 2, "execute_handler_from_dispatch for signal %d\n", sig); RSTATS_INC(num_signals); /* modify the rtframe before copying to stack so we can pass final * version to client, and propagate its mods */ uc = get_ucontext_from_rt_frame(frame); sc = SIGCXT_FROM_UCXT(uc); /* Because of difficulties determining when/if a signal handler * returns, we do what the kernel does: abandon all of our current * state, copy what we might need to the handler frame if we come back, * and then it's ok if the handler doesn't return. * If it does, we start interpreting afresh when we see sigreturn(). */ #ifdef DEBUG if (d_r_stats->loglevel >= 3 && (d_r_stats->logmask & LOG_ASYNCH) != 0) { LOG(THREAD, LOG_ASYNCH, 3, "original sigcontext " PFX ":\n", sc); dump_sigcontext(dcontext, sc); } #endif if (info->sigpending[sig]->use_sigcontext) { LOG(THREAD, LOG_ASYNCH, 2, "%s: using sigcontext, not mcontext (syscall restart)\n", __FUNCTION__); } else { /* copy currently-interrupted-context to frame's context, so we can * abandon the currently-interrupted context. */ mcontext_to_ucontext(uc, mcontext); } /* Sigreturn needs the target ISA mode to be set in the T bit in cpsr. * Since we came from d_r_dispatch, the post-signal target's mode is in dcontext. */ IF_ARM(set_pc_mode_in_cpsr(sc, dr_get_isa_mode(dcontext))); /* mcontext does not contain fp or mmx or xmm state, which may have * changed since the frame was created (while finishing up interrupted * fragment prior to returning to d_r_dispatch). Since DR does not touch * this state except for xmm on x64, we go ahead and copy the * current state into the frame, and then touch up xmm for x64. */ /* FIXME: should this be done for all pending as soon as reach * d_r_dispatch? what if get two asynch inside same frag prior to exiting * cache? have issues with fpstate, but also prob with next_tag? FIXME */ /* FIXME: we should clear fpstate for app handler itself as that's * how our own handler is executed. */ #if defined(LINUX) && defined(X86) ASSERT(sc->fpstate != NULL); /* not doing i#641 yet */ save_fpstate(dcontext, frame); #endif /* LINUX && X86 */ #ifdef DEBUG if (d_r_stats->loglevel >= 3 && (d_r_stats->logmask & LOG_ASYNCH) != 0) { LOG(THREAD, LOG_ASYNCH, 3, "new sigcontext " PFX ":\n", sc); dump_sigcontext(dcontext, sc); LOG(THREAD, LOG_ASYNCH, 3, "\n"); } #endif /* FIXME: other state? debug regs? * if no syscall allowed between master_ (when frame created) and * receiving, then don't have to worry about debug regs, etc. * check for syscall when record pending, if it exists, try to * receive in pre_system_call or something? what if ignorable? FIXME! */ if (!info->sigpending[sig]->use_sigcontext) { /* for the pc we want the app pc not the cache pc */ sc->SC_XIP = (ptr_uint_t)dcontext->next_tag; LOG(THREAD, LOG_ASYNCH, 3, "\tset frame's eip to " PFX "\n", sc->SC_XIP); } #ifdef CLIENT_INTERFACE sigcontext_t sc_interrupted = *sc; action = send_signal_to_client(dcontext, sig, frame, NULL, info->sigpending[sig]->access_address, false /*not blocked*/, NULL); /* in order to pass to the client, we come all the way here for signals * the app has no handler for */ if (action == DR_SIGNAL_REDIRECT) { /* send_signal_to_client copied mcontext into frame's sc */ priv_mcontext_t *mcontext = get_mcontext(dcontext); ucontext_to_mcontext(mcontext, uc); dcontext->next_tag = canonicalize_pc_target(dcontext, (app_pc)sc->SC_XIP); if (is_building_trace(dcontext)) { LOG(THREAD, LOG_ASYNCH, 3, "\tsquashing trace-in-progress\n"); trace_abort(dcontext); } IF_ARM(dr_set_isa_mode(dcontext, get_pc_mode_from_cpsr(sc), NULL)); mcontext->pc = dcontext->next_tag; sig_full_cxt_t sc_interrupted_full = { &sc_interrupted, NULL /*not provided*/ }; if (instrument_kernel_xfer(dcontext, DR_XFER_CLIENT_REDIRECT, sc_interrupted_full, NULL, NULL, dcontext->next_tag, mcontext->xsp, osc_empty, mcontext, sig)) dcontext->next_tag = canonicalize_pc_target(dcontext, mcontext->pc); return true; /* don't try another signal */ } else if (action == DR_SIGNAL_SUPPRESS || (info->app_sigaction[sig] != NULL && info->app_sigaction[sig]->handler == (handler_t)SIG_IGN)) { LOG(THREAD, LOG_ASYNCH, 2, "%s: not delivering!\n", (action == DR_SIGNAL_SUPPRESS) ? "client suppressing signal" : "app signal handler is SIG_IGN"); return false; } else if (action == DR_SIGNAL_BYPASS || (info->app_sigaction[sig] == NULL || info->app_sigaction[sig]->handler == (handler_t)SIG_DFL)) { LOG(THREAD, LOG_ASYNCH, 2, "%s: executing default action\n", (action == DR_SIGNAL_BYPASS) ? "client forcing default" : "app signal handler is SIG_DFL"); if (info->sigpending[sig]->use_sigcontext) { /* after the default action we want to go to the sigcontext */ dcontext->next_tag = canonicalize_pc_target(dcontext, (app_pc)sc->SC_XIP); ucontext_to_mcontext(get_mcontext(dcontext), uc); IF_ARM(dr_set_isa_mode(dcontext, get_pc_mode_from_cpsr(sc), NULL)); } execute_default_from_dispatch(dcontext, sig, frame); return true; } CLIENT_ASSERT(action == DR_SIGNAL_DELIVER, "invalid signal event return value"); #endif /* now that we've made all our changes and given the client a * chance to make changes, copy the frame to the appropriate stack * location and convert to non-rt if necessary */ copy_frame_to_stack(dcontext, sig, frame, xsp, true /*pending*/); /* now point at the app's frame */ sc = get_sigcontext_from_app_frame(info, sig, (void *)xsp); ASSERT(info->app_sigaction[sig] != NULL); /* add to set of blocked signals those in sigaction mask */ blocked = info->app_sigaction[sig]->mask; /* SA_NOMASK says whether to block sig itself or not */ if ((info->app_sigaction[sig]->flags & SA_NOMASK) == 0) kernel_sigaddset(&blocked, sig); set_blocked(dcontext, &blocked, false /*relative: OR these in*/); /* if we were building a trace, kill it */ if (is_building_trace(dcontext)) { LOG(THREAD, LOG_ASYNCH, 3, "\tsquashing trace-in-progress\n"); trace_abort(dcontext); } /* Doesn't matter what most app registers are, signal handler doesn't * expect anything except the frame on the stack. We do need to set xsp. */ mcontext->xsp = (ptr_uint_t)xsp; /* Set up args to handler: int sig, kernel_siginfo_t *siginfo, * kernel_ucontext_t *ucxt. */ #ifdef X86_64 mcontext->xdi = sig; mcontext->xsi = (reg_t) & ((sigframe_rt_t *)xsp)->info; mcontext->xdx = (reg_t) & ((sigframe_rt_t *)xsp)->uc; #elif defined(AARCHXX) mcontext->r0 = sig; if (IS_RT_FOR_APP(info, sig)) { mcontext->r1 = (reg_t) & ((sigframe_rt_t *)xsp)->info; mcontext->r2 = (reg_t) & ((sigframe_rt_t *)xsp)->uc; } if (sig_has_restorer(info, sig)) mcontext->lr = (reg_t)info->app_sigaction[sig]->restorer; else mcontext->lr = (reg_t)dynamorio_sigreturn; #endif #ifdef X86 /* Clear eflags DF (signal handler should match function entry ABI) */ mcontext->xflags &= ~EFLAGS_DF; #endif /* Make sure handler is next thing we execute */ dcontext->next_tag = canonicalize_pc_target( dcontext, (app_pc)SIGACT_PRIMARY_HANDLER(info->app_sigaction[sig])); if ((info->app_sigaction[sig]->flags & SA_ONESHOT) != 0) { /* clear handler now -- can't delete memory since sigreturn, * others may look at sigaction struct, so we just set to default */ info->app_sigaction[sig]->handler = (handler_t)SIG_DFL; } #ifdef CLIENT_INTERFACE mcontext->pc = dcontext->next_tag; sig_full_cxt_t sc_full = { sc, NULL /*not provided*/ }; if (instrument_kernel_xfer(dcontext, DR_XFER_SIGNAL_DELIVERY, sc_full, NULL, NULL, dcontext->next_tag, mcontext->xsp, osc_empty, mcontext, sig)) dcontext->next_tag = canonicalize_pc_target(dcontext, mcontext->pc); #endif LOG(THREAD, LOG_ASYNCH, 3, "\tset xsp to " PFX "\n", xsp); return true; } /* The arg to SYS_kill, i.e., the signal number, should be in dcontext->sys_param0 */ /* This routine unblocks signals, but the caller must set the handler to default. */ static void terminate_via_kill(dcontext_t *dcontext) { thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field; ASSERT(dcontext == get_thread_private_dcontext()); /* Enure signal_thread_exit() will not re-block */ memset(&info->app_sigblocked, 0, sizeof(info->app_sigblocked)); /* FIXME PR 541760: there can be multiple thread groups and thus * this may not exit all threads in the address space */ block_cleanup_and_terminate( dcontext, SYS_kill, /* Pass -pid in case main thread has exited * in which case will get -ESRCH */ IF_VMX86(os_in_vmkernel_userworld() ? -(int)get_process_id() :) get_process_id(), dcontext->sys_param0, true, 0, 0); ASSERT_NOT_REACHED(); } bool is_currently_on_sigaltstack(dcontext_t *dcontext) { thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field; byte *cur_esp; GET_STACK_PTR(cur_esp); return (cur_esp >= (byte *)info->sigstack.ss_sp && cur_esp < (byte *)info->sigstack.ss_sp + info->sigstack.ss_size); } static void terminate_via_kill_from_anywhere(dcontext_t *dcontext, int sig) { dcontext->sys_param0 = sig; /* store arg to SYS_kill */ if (is_currently_on_sigaltstack(dcontext)) { /* We can't clean up our sigstack properly when we're on it * (i#1160) so we terminate on the dstack. */ call_switch_stack(dcontext, dcontext->dstack, (void (*)(void *))terminate_via_kill, NULL /*!d_r_initstack */, false /*no return */); } else { terminate_via_kill(dcontext); } ASSERT_NOT_REACHED(); } /* xref os_request_fatal_coredump() */ void os_terminate_via_signal(dcontext_t *dcontext, terminate_flags_t flags, int sig) { if (signal_is_interceptable(sig)) { bool set_action = false; #if defined(STATIC_LIBRARY) && defined(LINUX) if (INTERNAL_OPTION(invoke_app_on_crash)) { /* We come here for asserts. Faults already bypass this routine. */ dcontext_t *my_dc = get_thread_private_dcontext(); if (my_dc != NULL) { thread_sig_info_t *info = (thread_sig_info_t *)my_dc->signal_field; if (info != NULL && info->app_sigaction[sig] != NULL && IS_RT_FOR_APP(info, sig)) { set_action = true; sigaction_syscall(sig, info->app_sigaction[sig], NULL); } } } #endif if (!set_action) { DEBUG_DECLARE(bool res =) set_default_signal_action(sig); ASSERT(res); } } if (TEST(TERMINATE_CLEANUP, flags)) { /* we enter from several different places, so rewind until top-level kstat */ KSTOP_REWIND_UNTIL(thread_measured); ASSERT(dcontext != NULL); dcontext->sys_param0 = sig; /* XXX: the comment in the else below implies some systems have SYS_kill * of SIGSEGV w/ no handler on oneself actually return. * cleanup_and_terminate won't return to us and will use global_do_syscall * to invoke SYS_kill, which in debug will do an inf loop (good!) but * in release will do SYS_exit_group -- oh well, the systems I'm testing * on do an immediate exit. */ terminate_via_kill_from_anywhere(dcontext, sig); } else { /* general clean up is unsafe: just remove .1config file */ d_r_config_exit(); dynamorio_syscall(SYS_kill, 2, get_process_id(), sig); /* We try both the SYS_kill and the immediate crash since on some platforms * the SIGKILL is delayed and on others the *-1 is hanging(?): should investigate */ if (sig == SIGSEGV) /* make doubly-sure */ *((int *)PTR_UINT_MINUS_1) = 0; while (true) { /* in case signal delivery is delayed we wait...forever */ os_thread_yield(); } } ASSERT_NOT_REACHED(); } static bool execute_default_action(dcontext_t *dcontext, int sig, sigframe_rt_t *frame, sigcontext_t *sc_orig, bool from_dispatch, bool forged) { thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field; sigcontext_t *sc = get_sigcontext_from_rt_frame(frame); byte *pc = (byte *)sc->SC_XIP; LOG(THREAD, LOG_ASYNCH, 3, "execute_default_action for signal %d\n", sig); /* should only come here for signals we catch, or signal with ONESHOT * that didn't sigreturn */ ASSERT(info->we_intercept[sig] || (info->app_sigaction[sig]->flags & SA_ONESHOT) != 0); if (info->app_sigaction[sig] != NULL && (info->app_sigaction[sig]->flags & SA_ONESHOT) != 0) { if (!info->we_intercept[sig]) { handler_free(dcontext, info->app_sigaction[sig], sizeof(kernel_sigaction_t)); info->app_sigaction[sig] = NULL; } } /* FIXME PR 205310: we can't always perfectly emulate the default * behavior. To execute the default action, we have to un-register our * handler, if we have one, for signals whose default action is not * ignore or that will just be re-raised upon returning to the * interrupted context -- FIXME: are any of the ignores repeated? * SIGURG? * * If called from execute_handler_from_cache(), our master_signal_handler() * is going to return directly to the translated context: which means we * go native to re-execute the instr, which if it does in fact generate * the signal again means we have a nice transparent core dump. * * If called from execute_handler_from_dispatch(), we need to generate * the signal ourselves. */ if (default_action[sig] != DEFAULT_IGNORE) { DEBUG_DECLARE(bool ok =) set_default_signal_action(sig); ASSERT(ok); /* FIXME: to avoid races w/ shared handlers should set a flag to * prevent another thread from re-enabling. * Perhaps worse: what if this signal arrives for another thread * in the meantime (and the default is not terminate)? */ if (info->shared_app_sigaction) { LOG(THREAD, LOG_ASYNCH, 1, "WARNING: having to install SIG_DFL for thread " TIDFMT ", but will be " "shared!\n", d_r_get_thread_id()); } if (default_action[sig] == DEFAULT_TERMINATE || default_action[sig] == DEFAULT_TERMINATE_CORE) { report_app_problem(dcontext, APPFAULT_CRASH, pc, (byte *)sc->SC_FP, "\nSignal %d delivered to application as default " "action.\n", sig); /* App may call sigaction to set handler SIG_DFL (unnecessary but legal), * in which case DR will put a handler in info->app_sigaction[sig]. * We must clear it, otherwise, signal_thread_exit may cleanup the * handler and set it to SIG_IGN instead. */ if (info->app_sigaction[sig] != NULL) { ASSERT(info->we_intercept[sig]); handler_free(dcontext, info->app_sigaction[sig], sizeof(kernel_sigaction_t)); info->app_sigaction[sig] = NULL; } /* N.B.: we don't have to restore our handler because the * default action is for the process (entire thread group for NPTL) to die! */ if (from_dispatch || can_always_delay[sig] || forged || is_sys_kill(dcontext, pc, (byte *)sc->SC_XSP, &frame->info)) { /* This must have come from SYS_kill rather than raised by * a faulting instruction. Thus we can't go re-execute the * instr in order to re-raise the signal (if from_dispatch, * we delayed and can't re-execute anyway). Instead we * re-generate via SYS_kill. An alternative, if we don't * care about generating a core dump, is to use SYS_exit * and pass the right exit code to indicate the signal * number: that would avoid races w/ the sigaction. * * FIXME: should have app make the syscall to get a more * transparent core dump! */ LOG(THREAD, LOG_ASYNCH, 1, "Terminating via kill\n"); if (!from_dispatch && !forged) KSTOP_NOT_MATCHING_NOT_PROPAGATED(fcache_default); KSTOP_NOT_MATCHING_NOT_PROPAGATED(dispatch_num_exits); if (is_couldbelinking(dcontext)) /* won't be for SYS_kill (i#1159) */ enter_nolinking(dcontext, NULL, false); /* we could be on sigstack so call this version: */ terminate_via_kill_from_anywhere(dcontext, sig); ASSERT_NOT_REACHED(); } else { /* We assume that re-executing the interrupted instr will * re-raise the fault. We could easily be wrong: * xref PR 363811 infinite loop due to memory we * thought was unreadable and thus thought would raise * a signal; xref PR 368277 to improve is_sys_kill(), and the * "forged" parameter that puts us in the if() above. * FIXME PR 205310: we should check whether we come out of * the cache when we expected to terminate! * * An alternative is to abandon transparent core dumps and * do the same explicit SYS_kill we do for from_dispatch. * That would let us clean up DR as well. * FIXME: currently we do not clean up DR for a synchronous * signal death, but we do for asynch. */ /* i#552: cleanup and raise client exit event */ int instr_sz = 0; thread_sig_info_t *info; /* We are on the sigstack now, so assign it to NULL to avoid being * freed during process exit cleanup */ info = (thread_sig_info_t *)dcontext->signal_field; info->sigstack.ss_sp = NULL; /* We enter from several different places, so rewind until * top-level kstat. */ KSTOP_REWIND_UNTIL(thread_measured); /* We try to raise the same signal in app's context so a correct * coredump can be generated. However, the client might change * the code in a way that the corresponding app code won't * raise the signal, so we first check if the app instr is the * same as instr in the cache, and raise the signal (by return). * Otherwise, we kill the process instead. * XXX: if the PC is unreadable we'll just crash here...should check * for readability safely. */ ASSERT(sc_orig != NULL); instr_sz = decode_sizeof(dcontext, (byte *)sc_orig->SC_XIP, NULL _IF_X86_64(NULL)); if (instr_sz != 0 && pc != NULL && /* avoid crash on xl8 failure (i#1699) */ instr_sz == decode_sizeof(dcontext, pc, NULL _IF_X86_64(NULL)) && memcmp(pc, (byte *)sc_orig->SC_XIP, instr_sz) == 0) { /* the app instr matches the cache instr; cleanup and raise the * the signal in the app context */ LOG(THREAD, LOG_ASYNCH, 1, "Raising signal by re-executing\n"); dynamo_process_exit(); /* we cannot re-enter the cache, which is freed by now */ ASSERT(!from_dispatch); return false; } else { /* mismatch, cleanup and terminate */ LOG(THREAD, LOG_ASYNCH, 1, "Terminating via kill\n"); dcontext->sys_param0 = sig; terminate_via_kill(dcontext); ASSERT_NOT_REACHED(); } } } else { /* FIXME PR 297033: in order to intercept DEFAULT_STOP / * DEFAULT_CONTINUE signals, we need to set sigcontext to point * to some kind of regain-control routine, so that when our * thread gets to run again we can reset our handler. So far * we have no signals that fall here that we intercept. */ CLIENT_ASSERT(false, "STOP/CONT signals not supported"); } #if defined(DEBUG) && defined(INTERNAL) if (sig == SIGSEGV && !dynamo_exited) { /* pc should be an app pc at this point (it was translated) -- * check for bad cases here */ if (safe_is_in_fcache(dcontext, pc, (byte *)sc->SC_XSP)) { fragment_t wrapper; fragment_t *f; LOG(THREAD, LOG_ALL, 1, "Received SIGSEGV at pc " PFX " in thread " TIDFMT "\n", pc, d_r_get_thread_id()); f = fragment_pclookup(dcontext, pc, &wrapper); if (f) disassemble_fragment(dcontext, f, false); ASSERT_NOT_REACHED(); } else if (in_generated_routine(dcontext, pc)) { LOG(THREAD, LOG_ALL, 1, "Received SIGSEGV at generated non-code-cache pc " PFX "\n", pc); ASSERT_NOT_REACHED(); } } #endif } /* now continue at the interruption point and re-raise the signal */ return true; } static bool execute_default_from_cache(dcontext_t *dcontext, int sig, sigframe_rt_t *frame, sigcontext_t *sc_orig, bool forged) { return execute_default_action(dcontext, sig, frame, sc_orig, false, forged); } static void execute_default_from_dispatch(dcontext_t *dcontext, int sig, sigframe_rt_t *frame) { execute_default_action(dcontext, sig, frame, NULL, true, false); } void receive_pending_signal(dcontext_t *dcontext) { thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field; sigpending_t *temp; int sig; LOG(THREAD, LOG_ASYNCH, 3, "receive_pending_signal\n"); if (info->interrupted != NULL) { relink_interrupted_fragment(dcontext, info); } /* grab first pending signal * XXX: start with real-time ones? */ /* "lock" the array to prevent a new signal that interrupts this bit of * code from prepended or deleting from the array while we're accessing it */ info->accessing_sigpending = true; /* barrier to prevent compiler from moving the above write below the loop */ __asm__ __volatile__("" : : : "memory"); if (!info->multiple_pending_units && info->num_pending + 2 >= DYNAMO_OPTION(max_pending_signals)) { /* We're close to the limit: proactively get a new unit while it's safe * to acquire locks. We do that by pushing over the edge. * We assume that filling up a 2nd unit is too pathological to plan for. */ info->multiple_pending_units = true; SYSLOG_INTERNAL_WARNING("many pending signals: asking for 2nd special unit"); sigpending_t *temp1 = special_heap_alloc(info->sigheap); sigpending_t *temp2 = special_heap_alloc(info->sigheap); sigpending_t *temp3 = special_heap_alloc(info->sigheap); special_heap_free(info->sigheap, temp1); special_heap_free(info->sigheap, temp2); special_heap_free(info->sigheap, temp3); } for (sig = 1; sig <= MAX_SIGNUM; sig++) { if (info->sigpending[sig] != NULL) { bool executing = true; /* We do not re-check whether blocked if it was unblocked at * receive time, to properly handle sigsuspend (i#1340). */ if (!info->sigpending[sig]->unblocked && kernel_sigismember(&info->app_sigblocked, sig)) { LOG(THREAD, LOG_ASYNCH, 3, "\tsignal %d is blocked!\n", sig); continue; } LOG(THREAD, LOG_ASYNCH, 3, "\treceiving signal %d\n", sig); /* execute_handler_from_dispatch()'s call to copy_frame_to_stack() is * allowed to remove the front entry from info->sigpending[sig] and * jump to d_r_dispatch. */ executing = execute_handler_from_dispatch(dcontext, sig); temp = info->sigpending[sig]; info->sigpending[sig] = temp->next; special_heap_free(info->sigheap, temp); info->num_pending--; /* only one signal at a time! */ if (executing) { /* Make negative so our fcache_enter check makes progress but * our C code still considers there to be pending signals. */ dcontext->signals_pending = -1; break; } } } /* barrier to prevent compiler from moving the below write above the loop */ __asm__ __volatile__("" : : : "memory"); info->accessing_sigpending = false; /* we only clear this on a call to us where we find NO pending signals */ if (sig > MAX_SIGNUM) { LOG(THREAD, LOG_ASYNCH, 3, "\tclearing signals_pending flag\n"); dcontext->signals_pending = 0; } } /* Returns false if should NOT issue syscall. */ bool #ifdef LINUX handle_sigreturn(dcontext_t *dcontext, bool rt) #else handle_sigreturn(dcontext_t *dcontext, void *ucxt_param, int style) #endif { thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field; sigcontext_t *sc = NULL; /* initialize to satisfy Mac clang */ kernel_ucontext_t *ucxt = NULL; int sig = 0; app_pc next_pc; /* xsp was put in mcontext prior to pre_system_call() */ reg_t xsp = get_mcontext(dcontext)->xsp; #ifdef MACOS bool rt = true; #endif LOG(THREAD, LOG_ASYNCH, 3, "%ssigreturn()\n", rt ? "rt_" : ""); LOG(THREAD, LOG_ASYNCH, 3, "\txsp is " PFX "\n", xsp); #ifdef PROGRAM_SHEPHERDING /* if (!sig_has_restorer, region was never added to exec list, * allowed as pattern only and kicked off at first write via * selfmod detection or otherwise if vsyscall, so no worries * about having to remove it here */ #endif /* The easiest way to set all the non-GPR state that DR does not separately * preserve is to actually execute the sigreturn syscall, so we set up to do * that. We do not want to change DR's signal state, however, so we set it * back to DR's values after processing the state for the app. */ kernel_sigset_t our_mask; sigprocmask_syscall(SIG_SETMASK, NULL, &our_mask, sizeof(our_mask)); /* get sigframe: it's the top thing on the stack, except the ret * popped off pretcode. * WARNING: handler for tcsh's window_change (SIGWINCH) clobbers its * signal # arg, so don't use frame->sig! (kernel doesn't look at sig * so app can get away with it) */ if (rt) { #ifdef LINUX sigframe_rt_t *frame = (sigframe_rt_t *)(xsp IF_X86(-sizeof(char *))); /* use si_signo instead of sig, less likely to be clobbered by app */ sig = frame->info.si_signo; # ifdef X86_32 LOG(THREAD, LOG_ASYNCH, 3, "\tsignal was %d (did == param %d)\n", sig, frame->sig); if (frame->sig != sig) LOG(THREAD, LOG_ASYNCH, 1, "WARNING: app sig handler clobbered sig param\n"); # endif sc = get_sigcontext_from_app_frame(info, sig, (void *)frame); ucxt = &frame->uc; #elif defined(MACOS) /* The initial frame fields on the stack are messed up due to * params to handler from tramp, so use params to syscall. * XXX: we don't have signal # though: so we have to rely on app * not clobbering the sig param field. */ sig = *(int *)xsp; LOG(THREAD, LOG_ASYNCH, 3, "\tsignal was %d\n", sig); ucxt = (kernel_ucontext_t *)ucxt_param; if (ucxt == NULL) { /* On Mac the kernel seems to store state on whether the process is * on the altstack, so longjmp calls _sigunaltstack() which issues a * sigreturn syscall telling the kernel about the altstack change, * with a NULL context. */ LOG(THREAD, LOG_ASYNCH, 3, "\tsigunalstack sigreturn: no context\n"); return true; } sc = SIGCXT_FROM_UCXT(ucxt); #endif ASSERT(sig > 0 && sig <= MAX_SIGNUM && IS_RT_FOR_APP(info, sig)); /* Re-set sigstack from the value stored in the frame. Silently ignore failure, * just like the kernel does. */ uint ignored; /* The kernel checks for being on the stack *after* swapping stacks, so pass * sc->SC_XSP as the current stack. */ handle_sigaltstack(dcontext, &ucxt->uc_stack, NULL, sc->SC_XSP, &ignored); /* Restore DR's so sigreturn syscall won't change it. */ ucxt->uc_stack = info->sigstack; /* FIXME: what if handler called sigaction and requested rt * when itself was non-rt? */ /* Discard blocked signals, re-set from prev mask stored in frame. */ set_blocked(dcontext, SIGMASK_FROM_UCXT(ucxt), true /*absolute*/); /* Restore DR's so sigreturn syscall won't change it. */ *SIGMASK_FROM_UCXT(ucxt) = our_mask; } #if defined(LINUX) && !defined(X64) else { /* FIXME: libc's restorer pops prior to calling sigreturn, I have * no idea why, but kernel asks for xsp-8 not xsp-4...weird! */ kernel_sigset_t prevset; sigframe_plain_t *frame = (sigframe_plain_t *)(xsp IF_X86(-8)); /* We don't trust frame->sig (app sometimes clobbers it), and for * plain frame there's no other place that sig is stored, * so as a hack we added a new frame! * FIXME: this means we won't support nonstandard use of SYS_sigreturn, * e.g., as NtContinue, if frame didn't come from a real signal and so * wasn't copied to stack by us. */ sig = frame->sig_noclobber; LOG(THREAD, LOG_ASYNCH, 3, "\tsignal was %d (did == param %d)\n", sig, IF_X86_ELSE(frame->sig, 0)); # ifdef X86_32 if (frame->sig != sig) LOG(THREAD, LOG_ASYNCH, 1, "WARNING: app sig handler clobbered sig param\n"); # endif ASSERT(sig > 0 && sig <= MAX_SIGNUM && !IS_RT_FOR_APP(info, sig)); sc = get_sigcontext_from_app_frame(info, sig, (void *)frame); /* discard blocked signals, re-set from prev mask stored in frame */ prevset.sig[0] = frame->IF_X86_ELSE(sc.oldmask, uc.uc_mcontext.oldmask); if (_NSIG_WORDS > 1) { memcpy(&prevset.sig[1], &frame->IF_X86_ELSE(extramask, uc.sigset_ex), sizeof(prevset.sig[1])); } # ifdef ARM ucxt = &frame->uc; /* we leave ucxt NULL for x86: not needed there */ # endif set_blocked(dcontext, &prevset, true /*absolute*/); /* Restore DR's so sigreturn syscall won't change it. */ convert_rt_mask_to_nonrt(frame, &our_mask); } #endif /* LINUX */ /* Make sure we deliver pending signals that are now unblocked. */ check_signals_pending(dcontext, info); /* if we were building a trace, kill it */ if (is_building_trace(dcontext)) { LOG(THREAD, LOG_ASYNCH, 3, "\tsquashing trace-in-progress\n"); trace_abort(dcontext); } /* Defensively check for NULL. * XXX i#3182: It did happen but it is not clear how. */ if (info->app_sigaction[sig] != NULL && TEST(SA_ONESHOT, info->app_sigaction[sig]->flags)) { ASSERT(info->app_sigaction[sig]->handler == (handler_t)SIG_DFL); if (!info->we_intercept[sig]) { /* let kernel do default independent of us */ handler_free(dcontext, info->app_sigaction[sig], sizeof(kernel_sigaction_t)); info->app_sigaction[sig] = NULL; } } ASSERT(!safe_is_in_fcache(dcontext, (app_pc)sc->SC_XIP, (byte *)sc->SC_XSP)); #ifdef CLIENT_INTERFACE sig_full_cxt_t sc_full = { sc, NULL /*not provided*/ }; get_mcontext(dcontext)->pc = dcontext->next_tag; instrument_kernel_xfer(dcontext, DR_XFER_SIGNAL_RETURN, osc_empty, NULL, get_mcontext(dcontext), (app_pc)sc->SC_XIP, sc->SC_XSP, sc_full, NULL, sig); #endif #ifdef DEBUG if (d_r_stats->loglevel >= 3 && (d_r_stats->logmask & LOG_ASYNCH) != 0) { LOG(THREAD, LOG_ASYNCH, 3, "returning-to sigcontext " PFX ":\n", sc); dump_sigcontext(dcontext, sc); } #endif /* XXX i#1206: if we interrupted a non-ignorable syscall to run the app's * handler, and we set up to restart the syscall, we'll come here with the * translated syscall pc -- thus we can't distinguish from a signal interrupting * the prior app instr. So we can't simply point at do_syscall and call * set_at_syscall -- we have to re-interpret the syscall and re-run the * pre-syscall handler. Hopefully all our pre-syscall handlers can handle that. */ /* set up for d_r_dispatch */ /* we have to use a different slot since next_tag ends up holding the do_syscall * entry when entered from d_r_dispatch (we're called from * pre_syscall, prior to entering cache) */ dcontext->asynch_target = canonicalize_pc_target( dcontext, (app_pc)(sc->SC_XIP IF_ARM(| (TEST(EFLAGS_T, sc->SC_XFLAGS) ? 1 : 0)))); next_pc = dcontext->asynch_target; #ifdef VMX86_SERVER /* PR 404712: kernel only restores gp regs so we do it ourselves and avoid * complexities of kernel's non-linux-like sigreturn semantics */ sig_full_cxt_t sc_full = { sc, NULL }; /* non-ARM so NULL ok */ sigcontext_to_mcontext(get_mcontext(dcontext), &sc_full, DR_MC_ALL); #else /* HACK to get eax put into mcontext AFTER do_syscall */ dcontext->next_tag = (app_pc)sc->IF_X86_ELSE(SC_XAX, SC_R0); /* use special linkstub so we know why we came out of the cache */ sc->IF_X86_ELSE(SC_XAX, SC_R0) = (ptr_uint_t)get_asynch_linkstub(); /* set our sigreturn context to point to fcache_return */ /* We don't need PC_AS_JMP_TGT b/c the kernel uses EFLAGS_T for the mode */ sc->SC_XIP = (ptr_uint_t)fcache_return_routine(dcontext); /* if we overlaid inner frame on nested signal, will end up with this * error -- disable in release build since this is often app's fault (stack * too small) * FIXME: how make this transparent? what ends up happening is that we * get a segfault when we start interpreting d_r_dispatch, we want to make it * look like whatever would happen to the app... */ ASSERT((app_pc)sc->SC_XIP != next_pc); # ifdef AARCHXX set_stolen_reg_val(get_mcontext(dcontext), get_sigcxt_stolen_reg(sc)); set_sigcxt_stolen_reg(sc, (reg_t)*get_dr_tls_base_addr()); # ifdef AARCH64 /* On entry to the do_syscall gencode, we save X1 into TLS_REG1_SLOT. * Then the sigreturn would redirect the flow to the fcache_return gencode. * In fcache_return it recovers the values of x0 and x1 from TLS_SLOT 0 and 1. */ get_mcontext(dcontext)->r1 = sc->regs[1]; # else /* We're going to our fcache_return gencode which uses DEFAULT_ISA_MODE */ set_pc_mode_in_cpsr(sc, DEFAULT_ISA_MODE); # endif # endif #endif LOG(THREAD, LOG_ASYNCH, 3, "set next tag to " PFX ", sc->SC_XIP to " PFX "\n", next_pc, sc->SC_XIP); return IF_VMX86_ELSE(false, true); } bool is_signal_restorer_code(byte *pc, size_t *len) { /* is this a sigreturn pattern placed by kernel on the stack or vsyscall page? * for non-rt frame: * 0x58 popl %eax * 0xb8 <sysnum> movl SYS_sigreturn, %eax * 0xcd 0x80 int 0x80 * for rt frame: * 0xb8 <sysnum> movl SYS_rt_sigreturn, %eax * 0xcd 0x80 int 0x80 */ /* optimized we only need two uint reads, but we have to do * some little-endian byte-order reverses to get the right result */ #define reverse(x) \ ((((x)&0xff) << 24) | (((x)&0xff00) << 8) | (((x)&0xff0000) >> 8) | \ (((x)&0xff000000) >> 24)) #ifdef MACOS # define SYS_RT_SIGRET SYS_sigreturn #else # define SYS_RT_SIGRET SYS_rt_sigreturn #endif #ifndef X64 /* 58 b8 s4 s3 s2 s1 cd 80 */ static const uint non_rt_1w = reverse(0x58b80000 | (reverse(SYS_sigreturn) >> 16)); static const uint non_rt_2w = reverse((reverse(SYS_sigreturn) << 16) | 0xcd80); #endif /* b8 s4 s3 s2 s1 cd 80 XX */ static const uint rt_1w = reverse(0xb8000000 | (reverse(SYS_RT_SIGRET) >> 8)); static const uint rt_2w = reverse((reverse(SYS_RT_SIGRET) << 24) | 0x00cd8000); /* test rt first as it's the most common * only 7 bytes here so we ignore the last one (becomes msb since little-endian) */ if (*((uint *)pc) == rt_1w && (*((uint *)(pc + 4)) & 0x00ffffff) == rt_2w) { if (len != NULL) *len = 7; return true; } #ifndef X64 if (*((uint *)pc) == non_rt_1w && *((uint *)(pc + 4)) == non_rt_2w) { if (len != NULL) *len = 8; return true; } #endif return false; } void os_forge_exception(app_pc target_pc, dr_exception_type_t type) { /* PR 205136: * We want to deliver now, and the caller expects us not to return. * We have two alternatives: * 1) Emulate stack frame, and call transfer_to_dispatch() for delivery. We * may not know how to fill out every field of the frame (cr2, etc.). Plus, * we have problems w/ default actions (PR 205310) but we have to solve * those long-term anyway. We also have to create different frames based on * whether app intercepts via rt or not. * 2) Call SYS_tgkill from a special location that our handler can * recognize and know it's a signal meant for the app and that the * interrupted DR can be discarded. We'd then essentially repeat 1, * but modifying the kernel-generated frame. We'd have to always * intercept SIGILL. * I'm going with #1 for now b/c the common case is simpler. */ dcontext_t *dcontext = get_thread_private_dcontext(); #if defined(LINUX) && defined(X86) thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field; #endif char frame_no_xstate[sizeof(sigframe_rt_t)]; sigframe_rt_t *frame = (sigframe_rt_t *)frame_no_xstate; int sig; dr_where_am_i_t cur_whereami = dcontext->whereami; kernel_ucontext_t *uc = get_ucontext_from_rt_frame(frame); sigcontext_t *sc = SIGCXT_FROM_UCXT(uc); switch (type) { case ILLEGAL_INSTRUCTION_EXCEPTION: sig = SIGILL; break; case UNREADABLE_MEMORY_EXECUTION_EXCEPTION: sig = SIGSEGV; break; case SINGLE_STEP_EXCEPTION: ASSERT_NOT_IMPLEMENTED(false); /* FIXME: i#2144 */ case IN_PAGE_ERROR_EXCEPTION: /* fall-through: Windows only */ default: ASSERT_NOT_REACHED(); sig = SIGSEGV; break; } LOG(GLOBAL, LOG_ASYNCH, 1, "os_forge_exception sig=%d\n", sig); /* Since we always delay delivery, we always want an rt frame. we'll convert * to a plain frame on delivery. */ memset(frame, 0, sizeof(*frame)); frame->info.si_signo = sig; /* Set si_code to match what would happen natively. We also need this to * avoid the !is_sys_kill() check in record_pending_signal() to avoid an * infinite loop (i#3171). */ frame->info.si_code = IF_LINUX_ELSE(SI_KERNEL, 0); frame->info.si_addr = target_pc; #ifdef X86_32 frame->sig = sig; frame->pinfo = &frame->info; frame->puc = (void *)&frame->uc; #endif #if defined(LINUX) && defined(X86) /* We use a TLS buffer to avoid too much stack space here. */ sc->fpstate = (kernel_fpstate_t *)get_xstate_buffer(dcontext); #endif mcontext_to_ucontext(uc, get_mcontext(dcontext)); sc->SC_XIP = (reg_t)target_pc; /* We'll fill in fpstate at delivery time. * We fill in segment registers to their current values and assume they won't * change and that these are the right values. * * FIXME i#2095: restore the app's segment register value(s). * * XXX: it seems to work w/o filling in the other state: * I'm leaving cr2 and other fields all zero. * If this gets problematic we could switch to approach #2. */ thread_set_segment_registers(sc); #if defined(X86) && defined(LINUX) if (sig_has_restorer(info, sig)) frame->pretcode = (char *)info->app_sigaction[sig]->restorer; else frame->pretcode = (char *)dynamorio_sigreturn; #endif /* We assume that we do not need to translate the context when forged. * If we did, we'd move this below enter_nolinking() (and update * record_pending_signal() to do the translation). */ record_pending_signal(dcontext, sig, &frame->uc, frame, true /*forged*/ _IF_CLIENT(NULL)); /* For most callers this is not necessary and we only do it to match * the Windows usage model: but for forging from our own handler, * this is good b/c it resets us to the base of dstack. */ /* tell d_r_dispatch() why we're coming there */ dcontext->whereami = DR_WHERE_TRAMPOLINE; KSTART(dispatch_num_exits); set_last_exit(dcontext, (linkstub_t *)get_asynch_linkstub()); if (is_couldbelinking(dcontext)) enter_nolinking(dcontext, NULL, false); transfer_to_dispatch( dcontext, get_mcontext(dcontext), cur_whereami != DR_WHERE_FCACHE && cur_whereami != DR_WHERE_SIGNAL_HANDLER /*full_DR_state*/); ASSERT_NOT_REACHED(); } void os_request_fatal_coredump(const char *msg) { /* To enable getting a coredump just make sure that rlimits are * not preventing getting one, e.g. ulimit -c unlimited */ SYSLOG_INTERNAL_ERROR("Crashing the process deliberately for a core dump!"); os_terminate_via_signal(NULL, 0 /*no cleanup*/, SIGSEGV); ASSERT_NOT_REACHED(); } void os_request_live_coredump(const char *msg) { #ifdef VMX86_SERVER if (os_in_vmkernel_userworld()) { vmk_request_live_coredump(msg); return; } #endif LOG(GLOBAL, LOG_ASYNCH, 1, "LiveCoreDump unsupported (PR 365105). " "Continuing execution without a core.\n"); return; } void os_dump_core(const char *msg) { /* FIXME Case 3408: fork stack dump crashes on 2.6 kernel, so moving the getchar * ahead to aid in debugging */ if (TEST(DUMPCORE_WAIT_FOR_DEBUGGER, dynamo_options.dumpcore_mask)) { SYSLOG_INTERNAL_ERROR("looping so you can use gdb to attach to pid %s", get_application_pid()); IF_CLIENT_INTERFACE(SYSLOG(SYSLOG_CRITICAL, WAITING_FOR_DEBUGGER, 2, get_application_name(), get_application_pid())); /* getchar() can hit our own vsyscall hook (from PR 212570); typically we * want to attach and not continue anyway, so doing an infinite loop: */ while (true) os_thread_yield(); } if (DYNAMO_OPTION(live_dump)) { os_request_live_coredump(msg); } if (TEST(DUMPCORE_INCLUDE_STACKDUMP, dynamo_options.dumpcore_mask)) { /* fork, dump core, then use gdb to get a stack dump * we can get into an infinite loop if there's a seg fault * in the process of doing this -- so we have a do-once test, * and if it failed we do the no-symbols dr callstack dump */ static bool tried_stackdump = false; if (!tried_stackdump) { tried_stackdump = true; d_r_stackdump(); } else { static bool tried_calldump = false; if (!tried_calldump) { tried_calldump = true; dump_dr_callstack(STDERR); } } } if (!DYNAMO_OPTION(live_dump)) { os_request_fatal_coredump(msg); ASSERT_NOT_REACHED(); } } #ifdef RETURN_AFTER_CALL bool at_known_exception(dcontext_t *dcontext, app_pc target_pc, app_pc source_fragment) { /* There is a known exception in signal restorers and the Linux * dynamic symbol resoulution. * The latter we assume it is the only other recurring known exception, * so the first time we pattern match to help make sure it is indeed * _dl_runtime_resolve (since with LD_BIND_NOW it will never be called). * After that we compare with the known value. */ static app_pc known_exception = 0; thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field; LOG(THREAD, LOG_INTERP, 1, "RCT: testing for KNOWN exception " PFX " " PFX "\n", target_pc, source_fragment); /* Check if this is a signal return. FIXME: we should really get that from the frame itself. Since currently grabbing restorer only when copying a frame, this will work with nested signals only if they all have same restorer (I haven't seen restorers other than the one in libc) */ if (target_pc == info->signal_restorer_retaddr) { LOG(THREAD, LOG_INTERP, 1, "RCT: KNOWN exception this is a signal restorer --ok \n"); STATS_INC(ret_after_call_signal_restorer); return true; } if (source_fragment == known_exception) { LOG(THREAD, LOG_INTERP, 1, "RCT: KNOWN exception again _dl_runtime_resolve --ok\n"); return true; } if (known_exception == 0) { int ret_imm; return at_dl_runtime_resolve_ret(dcontext, source_fragment, &ret_imm); } return false; } #endif /* RETURN_AFTER_CALL */ /*************************************************************************** * ITIMERS * * We support combining an app itimer with a DR itimer for each of the 3 types * (PR 204556). */ static inline uint64 timeval_to_usec(struct timeval *t1) { return ((uint64)(t1->tv_sec)) * 1000000 + t1->tv_usec; } static inline void usec_to_timeval(uint64 usec, struct timeval *t1) { t1->tv_sec = (long)usec / 1000000; t1->tv_usec = (long)usec % 1000000; } static void init_itimer(dcontext_t *dcontext, bool first) { thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field; int i; ASSERT(info != NULL); ASSERT(!info->shared_itimer); /* else inherit */ LOG(THREAD, LOG_ASYNCH, 2, "thread has private itimers%s\n", os_itimers_thread_shared() ? " (for now)" : ""); if (os_itimers_thread_shared()) { /* we have to allocate now even if no itimer is installed until later, * so that all child threads point to the same data */ info->itimer = (thread_itimer_info_t(*)[NUM_ITIMERS])global_heap_alloc( sizeof(*info->itimer) HEAPACCT(ACCT_OTHER)); } else { /* for simplicity and parallel w/ shared we allocate proactively */ info->itimer = (thread_itimer_info_t(*)[NUM_ITIMERS])heap_alloc( dcontext, sizeof(*info->itimer) HEAPACCT(ACCT_OTHER)); } memset(info->itimer, 0, sizeof(*info->itimer)); for (i = 0; i < NUM_ITIMERS; i++) { ASSIGN_INIT_RECURSIVE_LOCK_FREE((*info->itimer)[i].lock, shared_itimer_lock); } if (first) { /* see if app has set up an itimer before we were loaded */ struct itimerval prev; int rc; int which; for (which = 0; which < NUM_ITIMERS; which++) { rc = getitimer_syscall(which, &prev); ASSERT(rc == SUCCESS); (*info->itimer)[which].app.interval = timeval_to_usec(&prev.it_interval); (*info->itimer)[which].app.value = timeval_to_usec(&prev.it_value); } } } /* Up to caller to hold lock for shared itimers */ static bool set_actual_itimer(dcontext_t *dcontext, int which, thread_sig_info_t *info, bool enable) { struct itimerval val; int rc; ASSERT(info != NULL && info->itimer != NULL); ASSERT(which >= 0 && which < NUM_ITIMERS); if (enable) { LOG(THREAD, LOG_ASYNCH, 2, "installing itimer %d interval=" INT64_FORMAT_STRING ", value=" INT64_FORMAT_STRING "\n", which, (*info->itimer)[which].actual.interval, (*info->itimer)[which].actual.value); /* i#2907: we have no signal handlers until we start the app (i#2335) * so we can't set up an itimer until then. */ ASSERT(dynamo_initialized); ASSERT(!info->shared_itimer || self_owns_recursive_lock(&(*info->itimer)[which].lock)); usec_to_timeval((*info->itimer)[which].actual.interval, &val.it_interval); usec_to_timeval((*info->itimer)[which].actual.value, &val.it_value); } else { LOG(THREAD, LOG_ASYNCH, 2, "disabling itimer %d\n", which); memset(&val, 0, sizeof(val)); (*info->itimer)[which].actual.value = 0; (*info->itimer)[which].actual.interval = 0; } rc = setitimer_syscall(which, &val, NULL); return (rc == SUCCESS); } /* Caller should hold lock */ static bool itimer_new_settings(dcontext_t *dcontext, int which, bool app_changed) { struct itimerval val; bool res = true; int rc; thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field; ASSERT(info != NULL && info->itimer != NULL); ASSERT(which >= 0 && which < NUM_ITIMERS); ASSERT(!info->shared_itimer || self_owns_recursive_lock(&(*info->itimer)[which].lock)); /* the general strategy is to set the actual value to the smaller, * update the larger on each signal, and when the larger becomes * smaller do a one-time swap for the remaining */ if ((*info->itimer)[which].dr.interval > 0 && ((*info->itimer)[which].app.interval == 0 || (*info->itimer)[which].dr.interval < (*info->itimer)[which].app.interval)) (*info->itimer)[which].actual.interval = (*info->itimer)[which].dr.interval; else (*info->itimer)[which].actual.interval = (*info->itimer)[which].app.interval; if ((*info->itimer)[which].actual.value > 0) { if ((*info->itimer)[which].actual.interval == 0 && (*info->itimer)[which].dr.value == 0 && (*info->itimer)[which].app.value == 0) { (*info->itimer)[which].actual.value = 0; res = set_actual_itimer(dcontext, which, info, false /*disabled*/); } else { /* one of app or us has an in-flight timer which we should not interrupt. * but, we already set the new requested value (for app or us), so we * need to update the actual value so we subtract properly. */ rc = getitimer_syscall(which, &val); ASSERT(rc == SUCCESS); uint64 left = timeval_to_usec(&val.it_value); if (!app_changed && (*info->itimer)[which].actual.value == (*info->itimer)[which].app.value) (*info->itimer)[which].app.value = left; if (app_changed && (*info->itimer)[which].actual.value == (*info->itimer)[which].dr.value) (*info->itimer)[which].dr.value = left; (*info->itimer)[which].actual.value = left; } } else { if ((*info->itimer)[which].dr.value > 0 && ((*info->itimer)[which].app.value == 0 || (*info->itimer)[which].dr.value < (*info->itimer)[which].app.value)) (*info->itimer)[which].actual.value = (*info->itimer)[which].dr.value; else { (*info->itimer)[which].actual.value = (*info->itimer)[which].app.value; } res = set_actual_itimer(dcontext, which, info, true /*enable*/); } return res; } bool set_itimer_callback(dcontext_t *dcontext, int which, uint millisec, void (*func)(dcontext_t *, priv_mcontext_t *), void (*func_api)(dcontext_t *, dr_mcontext_t *)) { thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field; bool rc; if (which < 0 || which >= NUM_ITIMERS) { CLIENT_ASSERT(false, "invalid itimer type"); return false; } if (func == NULL && func_api == NULL && millisec != 0) { CLIENT_ASSERT(false, "invalid function"); return false; } ASSERT(info != NULL && info->itimer != NULL); if (info->shared_itimer) acquire_recursive_lock(&(*info->itimer)[which].lock); (*info->itimer)[which].dr.interval = ((uint64)millisec) * 1000; (*info->itimer)[which].dr.value = (*info->itimer)[which].dr.interval; (*info->itimer)[which].cb = func; (*info->itimer)[which].cb_api = func_api; if (!dynamo_initialized) { /* i#2907: we have no signal handlers until we start the app (i#2335) * so we can't set up an itimer until then. start_itimer() called * from os_thread_under_dynamo() will enable it. */ LOG(THREAD, LOG_ASYNCH, 2, "delaying itimer until attach\n"); rc = true; } else rc = itimer_new_settings(dcontext, which, false /*us*/); if (info->shared_itimer) release_recursive_lock(&(*info->itimer)[which].lock); return rc; } uint get_itimer_frequency(dcontext_t *dcontext, int which) { thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field; uint ms = 0; if (which < 0 || which >= NUM_ITIMERS) { CLIENT_ASSERT(false, "invalid itimer type"); return 0; } ASSERT(info != NULL && info->itimer != NULL); if (info->shared_itimer) acquire_recursive_lock(&(*info->itimer)[which].lock); ms = (*info->itimer)[which].dr.interval / 1000; if (info->shared_itimer) release_recursive_lock(&(*info->itimer)[which].lock); return ms; } static int signal_to_itimer_type(int sig) { if (sig == SIGALRM) return ITIMER_REAL; else if (sig == SIGVTALRM) return ITIMER_VIRTUAL; else if (sig == SIGPROF) return ITIMER_PROF; else return -1; } static bool alarm_signal_has_DR_only_itimer(dcontext_t *dcontext, int signal) { thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field; int which = signal_to_itimer_type(signal); if (which == -1) return false; if (info->shared_itimer) acquire_recursive_lock(&(*info->itimer)[which].lock); bool DR_only = ((*info->itimer)[which].dr.value > 0 || (*info->itimer)[which].dr.interval > 0) && (*info->itimer)[which].app.value == 0 && (*info->itimer)[which].app.interval == 0; if (info->shared_itimer) release_recursive_lock(&(*info->itimer)[which].lock); return DR_only; } static bool handle_alarm(dcontext_t *dcontext, int sig, kernel_ucontext_t *ucxt) { thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field; ASSERT(info != NULL && info->itimer != NULL); int which = 0; bool invoke_cb = false, pass_to_app = false, reset_timer_manually = false; bool should_release_lock = false; /* i#471: suppress alarms coming in after exit */ if (dynamo_exited) return pass_to_app; which = signal_to_itimer_type(sig); ASSERT(which != -1); LOG(THREAD, LOG_ASYNCH, 2, "received alarm %d @" PFX "\n", which, SIGCXT_FROM_UCXT(ucxt)->SC_XIP); /* This alarm could have interrupted an app thread making an itimer syscall, * which is why we don't want to block on a lock here. * It can't interrupt this same thread handling a prior alarm (b/c we block * the signal in our handler). It could arrive in thread B while thread A * is still handling a prior alarm if the alarm frequency is high and the * processing is slow, which is why we split the locks to be per-itimer-type. * We also avoid new thread setup code acquiring these itimer locks by using * atomic increments instead for the refcounts. Xref i#2993. */ if (info->shared_itimer) { #ifdef DEADLOCK_AVOIDANCE /* i#2061: in debug build we can get an alarm while in deadlock handling * code that holds innermost_lock. We just drop such alarms. */ if (OWN_MUTEX(&innermost_lock)) return pass_to_app; #endif if (self_owns_recursive_lock(&(*info->itimer)[which].lock)) { /* What can we do? We just go ahead and hope conflicting writes work out. * We don't re-acquire in case app was in middle of acquiring. */ } else { #define ALARM_LOCK_MAX_TRIES 4 int i; for (i = 0; i < ALARM_LOCK_MAX_TRIES; ++i) { if (try_recursive_lock(&(*info->itimer)[which].lock)) { should_release_lock = true; break; } os_thread_yield(); } if (!should_release_lock) { /* Heuristic: if fail N times then assume interrupted lock routine * while processing an app syscall (see above: we ruled out other * scenarios). What can we do? Just continue and hope conflicting * writes work out. */ } } } if ((*info->itimer)[which].app.value > 0) { /* Alarm could have been on its way when app value changed */ if ((*info->itimer)[which].app.value >= (*info->itimer)[which].actual.value) { (*info->itimer)[which].app.value -= (*info->itimer)[which].actual.value; LOG(THREAD, LOG_ASYNCH, 2, "\tapp value is now %d\n", (*info->itimer)[which].app.value); if ((*info->itimer)[which].app.value == 0) { pass_to_app = true; (*info->itimer)[which].app.value = (*info->itimer)[which].app.interval; } else reset_timer_manually = true; } } if ((*info->itimer)[which].dr.value > 0) { /* Alarm could have been on its way when DR value changed */ if ((*info->itimer)[which].dr.value >= (*info->itimer)[which].actual.value) { (*info->itimer)[which].dr.value -= (*info->itimer)[which].actual.value; LOG(THREAD, LOG_ASYNCH, 2, "\tdr value is now %d\n", (*info->itimer)[which].dr.value); if ((*info->itimer)[which].dr.value == 0) { invoke_cb = true; (*info->itimer)[which].dr.value = (*info->itimer)[which].dr.interval; } else reset_timer_manually = true; } } /* for efficiency we let the kernel reset the value to interval if * there's only one timer */ if (reset_timer_manually) { (*info->itimer)[which].actual.value = 0; itimer_new_settings(dcontext, which, true /*doesn't matter: actual.value==0*/); } else (*info->itimer)[which].actual.value = (*info->itimer)[which].actual.interval; if (invoke_cb) { /* invoke after setting new itimer value */ /* we save stack space by allocating superset dr_mcontext_t */ dr_mcontext_t dmc; dr_mcontext_init(&dmc); priv_mcontext_t *mc = dr_mcontext_as_priv_mcontext(&dmc); ucontext_to_mcontext(mc, ucxt); void (*cb)(dcontext_t *, priv_mcontext_t *) = (*info->itimer)[which].cb; void (*cb_api)(dcontext_t *, dr_mcontext_t *) = (*info->itimer)[which].cb_api; if (which == ITIMER_VIRTUAL && info->shared_itimer && should_release_lock) { release_recursive_lock(&(*info->itimer)[which].lock); should_release_lock = false; } if (cb != NULL) { cb(dcontext, mc); } else { cb_api(dcontext, &dmc); } } if (info->shared_itimer && should_release_lock) release_recursive_lock(&(*info->itimer)[which].lock); return pass_to_app; } /* Starts itimer if stopped, or increases refcount of existing itimer if already * started. It is *not* safe to call this more than once for the same thread, * since it will inflate the refcount and prevent cleanup. */ void start_itimer(dcontext_t *dcontext) { thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field; ASSERT(info != NULL && info->itimer != NULL); bool start = false; if (info->shared_itimer) { /* i#2993: We avoid acquiring the lock as an alarm signal can arrive during * the lock routine (esp in debug build) and cause problems. */ int new_count = atomic_add_exchange_int((volatile int *)info->shared_itimer_underDR, 1); start = (new_count == 1); } else start = true; if (start) { /* Enable all DR itimers b/c at least one thread in this set of threads * sharing itimers is under DR control */ int which; LOG(THREAD, LOG_ASYNCH, 2, "starting DR itimers from thread " TIDFMT "\n", d_r_get_thread_id()); for (which = 0; which < NUM_ITIMERS; which++) { if (info->shared_itimer) acquire_recursive_lock(&(*info->itimer)[which].lock); /* May have already been set up with the start delayed (i#2907). */ if ((*info->itimer)[which].dr.interval > 0) { (*info->itimer)[which].dr.value = (*info->itimer)[which].dr.interval; itimer_new_settings(dcontext, which, false /*!app*/); } if (info->shared_itimer) release_recursive_lock(&(*info->itimer)[which].lock); } } } /* Decrements the itimer refcount, and turns off the itimer once there are no * more threads listening for it. It is not safe to call this more than once on * the same thread. */ void stop_itimer(dcontext_t *dcontext) { thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field; ASSERT(info != NULL && info->itimer != NULL); bool stop = false; if (info->shared_itimer) { ASSERT(*info->shared_itimer_underDR > 0); int new_count = atomic_add_exchange_int((volatile int *)info->shared_itimer_underDR, -1); stop = (new_count == 0); } else stop = true; if (stop) { /* Disable all DR itimers b/c this set of threads sharing this * itimer is now completely native */ int which; LOG(THREAD, LOG_ASYNCH, 2, "stopping DR itimers from thread " TIDFMT "\n", d_r_get_thread_id()); for (which = 0; which < NUM_ITIMERS; which++) { if (info->shared_itimer) acquire_recursive_lock(&(*info->itimer)[which].lock); if ((*info->itimer)[which].dr.value > 0) { (*info->itimer)[which].dr.value = 0; if ((*info->itimer)[which].app.value > 0) { (*info->itimer)[which].actual.interval = (*info->itimer)[which].app.interval; } else set_actual_itimer(dcontext, which, info, false /*disable*/); } if (info->shared_itimer) release_recursive_lock(&(*info->itimer)[which].lock); } } } /* handle app itimer syscalls */ /* handle_pre_alarm also calls this function and passes NULL as prev_timer */ void handle_pre_setitimer(dcontext_t *dcontext, int which, const struct itimerval *new_timer, struct itimerval *prev_timer) { if (new_timer == NULL || which < 0 || which >= NUM_ITIMERS) return; thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field; ASSERT(info != NULL && info->itimer != NULL); struct itimerval val; if (d_r_safe_read(new_timer, sizeof(val), &val)) { if (info->shared_itimer) acquire_recursive_lock(&(*info->itimer)[which].lock); /* save a copy in case the syscall fails */ (*info->itimer)[which].app_saved = (*info->itimer)[which].app; (*info->itimer)[which].app.interval = timeval_to_usec(&val.it_interval); (*info->itimer)[which].app.value = timeval_to_usec(&val.it_value); LOG(THREAD, LOG_ASYNCH, 2, "app setitimer type=%d interval=" SZFMT " value=" SZFMT "\n", which, (*info->itimer)[which].app.interval, (*info->itimer)[which].app.value); itimer_new_settings(dcontext, which, true /*app*/); if (info->shared_itimer) release_recursive_lock(&(*info->itimer)[which].lock); } } void handle_post_setitimer(dcontext_t *dcontext, bool success, int which, const struct itimerval *new_timer, struct itimerval *prev_timer) { if (new_timer == NULL || which < 0 || which >= NUM_ITIMERS) { ASSERT(new_timer == NULL || !success); return; } thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field; ASSERT(info != NULL && info->itimer != NULL); ASSERT(which >= 0 && which < NUM_ITIMERS); if (!success && new_timer != NULL) { if (info->shared_itimer) acquire_recursive_lock(&(*info->itimer)[which].lock); /* restore saved pre-syscall settings */ (*info->itimer)[which].app = (*info->itimer)[which].app_saved; itimer_new_settings(dcontext, which, true /*app*/); if (info->shared_itimer) release_recursive_lock(&(*info->itimer)[which].lock); } if (success && prev_timer != NULL) handle_post_getitimer(dcontext, success, which, prev_timer); } void handle_post_getitimer(dcontext_t *dcontext, bool success, int which, struct itimerval *cur_timer) { thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field; ASSERT(info != NULL && info->itimer != NULL); if (success) { /* write succeeded for kernel but we're user and can have races */ struct timeval val; DEBUG_DECLARE(bool ok;) ASSERT(which >= 0 && which < NUM_ITIMERS); ASSERT(cur_timer != NULL); if (info->shared_itimer) acquire_recursive_lock(&(*info->itimer)[which].lock); usec_to_timeval((*info->itimer)[which].app.interval, &val); IF_DEBUG(ok =) safe_write_ex(&cur_timer->it_interval, sizeof(val), &val, NULL); ASSERT(ok); if (d_r_safe_read(&cur_timer->it_value, sizeof(val), &val)) { /* subtract the difference between last-asked-for value * and current value to reflect elapsed time */ uint64 left = (*info->itimer)[which].app.value - ((*info->itimer)[which].actual.value - timeval_to_usec(&val)); usec_to_timeval(left, &val); IF_DEBUG(ok =) safe_write_ex(&cur_timer->it_value, sizeof(val), &val, NULL); ASSERT(ok); } else ASSERT_NOT_REACHED(); if (info->shared_itimer) release_recursive_lock(&(*info->itimer)[which].lock); } } /* handle app alarm syscall */ /* alarm uses the same itimer and could be defined in terms of setitimer */ void handle_pre_alarm(dcontext_t *dcontext, unsigned int sec) { struct itimerval val; val.it_interval.tv_usec = 0; val.it_interval.tv_sec = 0; val.it_value.tv_usec = 0; val.it_value.tv_sec = sec; handle_pre_setitimer(dcontext, ITIMER_REAL, &val, NULL); } void handle_post_alarm(dcontext_t *dcontext, bool success, unsigned int sec) { /* alarm is always successful, so do nothing in post */ ASSERT(success); return; } /*************************************************************************** * Internal DR communication */ typedef struct _sig_detach_info_t { KSYNCH_TYPE *detached; byte *sigframe_xsp; #ifdef HAVE_SIGALTSTACK stack_t *app_sigstack; #endif } sig_detach_info_t; /* xsp is only set for X86 */ static void notify_and_jmp_without_stack(KSYNCH_TYPE *notify_var, byte *continuation, byte *xsp) { if (ksynch_kernel_support()) { /* Can't use dstack once we signal so in asm we do: * futex/semaphore = 1; * %xsp = xsp; * dynamorio_condvar_wake_and_jmp(notify_var, continuation); */ #ifdef MACOS ASSERT(sizeof(notify_var->sem) == 4); #endif #ifdef X86 # ifndef MACOS /* i#2632: recent clang for 32-bit annoyingly won't do the right thing for * "jmp dynamorio_condvar_wake_and_jmp" and leaves relocs so we ensure it's PIC. * We do this first as it may end up clobbering a scratch reg like xax. */ void (*asm_jmp_tgt)() = dynamorio_condvar_wake_and_jmp; asm("mov %0, %%" ASM_XDX : : "m"(asm_jmp_tgt)); # endif asm("mov %0, %%" ASM_XAX : : "m"(notify_var)); asm("mov %0, %%" ASM_XCX : : "m"(continuation)); asm("mov %0, %%" ASM_XSP : : "m"(xsp)); # ifdef MACOS asm("movl $1,4(%" ASM_XAX ")"); asm("jmp _dynamorio_condvar_wake_and_jmp"); # else asm("movl $1,(%" ASM_XAX ")"); asm("jmp *%" ASM_XDX); # endif #elif defined(AARCHXX) asm("ldr " ASM_R0 ", %0" : : "m"(notify_var)); asm("mov " ASM_R1 ", #1"); asm("str " ASM_R1 ",[" ASM_R0 "]"); asm("ldr " ASM_R1 ", %0" : : "m"(continuation)); asm("b dynamorio_condvar_wake_and_jmp"); #endif } else { ksynch_set_value(notify_var, 1); #ifdef X86 asm("mov %0, %%" ASM_XSP : : "m"(xsp)); asm("mov %0, %%" ASM_XAX : : "m"(continuation)); asm("jmp *%" ASM_XAX); #elif defined(AARCHXX) asm("ldr " ASM_R0 ", %0" : : "m"(continuation)); asm(ASM_INDJMP " " ASM_R0); #endif /* X86/ARM */ } } /* Go native from detach. This is executed on the app stack. */ static void sig_detach_go_native(sig_detach_info_t *info) { byte *xsp = info->sigframe_xsp; #ifdef HAVE_SIGALTSTACK /* Restore the app signal stack, though sigreturn will overwrite this with the * uc_stack in the frame's ucontext anyway (which we already set for the app). */ DEBUG_DECLARE(int rc =) sigaltstack_syscall(info->app_sigstack, NULL); ASSERT(rc == 0); #endif #ifdef X86 /* Skip pretcode */ xsp += sizeof(char *); #endif notify_and_jmp_without_stack(info->detached, (byte *)dynamorio_sigreturn, xsp); ASSERT_NOT_REACHED(); } /* Sets this (slave) thread to detach by directly returning from the signal. */ static void sig_detach(dcontext_t *dcontext, sigframe_rt_t *frame, KSYNCH_TYPE *detached) { thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field; byte *xsp; sig_detach_info_t detach_info; LOG(THREAD, LOG_ASYNCH, 1, "%s: detaching\n", __FUNCTION__); /* Update the mask of the signal frame so that the later sigreturn will * restore the app signal mask. */ memcpy(&frame->uc.uc_sigmask, &info->app_sigblocked, sizeof(info->app_sigblocked)); /* Copy the signal frame to the app stack. * XXX: We live with the transparency risk of storing the signal frame on * the app stack: we assume the app stack is writable where we need it to be, * and that we're not clobbering any app data beyond TOS. */ xsp = get_sigstack_frame_ptr(dcontext, SUSPEND_SIGNAL, frame); copy_frame_to_stack(dcontext, SUSPEND_SIGNAL, frame, xsp, false /*!pending*/); #ifdef HAVE_SIGALTSTACK /* Make sure the frame's sigstack reflects the app stack. * copy_frame_to_stack() should have done this for us. */ ASSERT(((sigframe_rt_t *)xsp)->uc.uc_stack.ss_sp == info->app_sigstack.ss_sp); #endif /* Restore app segment registers. */ os_thread_not_under_dynamo(dcontext); os_tls_thread_exit(dcontext->local_state); #ifdef HAVE_SIGALTSTACK /* We can't restore the app's sigstack here as that will invalidate the * sigstack we're currently on. */ detach_info.app_sigstack = &info->app_sigstack; #endif detach_info.detached = detached; detach_info.sigframe_xsp = xsp; call_switch_stack(&detach_info, xsp, (void (*)(void *))sig_detach_go_native, false /*free_initstack*/, false /*do not return*/); ASSERT_NOT_REACHED(); } /* Returns whether to pass on to app */ static bool handle_suspend_signal(dcontext_t *dcontext, kernel_ucontext_t *ucxt, sigframe_rt_t *frame) { os_thread_data_t *ostd = (os_thread_data_t *)dcontext->os_field; kernel_sigset_t prevmask; sig_full_cxt_t sc_full; ASSERT(ostd != NULL); if (ostd->terminate) { /* PR 297902: exit this thread, without using the dstack */ /* For MacOS, we need a stack as 32-bit syscalls take args on the stack. * We go ahead and use it for x86 too for simpler sysenter return. * We don't have a lot of options: we're terminating, so we go ahead * and use the app stack. */ byte *app_xsp; if (IS_CLIENT_THREAD(dcontext)) app_xsp = (byte *)SIGCXT_FROM_UCXT(ucxt)->SC_XSP; else app_xsp = (byte *)get_mcontext(dcontext)->xsp; LOG(THREAD, LOG_ASYNCH, 2, "handle_suspend_signal: exiting\n"); ASSERT(app_xsp != NULL); notify_and_jmp_without_stack(&ostd->terminated, (byte *)dynamorio_sys_exit, app_xsp); ASSERT_NOT_REACHED(); return false; } if (!doing_detach && is_thread_currently_native(dcontext->thread_record) && !IS_CLIENT_THREAD(dcontext) IF_APP_EXPORTS(&&!dr_api_exit)) { if (!sig_take_over(ucxt)) return false; ASSERT_NOT_REACHED(); /* else, shouldn't return */ } /* If suspend_count is 0, we are not trying to suspend this thread * (os_thread_resume() may have already decremented suspend_count to 0, but * os_thread_suspend() will not send a signal until this thread unsets * ostd->suspended, so not having a lock around the suspend_count read is * ok), so pass signal to app. * If we are trying or have already suspended this thread, our own * os_thread_suspend() will not send a 2nd suspend signal until we are * completely resumed, so we can distinguish app uses of SUSPEND_SIGNAL. We * can't have a race between the read and write of suspended_sigcxt b/c * signals are blocked. It's fine to have a race and reorder the app's * signal w/ DR's. */ if (ostd->suspend_count == 0) return true; /* pass to app */ ASSERT(ostd->suspended_sigcxt == NULL); /* XXX: we're not setting DR_WHERE_SIGNAL_HANDLER in enough places. * It's trickier than other whereamis b/c we want to resume the * prior whereami when we return from the handler, but there are * complex control paths that do not always return. * We try to at least do it for the ksynch_wait here. */ dr_where_am_i_t prior_whereami = dcontext->whereami; dcontext->whereami = DR_WHERE_SIGNAL_HANDLER; sig_full_initialize(&sc_full, ucxt); ostd->suspended_sigcxt = &sc_full; LOG(THREAD, LOG_ASYNCH, 2, "handle_suspend_signal: suspended now\n"); /* We cannot use mutexes here as we have interrupted DR at an * arbitrary point! Thus we can't use the event_t routines. * However, the existing synch and check above prevent any * re-entrance here, and our cond vars target just a single thread, * so we can get away w/o a mutex. */ /* Notify os_thread_suspend that it can now return, as this thread is * officially suspended now and is ready for thread_{get,set}_mcontext. */ ASSERT(ksynch_get_value(&ostd->suspended) == 0); ksynch_set_value(&ostd->suspended, 1); ksynch_wake_all(&ostd->suspended); /* We're sitting on our sigaltstack w/ all signals blocked. We're * going to stay here but unblock all signals so we don't lose any * delivered while we're waiting. We're at a safe enough point (now * that we've set ostd->suspended: i#5779) to re-enter * master_signal_handler(). We use a mutex in thread_{suspend,resume} to * prevent our own re-suspension signal from arriving before we've * re-blocked on the resume. */ sigprocmask_syscall(SIG_SETMASK, SIGMASK_FROM_UCXT(ucxt), &prevmask, sizeof(ucxt->uc_sigmask)); /* i#96/PR 295561: use futex(2) if available */ while (ksynch_get_value(&ostd->wakeup) == 0) { /* Waits only if the wakeup flag is not set as 1. Return value * doesn't matter because the flag will be re-checked. */ ksynch_wait(&ostd->wakeup, 0, 0); if (ksynch_get_value(&ostd->wakeup) == 0) { /* If it still has to wait, give up the cpu. */ os_thread_yield(); } } LOG(THREAD, LOG_ASYNCH, 2, "handle_suspend_signal: awake now\n"); /* re-block so our exit from master_signal_handler is not interrupted */ sigprocmask_syscall(SIG_SETMASK, &prevmask, NULL, sizeof(prevmask)); ostd->suspended_sigcxt = NULL; /* Notify os_thread_resume that it can return now, which (assuming * suspend_count is back to 0) means it's then safe to re-suspend. */ ksynch_set_value(&ostd->suspended, 0); /*reset prior to signalling os_thread_resume*/ ksynch_set_value(&ostd->resumed, 1); ksynch_wake_all(&ostd->resumed); dcontext->whereami = prior_whereami; if (ostd->retakeover) { ostd->retakeover = false; sig_take_over(ucxt); /* shouldn't return for this case */ ASSERT_NOT_REACHED(); } else if (ostd->do_detach) { ostd->do_detach = false; sig_detach(dcontext, frame, &ostd->detached); /* no return */ ASSERT_NOT_REACHED(); } return false; /* do not pass to app */ } /* PR 206278: for try/except we need to save the signal mask */ void dr_setjmp_sigmask(dr_jmp_buf_t *buf) { /* i#226/PR 492568: we rely on the kernel storing the prior mask in the * signal frame, so we do not need to store it on every setjmp, which * can be a performance hit. */ #ifdef DEBUG sigprocmask_syscall(SIG_SETMASK, NULL, &buf->sigmask, sizeof(buf->sigmask)); #endif } /* i#61/PR 211530: nudge on Linux. * Determines whether this is a nudge signal, and if so queues up a nudge, * or is an app signal. Returns whether to pass the signal on to the app. */ static bool handle_nudge_signal(dcontext_t *dcontext, kernel_siginfo_t *siginfo, kernel_ucontext_t *ucxt) { sigcontext_t *sc = SIGCXT_FROM_UCXT(ucxt); nudge_arg_t *arg = (nudge_arg_t *)siginfo; instr_t instr; char buf[MAX_INSTR_LENGTH]; /* Distinguish a nudge from an app signal. An app using libc sigqueue() * will never have its signal mistaken as libc does not expose the kernel_siginfo_t * and always passes 0 for si_errno, so we're only worried beyond our * si_code check about an app using a raw syscall that is deliberately * trying to fool us. * While there is a lot of padding space in kernel_siginfo_t, the kernel doesn't * copy it through on SYS_rt_sigqueueinfo so we don't have room for any * dedicated magic numbers. The client id could function as a magic * number for client nudges, but I don't think we want to kill the app * if an external nudger types the client id wrong. */ LOG(THREAD, LOG_ASYNCH, 2, "%s: sig=%d code=%d errno=%d\n", __FUNCTION__, siginfo->si_signo, siginfo->si_code, siginfo->si_errno); if (siginfo->si_signo != NUDGESIG_SIGNUM /* PR 477454: remove the IF_NOT_VMX86 once we have nudge-arg support */ IF_NOT_VMX86(|| siginfo->si_code != SI_QUEUE || siginfo->si_errno == 0)) { return true; /* pass to app */ } #if defined(CLIENT_INTERFACE) && !defined(VMX86_SERVER) DODEBUG({ if (TEST(NUDGE_GENERIC(client), arg->nudge_action_mask) && !is_valid_client_id(arg->client_id)) { SYSLOG_INTERNAL_WARNING("received client nudge for invalid id=0x%x", arg->client_id); } }); #endif if (dynamo_exited || !dynamo_initialized || dcontext == NULL) { /* Ignore the nudge: too early, or too late. * Xref Windows handling of such cases in nudge.c: old case 5702, etc. * We do this before the illegal-instr check b/c it's unsafe to decode * if too early or too late. */ SYSLOG_INTERNAL_WARNING("too-early or too-late nudge: ignoring"); return false; /* do not pass to app */ } /* As a further check, try to detect whether this was raised synchronously * from a real illegal instr: though si_code for that should not be * SI_QUEUE. It's possible a nudge happened to come at a bad instr before * it faulted, or maybe the instr after a syscall or other wait spot is * illegal, but we'll live with that risk. */ ASSERT(NUDGESIG_SIGNUM == SIGILL); /* else this check makes no sense */ instr_init(dcontext, &instr); if (d_r_safe_read((byte *)sc->SC_XIP, sizeof(buf), buf) && (decode(dcontext, (byte *)buf, &instr) == NULL || /* check for ud2 (xref PR 523161) */ instr_is_undefined(&instr))) { LOG(THREAD, LOG_ASYNCH, 2, "%s: real illegal instr @" PFX "\n", __FUNCTION__, sc->SC_XIP); DOLOG(2, LOG_ASYNCH, { disassemble_with_bytes(dcontext, (byte *)sc->SC_XIP, THREAD); }); instr_free(dcontext, &instr); return true; /* pass to app */ } instr_free(dcontext, &instr); #ifdef VMX86_SERVER /* Treat as a client nudge until we have PR 477454 */ if (siginfo->si_errno == 0) { arg->version = NUDGE_ARG_CURRENT_VERSION; arg->flags = 0; arg->nudge_action_mask = NUDGE_GENERIC(client); arg->client_id = 0; arg->client_arg = 0; } #endif LOG(THREAD, LOG_ASYNCH, 1, "received nudge version=%u flags=0x%x mask=0x%x id=0x%08x " "arg=0x" ZHEX64_FORMAT_STRING "\n", arg->version, arg->flags, arg->nudge_action_mask, arg->client_id, arg->client_arg); SYSLOG_INTERNAL_INFO("received nudge mask=0x%x id=0x%08x arg=0x" ZHEX64_FORMAT_STRING, arg->nudge_action_mask, arg->client_id, arg->client_arg); /* We need to handle the nudge at a safe, nolinking spot */ if (safe_is_in_fcache(dcontext, (byte *)sc->SC_XIP, (byte *)sc->SC_XSP) && dcontext->interrupted_for_nudge == NULL) { /* We unlink the interrupted fragment and skip any inlined syscalls to * bound the nudge delivery time. If we already unlinked one we assume * that's sufficient. */ fragment_t wrapper; fragment_t *f = fragment_pclookup(dcontext, (byte *)sc->SC_XIP, &wrapper); if (f != NULL) { if (unlink_fragment_for_signal(dcontext, f, (byte *)sc->SC_XIP)) dcontext->interrupted_for_nudge = f; } } /* No lock is needed since thread-private and this signal is blocked now */ nudge_add_pending(dcontext, arg); return false; /* do not pass to app */ }
1
17,994
It seems like it's too big now: can we remove signal_frame_extra_size from line 537? That should only be needed when placing xstate separately. It seems like it isn't needed at all for pending? Also, if we have special heap align forward for us, we don't need this align here either.
DynamoRIO-dynamorio
c
@@ -128,9 +128,12 @@ catch # fortunately, using PS with stdin input_method should never happen if input_method == 'powershell' conn.execute(<<-PS) -$private:taskArgs = Get-ContentAsJson ( +$private:tempArgs = Get-ContentAsJson ( $utf8.GetString([System.Convert]::FromBase64String('#{Base64.encode64(JSON.dump(arguments))}')) ) +$allowedArgs = (Get-Command "#{remote_path}").Parameters.Keys +$private:taskArgs = @{} +$private:tempArgs.Keys | ? { $allowedArgs -contains $_ } | % { $private:taskArgs[$_] = $private:tempArgs[$_] } try { & "#{remote_path}" @taskArgs } catch { Write-Error $_.Exception; exit 1 } PS else
1
# frozen_string_literal: true require 'bolt/transport/base' module Bolt module Transport class WinRM < Base PS_ARGS = %w[ -NoProfile -NonInteractive -NoLogo -ExecutionPolicy Bypass ].freeze def self.options %w[port user password connect-timeout ssl ssl-verify tmpdir cacert extensions] end PROVIDED_FEATURES = ['powershell'].freeze def self.validate(options) ssl_flag = options['ssl'] unless !!ssl_flag == ssl_flag raise Bolt::ValidationError, 'ssl option must be a Boolean true or false' end ssl_verify_flag = options['ssl-verify'] unless !!ssl_verify_flag == ssl_verify_flag raise Bolt::ValidationError, 'ssl-verify option must be a Boolean true or false' end timeout_value = options['connect-timeout'] unless timeout_value.is_a?(Integer) || timeout_value.nil? error_msg = "connect-timeout value must be an Integer, received #{timeout_value}:#{timeout_value.class}" raise Bolt::ValidationError, error_msg end end def initialize super require 'winrm' require 'winrm-fs' end def with_connection(target) conn = Connection.new(target) conn.connect yield conn ensure begin conn&.disconnect rescue StandardError => ex logger.info("Failed to close connection to #{target.uri} : #{ex.message}") end end def upload(target, source, destination, _options = {}) with_connection(target) do |conn| conn.write_remote_file(source, destination) Bolt::Result.for_upload(target, source, destination) end end def run_command(target, command, _options = {}) with_connection(target) do |conn| output = conn.execute(command) Bolt::Result.for_command(target, output.stdout.string, output.stderr.string, output.exit_code) end end def run_script(target, script, arguments, _options = {}) with_connection(target) do |conn| conn.with_remote_file(script) do |remote_path| if powershell_file?(remote_path) mapped_args = arguments.map do |a| "$invokeArgs.ArgumentList += @'\n#{a}\n'@" end.join("\n") output = conn.execute(<<-PS) $invokeArgs = @{ ScriptBlock = (Get-Command "#{remote_path}").ScriptBlock ArgumentList = @() } #{mapped_args} try { Invoke-Command @invokeArgs } catch { Write-Error $_.Exception exit 1 } PS else path, args = *process_from_extension(remote_path) args += escape_arguments(arguments) output = conn.execute_process(path, args) end Bolt::Result.for_command(target, output.stdout.string, output.stderr.string, output.exit_code) end end end def run_task(target, task, arguments, _options = {}) executable = target.select_impl(task, PROVIDED_FEATURES) raise "No suitable implementation of #{task.name} for #{target.name}" unless executable input_method = task.input_method input_method ||= powershell_file?(executable) ? 'powershell' : 'both' with_connection(target) do |conn| if STDIN_METHODS.include?(input_method) stdin = JSON.dump(arguments) end if ENVIRONMENT_METHODS.include?(input_method) arguments.each do |(arg, val)| cmd = "[Environment]::SetEnvironmentVariable('PT_#{arg}', @'\n#{val}\n'@)" result = conn.execute(cmd) if result.exit_code != 0 raise EnvironmentVarError(var, value) end end end conn.with_remote_file(executable) do |remote_path| output = if powershell_file?(remote_path) && stdin.nil? # NOTE: cannot redirect STDIN to a .ps1 script inside of PowerShell # must create new powershell.exe process like other interpreters # fortunately, using PS with stdin input_method should never happen if input_method == 'powershell' conn.execute(<<-PS) $private:taskArgs = Get-ContentAsJson ( $utf8.GetString([System.Convert]::FromBase64String('#{Base64.encode64(JSON.dump(arguments))}')) ) try { & "#{remote_path}" @taskArgs } catch { Write-Error $_.Exception; exit 1 } PS else conn.execute(%(try { & "#{remote_path}" } catch { Write-Error $_.Exception; exit 1 })) end else path, args = *process_from_extension(remote_path) conn.execute_process(path, args, stdin) end Bolt::Result.for_task(target, output.stdout.string, output.stderr.string, output.exit_code) end end end def powershell_file?(path) Pathname(path).extname.casecmp('.ps1').zero? end def process_from_extension(path) case Pathname(path).extname.downcase when '.rb' [ 'ruby.exe', ['-S', "\"#{path}\""] ] when '.ps1' [ 'powershell.exe', [*PS_ARGS, '-File', "\"#{path}\""] ] when '.pp' [ 'puppet.bat', ['apply', "\"#{path}\""] ] else # Run the script via cmd, letting Windows extension handling determine how [ 'cmd.exe', ['/c', "\"#{path}\""] ] end end def escape_arguments(arguments) arguments.map do |arg| if arg =~ / / "\"#{arg}\"" else arg end end end end end end require 'bolt/transport/winrm/connection'
1
8,873
Just double checked the `-in` operator. It's PS3 only, so we might want to change `$_ -in $allowedArgs` to `$allowedArgs -contains $_`
puppetlabs-bolt
rb
@@ -152,6 +152,14 @@ class StartButton(IAccessible): states = super(StartButton, self).states states.discard(controlTypes.STATE_SELECTED) return states + +class UIProperty(UIA): + #Used for columns in Windows Explorer Details view. + #These can contain dates that include unwanted left-to-right and right-to-left indicator characters. + + def _get_value(self): + value = super(UIProperty, self).value + return value.replace(u'\u200E','').replace(u'\u200F','') class AppModule(appModuleHandler.AppModule):
1
#appModules/explorer.py #A part of NonVisual Desktop Access (NVDA) #Copyright (C) 2006-2015 NV Access Limited, Joseph Lee #This file is covered by the GNU General Public License. #See the file COPYING for more details. from comtypes import COMError import time import appModuleHandler import controlTypes import winUser import api import speech import eventHandler import mouseHandler from NVDAObjects.window import Window from NVDAObjects.IAccessible import sysListView32, IAccessible, List from NVDAObjects.UIA import UIA # Suppress incorrect Win 10 Task switching window focus class MultitaskingViewFrameWindow(UIA): shouldAllowUIAFocusEvent=False # suppress focus ancestry for task switching list items if alt is held down (alt+tab) class MultitaskingViewFrameListItem(UIA): def _get_container(self): if winUser.getAsyncKeyState(winUser.VK_MENU)&32768: return api.getDesktopObject() else: return super(MultitaskingViewFrameListItem,self).container # support for Win8 start screen search suggestions. class SuggestionListItem(UIA): def event_UIA_elementSelected(self): speech.cancelSpeech() api.setNavigatorObject(self) self.reportFocus() super(SuggestionListItem,self).event_UIA_elementSelected() #win8hack: Class to disable incorrect focus on windows 8 search box (containing the already correctly focused edit field) class SearchBoxClient(IAccessible): shouldAllowIAccessibleFocusEvent=False #Class for menu items for Windows Places and Frequently used Programs (in start menu) class SysListView32MenuItem(sysListView32.ListItemWithoutColumnSupport): #When focus moves to these items, an extra focus is fired on the parent #However NVDA redirects it to the real focus. #But this means double focus events on the item, so filter the second one out #Ticket #474 def _get_shouldAllowIAccessibleFocusEvent(self): res=super(SysListView32MenuItem,self).shouldAllowIAccessibleFocusEvent if not res: return False focus=eventHandler.lastQueuedFocusObject if type(focus)!=type(self) or (self.event_windowHandle,self.event_objectID,self.event_childID)!=(focus.event_windowHandle,focus.event_objectID,focus.event_childID): return True return False class ClassicStartMenu(Window): # Override the name, as Windows names this the "Application" menu contrary to all documentation. # Translators: The title of Start menu/screen in your language (only the word start). name = _("Start") def event_gainFocus(self): # In Windows XP, the Start button will get focus first, so silence this. speech.cancelSpeech() super(ClassicStartMenu, self).event_gainFocus() class NotificationArea(IAccessible): """The Windows notification area, a.k.a. system tray. """ def event_gainFocus(self): if mouseHandler.lastMouseEventTime < time.time() - 0.2: # This focus change was not caused by a mouse event. # If the mouse is on another toolbar control, the notification area toolbar will rudely # bounce the focus back to the object under the mouse after a brief pause. # Moving the mouse to the focus object isn't a good solution because # sometimes, the focus can't be moved away from the object under the mouse. # Therefore, move the mouse out of the way. winUser.setCursorPos(0, 0) if self.role == controlTypes.ROLE_TOOLBAR: # Sometimes, the toolbar itself receives the focus instead of the focused child. # However, the focused child still has the focused state. for child in self.children: if child.hasFocus: # Redirect the focus to the focused child. eventHandler.executeEvent("gainFocus", child) return # We've really landed on the toolbar itself. # This was probably caused by moving the mouse out of the way in a previous focus event. # This previous focus event is no longer useful, so cancel speech. speech.cancelSpeech() if eventHandler.isPendingEvents("gainFocus"): return super(NotificationArea, self).event_gainFocus() class GridTileElement(UIA): role=controlTypes.ROLE_TABLECELL def _get_description(self): name=self.name descriptionStrings=[] for child in self.children: description=child.basicText if not description or description==name: continue descriptionStrings.append(description) return " ".join(descriptionStrings) return description class GridListTileElement(UIA): role=controlTypes.ROLE_TABLECELL description=None class GridGroup(UIA): """A group in the Windows 8 Start Menu. """ presentationType=UIA.presType_content #Normally the name is the first tile which is rather redundant #However some groups have custom header text which should be read instead def _get_name(self): child=self.firstChild if isinstance(child,UIA): try: automationID=child.UIAElement.currentAutomationID except COMError: automationID=None if automationID=="GridListGroupHeader": return child.name class ImmersiveLauncher(UIA): #When the win8 start screen openes, focus correctly goes to the first tile, but then incorrectly back to the root of the window. #Ignore focus events on this object. shouldAllowUIAFocusEvent=False class StartButton(IAccessible): """For Windows 8.1 and 10 RTM Start buttons to be recognized as proper buttons and to suppress selection announcement.""" role = controlTypes.ROLE_BUTTON def _get_states(self): # #5178: Selection announcement should be suppressed. # Borrowed from Mozilla objects in NVDAObjects/IAccessible/Mozilla.py. states = super(StartButton, self).states states.discard(controlTypes.STATE_SELECTED) return states class AppModule(appModuleHandler.AppModule): def chooseNVDAObjectOverlayClasses(self, obj, clsList): windowClass = obj.windowClassName role = obj.role if windowClass in ("Search Box","UniversalSearchBand") and role==controlTypes.ROLE_PANE and isinstance(obj,IAccessible): clsList.insert(0,SearchBoxClient) return if windowClass == "ToolbarWindow32" and role == controlTypes.ROLE_POPUPMENU: parent = obj.parent if parent and parent.windowClassName == "SysPager" and obj.windowStyle & 0x80: clsList.insert(0, ClassicStartMenu) return if windowClass == "SysListView32" and role == controlTypes.ROLE_MENUITEM: clsList.insert(0, SysListView32MenuItem) return if windowClass == "ToolbarWindow32": # Check whether this is the notification area, a.k.a. system tray. if isinstance(obj.parent, ClassicStartMenu): return #This can't be a notification area try: # The toolbar's immediate parent is its window object, so we need to go one further. toolbarParent = obj.parent.parent if role != controlTypes.ROLE_TOOLBAR: # Toolbar item. toolbarParent = toolbarParent.parent except AttributeError: toolbarParent = None if toolbarParent and toolbarParent.windowClassName == "SysPager": clsList.insert(0, NotificationArea) return # #5178: Start button in Windows 8.1 and 10 RTM should not have been a list in the first place. if windowClass == "Start" and role in (controlTypes.ROLE_LIST, controlTypes.ROLE_BUTTON): if role == controlTypes.ROLE_LIST: clsList.remove(List) clsList.insert(0, StartButton) if isinstance(obj, UIA): uiaClassName = obj.UIAElement.cachedClassName if uiaClassName == "GridTileElement": clsList.insert(0, GridTileElement) elif uiaClassName == "GridListTileElement": clsList.insert(0, GridListTileElement) elif uiaClassName == "GridGroup": clsList.insert(0, GridGroup) elif uiaClassName == "ImmersiveLauncher" and role == controlTypes.ROLE_PANE: clsList.insert(0, ImmersiveLauncher) elif uiaClassName=="ListViewItem" and obj.UIAElement.cachedAutomationId.startswith('Suggestion_'): clsList.insert(0,SuggestionListItem) elif uiaClassName=="MultitaskingViewFrame" and role==controlTypes.ROLE_WINDOW: clsList.insert(0,MultitaskingViewFrameWindow) elif obj.windowClassName=="MultitaskingViewFrame" and role==controlTypes.ROLE_LISTITEM: clsList.insert(0,MultitaskingViewFrameListItem) def event_NVDAObject_init(self, obj): windowClass = obj.windowClassName role = obj.role if windowClass == "ToolbarWindow32" and role == controlTypes.ROLE_POPUPMENU: parent = obj.parent if parent and parent.windowClassName == "SysPager" and not (obj.windowStyle & 0x80): # This is the menu for a group of icons on the task bar, which Windows stupidly names "Application". obj.name = None return if windowClass == "#32768": # Standard menu. parent = obj.parent if parent and not parent.parent: # Context menu. # We don't trust the names that Explorer gives to context menus, so better to have no name at all. obj.name = None return if windowClass == "DV2ControlHost" and role == controlTypes.ROLE_PANE: # Windows Vista/7 start menu. obj.presentationType=obj.presType_content obj.isPresentableFocusAncestor = True # In Windows 7, the description of this pane is extremely verbose help text, so nuke it. obj.description = None return #The Address bar is embedded inside a progressbar, how strange. #Lets hide that if windowClass=="msctls_progress32" and winUser.getClassName(winUser.getAncestor(obj.windowHandle,winUser.GA_PARENT))=="Address Band Root": obj.presentationType=obj.presType_layout def event_gainFocus(self, obj, nextHandler): wClass = obj.windowClassName if wClass == "ToolbarWindow32" and obj.role == controlTypes.ROLE_MENUITEM and obj.parent.role == controlTypes.ROLE_MENUBAR and eventHandler.isPendingEvents("gainFocus"): # When exiting a menu, Explorer fires focus on the top level menu item before it returns to the previous focus. # Unfortunately, this focus event always occurs in a subsequent cycle, so the event limiter doesn't eliminate it. # Therefore, if there is a pending focus event, don't bother handling this event. return if wClass == "ForegroundStaging": # #5116: The Windows 10 Task View fires foreground/focus on this weird invisible window before and after it appears. # This causes NVDA to report "unknown", so ignore it. # We can't do this using shouldAllowIAccessibleFocusEvent because this isn't checked for foreground. return nextHandler()
1
17,642
Might as well use translate here, as @jcsteh suggested
nvaccess-nvda
py
@@ -145,8 +145,9 @@ class DimensionedPlot(Plot): show_title = param.Boolean(default=True, doc=""" Whether to display the plot title.""") - title_format = param.String(default="{label} {group}", doc=""" - The formatting string for the title of this plot.""") + title_format = param.String(default="{label} {group}\n{dimensions}", doc=""" + The formatting string for the title of this plot, allows defining + a label group separator and dimension labels.""") normalize = param.Boolean(default=True, doc=""" Whether to compute ranges across all Elements at this level
1
""" Public API for all plots supported by HoloViews, regardless of plotting package or backend. Every plotting classes must be a subclass of this Plot baseclass. """ from itertools import groupby, product from collections import Counter import numpy as np import param from ..core import OrderedDict from ..core import util, traversal from ..core.element import Element from ..core.overlay import Overlay, CompositeOverlay from ..core.layout import Empty, NdLayout, Layout from ..core.options import Store, Compositor from ..core.spaces import HoloMap, DynamicMap from ..element import Table from .util import get_dynamic_mode, initialize_sampled class Plot(param.Parameterized): """ Base class of all Plot classes in HoloViews, designed to be general enough to use any plotting package or backend. """ # A list of style options that may be supplied to the plotting # call style_opts = [] # Sometimes matplotlib doesn't support the common aliases. # Use this list to disable any invalid style options _disabled_opts = [] def initialize_plot(self, ranges=None): """ Initialize the matplotlib figure. """ raise NotImplementedError def update(self, key): """ Update the internal state of the Plot to represent the given key tuple (where integers represent frames). Returns this state. """ return self.state @property def state(self): """ The plotting state that gets updated via the update method and used by the renderer to generate output. """ raise NotImplementedError def __len__(self): """ Returns the total number of available frames. """ raise NotImplementedError @classmethod def lookup_options(cls, obj, group): return Store.lookup_options(cls.renderer.backend, obj, group) class PlotSelector(object): """ Proxy that allows dynamic selection of a plotting class based on a function of the plotted object. Behaves like a Plot class and presents the same parameterized interface. """ _disabled_opts = [] def __init__(self, selector, plot_classes, allow_mismatch=False): """ The selector function accepts a component instance and returns the appropriate key to index plot_classes dictionary. """ self.selector = selector self.plot_classes = OrderedDict(plot_classes) interface = self._define_interface(self.plot_classes.values(), allow_mismatch) self.style_opts, self.plot_options = interface def _define_interface(self, plots, allow_mismatch): parameters = [{k:v.precedence for k,v in plot.params().items() if ((v.precedence is None) or (v.precedence >= 0))} for plot in plots] param_sets = [set(params.keys()) for params in parameters] if not allow_mismatch and not all(pset == param_sets[0] for pset in param_sets): raise Exception("All selectable plot classes must have identical plot options.") styles= [plot.style_opts for plot in plots] if not allow_mismatch and not all(style == styles[0] for style in styles): raise Exception("All selectable plot classes must have identical style options.") return styles[0], parameters[0] def __call__(self, obj, **kwargs): key = self.selector(obj) if key not in self.plot_classes: msg = "Key %s returned by selector not in set: %s" raise Exception(msg % (key, ', '.join(self.plot_classes.keys()))) return self.plot_classes[key](obj, **kwargs) def __setattr__(self, label, value): try: return super(PlotSelector, self).__setattr__(label, value) except: raise Exception("Please set class parameters directly on classes %s" % ', '.join(str(cls) for cls in self.__dict__['plot_classes'].values())) def params(self): return self.plot_options class DimensionedPlot(Plot): """ DimensionedPlot implements a number of useful methods to compute dimension ranges and titles containing the dimension values. """ fontsize = param.Parameter(default=None, allow_None=True, doc=""" Specifies various fontsizes of the displayed text. Finer control is available by supplying a dictionary where any unmentioned keys reverts to the default sizes, e.g: {'ticks':20, 'title':15, 'ylabel':5, 'xlabel':5, 'legend':8, 'legend_title':13} You can set the fontsize of both 'ylabel' and 'xlabel' together using the 'labels' key.""") show_title = param.Boolean(default=True, doc=""" Whether to display the plot title.""") title_format = param.String(default="{label} {group}", doc=""" The formatting string for the title of this plot.""") normalize = param.Boolean(default=True, doc=""" Whether to compute ranges across all Elements at this level of plotting. Allows selecting normalization at different levels for nested data containers.""") projection = param.ObjectSelector(default=None) def __init__(self, keys=None, dimensions=None, layout_dimensions=None, uniform=True, subplot=False, adjoined=None, layout_num=0, style=None, subplots=None, dynamic=False, **params): self.subplots = subplots self.adjoined = adjoined self.dimensions = dimensions self.layout_num = layout_num self.layout_dimensions = layout_dimensions self.subplot = subplot self.keys = keys self.uniform = uniform self.dynamic = dynamic self.drawn = False self.handles = {} self.group = None self.label = None self.current_frame = None self.current_key = None self.ranges = {} params = {k: v for k, v in params.items() if k in self.params()} super(DimensionedPlot, self).__init__(**params) def __getitem__(self, frame): """ Get the state of the Plot for a given frame number. """ if not self.dynamic == 'open' and isinstance(frame, int) and frame > len(self): self.warning("Showing last frame available: %d" % len(self)) if not self.drawn: self.handles['fig'] = self.initialize_plot() if not self.dynamic == 'open' and not isinstance(frame, tuple): frame = self.keys[frame] self.update_frame(frame) return self.state def _get_frame(self, key): """ Required on each MPLPlot type to get the data corresponding just to the current frame out from the object. """ pass def matches(self, spec): """ Matches a specification against the current Plot. """ if callable(spec) and not isinstance(spec, type): return spec(self) elif isinstance(spec, type): return isinstance(self, spec) else: raise ValueError("Matching specs have to be either a type or a callable.") def traverse(self, fn=None, specs=None, full_breadth=True): """ Traverses any nested DimensionedPlot returning a list of all plots that match the specs. The specs should be supplied as a list of either Plot types or callables, which should return a boolean given the plot class. """ accumulator = [] matches = specs is None if not matches: for spec in specs: matches = self.matches(spec) if matches: break if matches: accumulator.append(fn(self) if fn else self) # Assumes composite objects are iterables if hasattr(self, 'subplots') and self.subplots: for el in self.subplots.values(): accumulator += el.traverse(fn, specs, full_breadth) if not full_breadth: break return accumulator def _frame_title(self, key, group_size=2, separator='\n'): """ Returns the formatted dimension group strings for a particular frame. """ if self.dynamic == 'open' and self.current_key: key = self.current_key if self.layout_dimensions is not None: dimensions, key = zip(*self.layout_dimensions.items()) elif not self.dynamic and (not self.uniform or len(self) == 1) or self.subplot: return '' else: key = key if isinstance(key, tuple) else (key,) dimensions = self.dimensions dimension_labels = [dim.pprint_value_string(k) for dim, k in zip(dimensions, key)] groups = [', '.join(dimension_labels[i*group_size:(i+1)*group_size]) for i in range(len(dimension_labels))] return util.safe_unicode(separator.join(g for g in groups if g)) def _fontsize(self, key, label='fontsize', common=True): """ To be used as kwargs e.g: **self._fontsize('title') """ if not self.fontsize: return {} if isinstance(self.fontsize, dict): if key in self.fontsize: return {label:self.fontsize[key]} elif key in ['ylabel', 'xlabel'] and 'labels' in self.fontsize: return {label:self.fontsize['labels']} else: return {} return {label:self.fontsize} if common else {} def compute_ranges(self, obj, key, ranges): """ Given an object, a specific key and the normalization options this method will find the specified normalization options on the appropriate OptionTree, group the elements according to the selected normalization option (i.e. either per frame or over the whole animation) and finally compute the dimension ranges in each group. The new set of ranges is returned. """ all_table = all(isinstance(el, Table) for el in obj.traverse(lambda x: x, [Element])) if obj is None or not self.normalize or all_table: return OrderedDict() # Get inherited ranges ranges = self.ranges if ranges is None else dict(ranges) # Get element identifiers from current object and resolve # with selected normalization options norm_opts = self._get_norm_opts(obj) # Traverse displayed object if normalization applies # at this level, and ranges for the group have not # been supplied from a composite plot elements = [] return_fn = lambda x: x if isinstance(x, Element) else None for group, (axiswise, framewise) in norm_opts.items(): elements = [] # Skip if ranges are cached or already computed by a # higher-level container object. framewise = framewise or self.dynamic if group in ranges and (not framewise or ranges is not self.ranges): continue elif not framewise: # Traverse to get all elements elements = obj.traverse(return_fn, [group]) elif key is not None: # Traverse to get elements for each frame frame = self._get_frame(key) elements = [] if frame is None else frame.traverse(return_fn, [group]) if not axiswise or ((not framewise or len(elements) == 1) and isinstance(obj, HoloMap)): # Compute new ranges self._compute_group_range(group, elements, ranges) self.ranges.update(ranges) return ranges def _get_norm_opts(self, obj): """ Gets the normalization options for a LabelledData object by traversing the object for to find elements and their ids. The id is then used to select the appropriate OptionsTree, accumulating the normalization options into a dictionary. Returns a dictionary of normalization options for each element in the tree. """ norm_opts = {} # Get all elements' type.group.label specs and ids type_val_fn = lambda x: (x.id, (type(x).__name__, util.group_sanitizer(x.group, escape=False), util.label_sanitizer(x.label, escape=False))) \ if isinstance(x, Element) else None element_specs = {(idspec[0], idspec[1]) for idspec in obj.traverse(type_val_fn) if idspec is not None} # Group elements specs by ID and override normalization # options sequentially key_fn = lambda x: -1 if x[0] is None else x[0] id_groups = groupby(sorted(element_specs, key=key_fn), key_fn) for gid, element_spec_group in id_groups: gid = None if gid == -1 else gid group_specs = [el for _, el in element_spec_group] backend = self.renderer.backend optstree = Store.custom_options( backend=backend).get(gid, Store.options(backend=backend)) # Get the normalization options for the current id # and match against customizable elements for opts in optstree: path = tuple(opts.path.split('.')[1:]) applies = any(path == spec[:i] for spec in group_specs for i in range(1, 4)) if applies and 'norm' in opts.groups: nopts = opts['norm'].options if 'axiswise' in nopts or 'framewise' in nopts: norm_opts.update({path: (nopts.get('axiswise', False), nopts.get('framewise', False))}) element_specs = [spec for eid, spec in element_specs] norm_opts.update({spec: (False, False) for spec in element_specs if not any(spec[:i] in norm_opts.keys() for i in range(1, 4))}) return norm_opts @staticmethod def _compute_group_range(group, elements, ranges): # Iterate over all elements in a normalization group # and accumulate their ranges into the supplied dictionary. elements = [el for el in elements if el is not None] group_ranges = OrderedDict() for el in elements: if isinstance(el, (Empty, Table)): continue for dim in el.dimensions(label=True): dim_range = el.range(dim) if dim not in group_ranges: group_ranges[dim] = [] group_ranges[dim].append(dim_range) ranges[group] = OrderedDict((k, util.max_range(v)) for k, v in group_ranges.items()) @classmethod def _deep_options(cls, obj, opt_type, opts, specs=None): """ Traverses the supplied object getting all options in opts for the specified opt_type and specs """ lookup = lambda x: ((type(x).__name__, x.group, x.label), {o: cls.lookup_options(x, opt_type).options.get(o, None) for o in opts}) return dict(obj.traverse(lookup, specs)) def update(self, key): if len(self) == 1 and key == 0 and not self.drawn: return self.initialize_plot() return self.__getitem__(key) def __len__(self): """ Returns the total number of available frames. """ return len(self.keys) class GenericElementPlot(DimensionedPlot): """ Plotting baseclass to render contents of an Element. Implements methods to get the correct frame given a HoloMap, axis labels and extents and titles. """ apply_ranges = param.Boolean(default=True, doc=""" Whether to compute the plot bounds from the data itself.""") apply_extents = param.Boolean(default=True, doc=""" Whether to apply extent overrides on the Elements""") def __init__(self, element, keys=None, ranges=None, dimensions=None, overlaid=0, cyclic_index=0, zorder=0, style=None, overlay_dims={}, **params): self.zorder = zorder self.cyclic_index = cyclic_index self.overlaid = overlaid self.overlay_dims = overlay_dims if not isinstance(element, (HoloMap, DynamicMap)): self.hmap = HoloMap(initial_items=(0, element), kdims=['Frame'], id=element.id) else: self.hmap = element self.style = self.lookup_options(self.hmap.last, 'style') if style is None else style dimensions = self.hmap.kdims if dimensions is None else dimensions keys = keys if keys else list(self.hmap.data.keys()) plot_opts = self.lookup_options(self.hmap.last, 'plot').options dynamic = False if not isinstance(element, DynamicMap) or element.sampled else element.mode super(GenericElementPlot, self).__init__(keys=keys, dimensions=dimensions, dynamic=dynamic, **dict(params, **plot_opts)) def _get_frame(self, key): if isinstance(self.hmap, DynamicMap) and self.overlaid and self.current_frame: self.current_key = key return self.current_frame elif self.dynamic: if isinstance(key, tuple): frame = self.hmap[key] elif key < self.hmap.counter: key = self.hmap.keys()[key] frame = self.hmap[key] elif key >= self.hmap.counter: frame = next(self.hmap) key = self.hmap.keys()[-1] if not isinstance(key, tuple): key = (key,) if not key in self.keys: self.keys.append(key) self.current_frame = frame self.current_key = key return frame if isinstance(key, int): key = self.hmap.keys()[min([key, len(self.hmap)-1])] if key == self.current_key: return self.current_frame else: self.current_key = key if self.uniform: if not isinstance(key, tuple): key = (key,) kdims = [d.name for d in self.hmap.kdims] if self.dimensions is None: dimensions = kdims else: dimensions = [d.name for d in self.dimensions] if kdims == ['Frame'] and kdims != dimensions: select = dict(Frame=0) else: select = {d: key[dimensions.index(d)] for d in kdims} else: select = dict(zip(self.hmap.dimensions('key', label=True), key)) try: selection = self.hmap.select((HoloMap, DynamicMap), **select) except KeyError: selection = None selection = selection.last if isinstance(selection, HoloMap) else selection self.current_frame = selection return selection def get_extents(self, view, ranges): """ Gets the extents for the axes from the current View. The globally computed ranges can optionally override the extents. """ ndims = len(view.dimensions()) num = 6 if self.projection == '3d' else 4 if self.apply_ranges: if ranges: dims = view.dimensions() x0, x1 = ranges[dims[0].name] if ndims > 1: y0, y1 = ranges[dims[1].name] else: y0, y1 = (np.NaN, np.NaN) if self.projection == '3d': z0, z1 = ranges[dims[2].name] else: x0, x1 = view.range(0) y0, y1 = view.range(1) if ndims > 1 else (np.NaN, np.NaN) if self.projection == '3d': z0, z1 = view.range(2) if self.projection == '3d': range_extents = (x0, y0, z0, x1, y1, z1) else: range_extents = (x0, y0, x1, y1) else: range_extents = (np.NaN,) * num if self.apply_extents: norm_opts = self.lookup_options(view, 'norm').options if norm_opts.get('framewise', False) or self.dynamic: extents = view.extents else: extent_list = self.hmap.traverse(lambda x: x.extents, [Element]) extents = util.max_extents(extent_list, self.projection == '3d') else: extents = (np.NaN,) * num return tuple(l1 if l2 is None or not np.isfinite(l2) else l2 for l1, l2 in zip(range_extents, extents)) def _axis_labels(self, view, subplots, xlabel=None, ylabel=None, zlabel=None): # Axis labels if isinstance(view, CompositeOverlay): bottom = view.values()[0] dims = bottom.dimensions() if isinstance(bottom, CompositeOverlay): dims = dims[bottom.ndims:] else: dims = view.dimensions() if dims and xlabel is None: xlabel = util.safe_unicode(str(dims[0])) if len(dims) >= 2 and ylabel is None: ylabel = util.safe_unicode(str(dims[1])) if self.projection == '3d' and len(dims) >= 3 and zlabel is None: zlabel = util.safe_unicode(str(dims[2])) return xlabel, ylabel, zlabel def _format_title(self, key, separator='\n'): frame = self._get_frame(key) if frame is None: return None type_name = type(frame).__name__ group = frame.group if frame.group != type_name else '' label = frame.label if self.layout_dimensions: title = '' else: title_format = util.safe_unicode(self.title_format) title = title_format.format(label=util.safe_unicode(label), group=util.safe_unicode(group), type=type_name) dim_title = self._frame_title(key, separator=separator) if not title or title.isspace(): return dim_title elif not dim_title or dim_title.isspace(): return title else: return separator.join([title, dim_title]) def update_frame(self, key, ranges=None): """ Set the plot(s) to the given frame number. Operates by manipulating the matplotlib objects held in the self._handles dictionary. If n is greater than the number of available frames, update using the last available frame. """ class GenericOverlayPlot(GenericElementPlot): """ Plotting baseclass to render (Nd)Overlay objects. It implements methods to handle the creation of ElementPlots, coordinating style groupings and zorder for all layers across a HoloMap. It also allows collapsing of layers via the Compositor. """ show_legend = param.Boolean(default=False, doc=""" Whether to show legend for the plot.""") style_grouping = param.Integer(default=2, doc="""The length of the type.group.label spec that will be used to group Elements into style groups, i.e. a style_grouping value of 1 will group just by type, a value of 2 will group by type and group and a value of 3 will group by the full specification.""") _passed_handles = [] def __init__(self, overlay, ranges=None, **params): super(GenericOverlayPlot, self).__init__(overlay, ranges=ranges, **params) # Apply data collapse self.hmap = Compositor.collapse(self.hmap, None, mode='data') self.hmap = self._apply_compositor(self.hmap, ranges, self.keys) self.subplots = self._create_subplots(ranges) def _apply_compositor(self, holomap, ranges=None, keys=None, dimensions=None): """ Given a HoloMap compute the appropriate (mapwise or framewise) ranges in order to apply the Compositor collapse operations in display mode (data collapse should already have happened). """ # Compute framewise normalization defaultdim = holomap.ndims == 1 and holomap.kdims[0].name != 'Frame' if keys and ranges and dimensions and not defaultdim: dim_inds = [dimensions.index(d) for d in holomap.kdims] sliced_keys = [tuple(k[i] for i in dim_inds) for k in keys] frame_ranges = OrderedDict([(slckey, self.compute_ranges(holomap, key, ranges[key])) for key, slckey in zip(keys, sliced_keys) if slckey in holomap.data.keys()]) else: mapwise_ranges = self.compute_ranges(holomap, None, None) frame_ranges = OrderedDict([(key, self.compute_ranges(holomap, key, mapwise_ranges)) for key in holomap.keys()]) ranges = frame_ranges.values() return Compositor.collapse(holomap, (ranges, frame_ranges.keys()), mode='display') def _create_subplots(self, ranges): subplots = OrderedDict() length = self.style_grouping ordering = util.layer_sort(self.hmap) keys, vmaps = self.hmap.split_overlays() group_fn = lambda x: (x.type.__name__, x.last.group, x.last.label) map_lengths = Counter() for m in vmaps: map_lengths[group_fn(m)[:length]] += 1 zoffset = 0 overlay_type = 1 if self.hmap.type == Overlay else 2 group_counter = Counter() for (key, vmap) in zip(keys, vmaps): vtype = type(vmap.last) plottype = Store.registry[self.renderer.backend].get(vtype, None) if plottype is None: self.warning("No plotting class for %s type and %s backend " "found. " % (vtype.__name__, self.renderer.backend)) continue if self.hmap.type == Overlay: style_key = (vmap.type.__name__,) + key else: if not isinstance(key, tuple): key = (key,) style_key = group_fn(vmap) + key group_key = style_key[:length] zorder = ordering.index(style_key) + zoffset cyclic_index = group_counter[group_key] group_counter[group_key] += 1 group_length = map_lengths[group_key] opts = {} if overlay_type == 2: opts['overlay_dims'] = OrderedDict(zip(self.hmap.last.kdims, key)) style = self.lookup_options(vmap.last, 'style').max_cycles(group_length) plotopts = dict(opts, keys=self.keys, style=style, cyclic_index=cyclic_index, zorder=self.zorder+zorder, ranges=ranges, overlaid=overlay_type, layout_dimensions=self.layout_dimensions, show_title=self.show_title, dimensions=self.dimensions, uniform=self.uniform, show_legend=self.show_legend, **{k: v for k, v in self.handles.items() if k in self._passed_handles}) if not isinstance(key, tuple): key = (key,) subplots[key] = plottype(vmap, **plotopts) if not isinstance(plottype, PlotSelector) and issubclass(plottype, GenericOverlayPlot): zoffset += len(set([k for o in vmap for k in o.keys()])) - 1 return subplots def get_extents(self, overlay, ranges): extents = [] items = overlay.items() for key, subplot in self.subplots.items(): layer = overlay.data.get(key, None) found = False if isinstance(self.hmap, DynamicMap) and layer is None: for i, (k, layer) in enumerate(items): if isinstance(layer, subplot.hmap.type): found = True break if not found: layer = None if layer and subplot.apply_ranges: if isinstance(layer, CompositeOverlay): sp_ranges = ranges else: sp_ranges = util.match_spec(layer, ranges) if ranges else {} extents.append(subplot.get_extents(layer, sp_ranges)) return util.max_extents(extents, self.projection == '3d') def _format_title(self, key, separator='\n'): frame = self._get_frame(key) if frame is None: return None type_name = type(frame).__name__ group = frame.group if frame.group != type_name else '' label = frame.label if self.layout_dimensions: title = '' else: title_format = util.safe_unicode(self.title_format) title = title_format.format(label=util.safe_unicode(label), group=util.safe_unicode(group), type=type_name) dim_title = self._frame_title(key, 2) if not title or title.isspace(): return dim_title elif not dim_title or dim_title.isspace(): return title else: return separator.join([title, dim_title]) class GenericCompositePlot(DimensionedPlot): def _get_frame(self, key): """ Creates a clone of the Layout with the nth-frame for each Element. """ layout_frame = self.layout.clone(shared_data=False) keyisint = isinstance(key, int) if not isinstance(key, tuple): key = (key,) nthkey_fn = lambda x: zip(tuple(x.name for x in x.kdims), list(x.data.keys())[min([key[0], len(x)-1])]) if key == self.current_key: return self.current_frame else: self.current_key = key for path, item in self.layout.items(): if self.dynamic == 'open': if keyisint: counts = item.traverse(lambda x: x.counter, (DynamicMap,)) if key[0] >= counts[0]: item.traverse(lambda x: next(x), (DynamicMap,)) dim_keys = item.traverse(nthkey_fn, (DynamicMap,))[0] else: dim_keys = zip([d.name for d in self.dimensions if d in item.dimensions('key')], key) self.current_key = tuple(k[1] for k in dim_keys) elif self.uniform: dim_keys = zip([d.name for d in self.dimensions if d in item.dimensions('key')], key) else: dim_keys = item.traverse(nthkey_fn, (HoloMap,))[0] if dim_keys: obj = item.select((HoloMap,), **dict(dim_keys)) if isinstance(obj, HoloMap) and len(obj) == 0: continue else: layout_frame[path] = obj else: layout_frame[path] = item self.current_frame = layout_frame return layout_frame def __len__(self): return len(self.keys) def _format_title(self, key, separator='\n'): dim_title = self._frame_title(key, 3, separator) layout = self.layout type_name = type(self.layout).__name__ group = util.safe_unicode(layout.group if layout.group != type_name else '') label = util.safe_unicode(layout.label) title = util.safe_unicode(self.title_format).format(label=label, group=group, type=type_name) title = '' if title.isspace() else title if not title: return dim_title elif not dim_title: return title else: return separator.join([title, dim_title]) class GenericLayoutPlot(GenericCompositePlot): """ A GenericLayoutPlot accepts either a Layout or a NdLayout and displays the elements in a cartesian grid in scanline order. """ def __init__(self, layout, **params): if not isinstance(layout, (NdLayout, Layout)): raise ValueError("GenericLayoutPlot only accepts Layout objects.") if len(layout.values()) == 0: raise ValueError("Cannot display empty layout") self.layout = layout self.subplots = {} self.rows, self.cols = layout.shape self.coords = list(product(range(self.rows), range(self.cols))) dynamic, sampled = get_dynamic_mode(layout) dimensions, keys = traversal.unique_dimkeys(layout) if sampled: initialize_sampled(layout, dimensions, keys[0]) uniform = traversal.uniform(layout) plotopts = self.lookup_options(layout, 'plot').options super(GenericLayoutPlot, self).__init__(keys=keys, dimensions=dimensions, uniform=uniform, dynamic=dynamic, **dict(plotopts, **params))
1
14,261
Definitely an improvement as long as the old tests pass (i.e backwards compatible).
holoviz-holoviews
py
@@ -22,11 +22,11 @@ package com.netflix.iceberg; import com.google.common.collect.Maps; import com.netflix.iceberg.exceptions.RuntimeIOException; import com.netflix.iceberg.io.FileIO; -import java.util.Map; import com.netflix.iceberg.io.LocationProvider; import org.junit.rules.TemporaryFolder; import java.io.IOException; +import java.util.Map; class LocalTableOperations implements TableOperations { private final TemporaryFolder temp;
1
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.netflix.iceberg; import com.google.common.collect.Maps; import com.netflix.iceberg.exceptions.RuntimeIOException; import com.netflix.iceberg.io.FileIO; import java.util.Map; import com.netflix.iceberg.io.LocationProvider; import org.junit.rules.TemporaryFolder; import java.io.IOException; class LocalTableOperations implements TableOperations { private final TemporaryFolder temp; private final FileIO io; private final Map<String, String> createdMetadataFilePaths = Maps.newHashMap(); LocalTableOperations(TemporaryFolder temp) { this.temp = temp; this.io = new TestTables.LocalFileIO(); } @Override public TableMetadata current() { throw new UnsupportedOperationException("Not implemented for tests"); } @Override public TableMetadata refresh() { throw new UnsupportedOperationException("Not implemented for tests"); } @Override public void commit(TableMetadata base, TableMetadata metadata) { throw new UnsupportedOperationException("Not implemented for tests"); } @Override public FileIO io() { return io; } @Override public String metadataFileLocation(String fileName) { return createdMetadataFilePaths.computeIfAbsent(fileName, name -> { try { return temp.newFile(name).getAbsolutePath(); } catch (IOException e) { throw new RuntimeIOException(e); } }); } @Override public LocationProvider locationProvider() { throw new UnsupportedOperationException("Not implemented for tests"); } @Override public long newSnapshotId() { throw new UnsupportedOperationException("Not implemented for tests"); } }
1
12,710
nit: non functional change
apache-iceberg
java
@@ -130,6 +130,17 @@ func main() { }() } + // Fail fast if the AWS credentials are not present. + awsCredentialsPath := os.Getenv("AWS_SHARED_CREDENTIALS_FILE") + if len(awsCredentialsPath) == 0 { + awsCredentialsPath = "/home/.aws/credentials" + } + _, err := os.Stat(awsCredentialsPath) + if err != nil { + setupLog.Error(err, "AWS credentials not found") + os.Exit(1) + } + ctrl.SetLogger(klogr.New()) // Machine and cluster operations can create enough events to trigger the event recorder spam filter // Setting the burst size higher ensures all events will be recorded and submitted to the API
1
/* Copyright 2018 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import ( "flag" "net/http" _ "net/http/pprof" "os" "time" "k8s.io/apimachinery/pkg/runtime" clientgoscheme "k8s.io/client-go/kubernetes/scheme" cgrecord "k8s.io/client-go/tools/record" "k8s.io/klog" "k8s.io/klog/klogr" infrav1alpha2 "sigs.k8s.io/cluster-api-provider-aws/api/v1alpha2" infrav1alpha3 "sigs.k8s.io/cluster-api-provider-aws/api/v1alpha3" "sigs.k8s.io/cluster-api-provider-aws/controllers" "sigs.k8s.io/cluster-api-provider-aws/pkg/record" clusterv1 "sigs.k8s.io/cluster-api/api/v1alpha3" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/controller" // +kubebuilder:scaffold:imports ) var ( scheme = runtime.NewScheme() setupLog = ctrl.Log.WithName("setup") ) func init() { _ = clientgoscheme.AddToScheme(scheme) _ = infrav1alpha2.AddToScheme(scheme) _ = infrav1alpha3.AddToScheme(scheme) _ = clusterv1.AddToScheme(scheme) // +kubebuilder:scaffold:scheme } func main() { klog.InitFlags(nil) var ( metricsAddr string enableLeaderElection bool watchNamespace string profilerAddress string awsClusterConcurrency int awsMachineConcurrency int syncPeriod time.Duration webhookPort int ) flag.StringVar( &metricsAddr, "metrics-addr", ":8080", "The address the metric endpoint binds to.", ) flag.BoolVar( &enableLeaderElection, "enable-leader-election", false, "Enable leader election for controller manager. Enabling this will ensure there is only one active controller manager.", ) flag.StringVar( &watchNamespace, "namespace", "", "Namespace that the controller watches to reconcile cluster-api objects. If unspecified, the controller watches for cluster-api objects across all namespaces.", ) flag.StringVar( &profilerAddress, "profiler-address", "", "Bind address to expose the pprof profiler (e.g. localhost:6060)", ) flag.IntVar(&awsClusterConcurrency, "awscluster-concurrency", 2, "Number of AWSClusters to process simultaneously", ) flag.IntVar(&awsMachineConcurrency, "awsmachine-concurrency", 2, "Number of AWSMachines to process simultaneously", ) flag.DurationVar(&syncPeriod, "sync-period", 10*time.Minute, "The minimum interval at which watched resources are reconciled (e.g. 15m)", ) flag.IntVar(&webhookPort, "webhook-port", 9443, "Webhook server port", ) flag.Parse() if watchNamespace != "" { setupLog.Info("Watching cluster-api objects only in namespace for reconciliation", "namespace", watchNamespace) } if profilerAddress != "" { setupLog.Info("Profiler listening for requests", "profiler-address", profilerAddress) go func() { setupLog.Error(http.ListenAndServe(profilerAddress, nil), "listen and serve error") }() } ctrl.SetLogger(klogr.New()) // Machine and cluster operations can create enough events to trigger the event recorder spam filter // Setting the burst size higher ensures all events will be recorded and submitted to the API broadcaster := cgrecord.NewBroadcasterWithCorrelatorOptions(cgrecord.CorrelatorOptions{ BurstSize: 100, }) mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{ Scheme: scheme, MetricsBindAddress: metricsAddr, LeaderElection: enableLeaderElection, LeaderElectionID: "controller-leader-election-capa", SyncPeriod: &syncPeriod, Namespace: watchNamespace, EventBroadcaster: broadcaster, Port: webhookPort, }) if err != nil { setupLog.Error(err, "unable to start manager") os.Exit(1) } // Initialize event recorder. record.InitFromRecorder(mgr.GetEventRecorderFor("aws-controller")) if err = (&controllers.AWSMachineReconciler{ Client: mgr.GetClient(), Log: ctrl.Log.WithName("controllers").WithName("AWSMachine"), Recorder: mgr.GetEventRecorderFor("awsmachine-controller"), }).SetupWithManager(mgr, controller.Options{MaxConcurrentReconciles: awsMachineConcurrency}); err != nil { setupLog.Error(err, "unable to create controller", "controller", "AWSMachine") os.Exit(1) } if err = (&controllers.AWSClusterReconciler{ Client: mgr.GetClient(), Log: ctrl.Log.WithName("controllers").WithName("AWSCluster"), Recorder: mgr.GetEventRecorderFor("awscluster-controller"), }).SetupWithManager(mgr, controller.Options{MaxConcurrentReconciles: awsClusterConcurrency}); err != nil { setupLog.Error(err, "unable to create controller", "controller", "AWSCluster") os.Exit(1) } if err = (&infrav1alpha3.AWSMachineTemplate{}).SetupWebhookWithManager(mgr); err != nil { setupLog.Error(err, "unable to create webhook", "webhook", "AWSMachineTemplate") os.Exit(1) } // +kubebuilder:scaffold:builder setupLog.Info("starting manager") if err := mgr.Start(ctrl.SetupSignalHandler()); err != nil { setupLog.Error(err, "problem running manager") os.Exit(1) } }
1
11,720
The file is not required - if you're using an IAM instance profile, for example. I'm not sure we can error 100% of the time if it's missing. @randomvariable any suggestions?
kubernetes-sigs-cluster-api-provider-aws
go
@@ -2527,7 +2527,7 @@ func (c *Compiler) parseExpr(frame *Frame, expr ssa.Value) (llvm.Value, error) { } if expr.High != nil { - highType = expr.High.Type().(*types.Basic) + highType = expr.High.Type().Underlying().(*types.Basic) high, err = c.parseExpr(frame, expr.High) if err != nil { return llvm.Value{}, nil
1
package compiler import ( "errors" "fmt" "go/build" "go/constant" "go/parser" "go/token" "go/types" "os" "path/filepath" "regexp" "runtime" "strconv" "strings" "github.com/aykevl/go-llvm" "github.com/aykevl/tinygo/ir" "golang.org/x/tools/go/loader" "golang.org/x/tools/go/ssa" ) func init() { llvm.InitializeAllTargets() llvm.InitializeAllTargetMCs() llvm.InitializeAllTargetInfos() llvm.InitializeAllAsmParsers() llvm.InitializeAllAsmPrinters() } // Configure the compiler. type Config struct { Triple string // LLVM target triple, e.g. x86_64-unknown-linux-gnu (empty string means default) DumpSSA bool // dump Go SSA, for compiler debugging Debug bool // add debug symbols for gdb RootDir string // GOROOT for TinyGo GOPATH string // GOPATH, like `go env GOPATH` BuildTags []string // build tags for TinyGo (empty means {runtime.GOOS/runtime.GOARCH}) InitInterp bool // use new init interpretation, meaning the old one is disabled } type Compiler struct { Config mod llvm.Module ctx llvm.Context builder llvm.Builder dibuilder *llvm.DIBuilder cu llvm.Metadata difiles map[string]llvm.Metadata ditypes map[string]llvm.Metadata machine llvm.TargetMachine targetData llvm.TargetData intType llvm.Type i8ptrType llvm.Type // for convenience uintptrType llvm.Type coroIdFunc llvm.Value coroSizeFunc llvm.Value coroBeginFunc llvm.Value coroSuspendFunc llvm.Value coroEndFunc llvm.Value coroFreeFunc llvm.Value initFuncs []llvm.Value deferFuncs []*ir.Function deferInvokeFuncs []InvokeDeferFunction ctxDeferFuncs []ContextDeferFunction ir *ir.Program } type Frame struct { fn *ir.Function locals map[ssa.Value]llvm.Value // local variables blockEntries map[*ssa.BasicBlock]llvm.BasicBlock // a *ssa.BasicBlock may be split up blockExits map[*ssa.BasicBlock]llvm.BasicBlock // these are the exit blocks currentBlock *ssa.BasicBlock phis []Phi blocking bool taskHandle llvm.Value cleanupBlock llvm.BasicBlock suspendBlock llvm.BasicBlock deferPtr llvm.Value difunc llvm.Metadata } type Phi struct { ssa *ssa.Phi llvm llvm.Value } // A thunk for a defer that defers calling a function pointer with context. type ContextDeferFunction struct { fn llvm.Value deferStruct []llvm.Type signature *types.Signature } // A thunk for a defer that defers calling an interface method. type InvokeDeferFunction struct { method *types.Func valueTypes []llvm.Type } func NewCompiler(pkgName string, config Config) (*Compiler, error) { if config.Triple == "" { config.Triple = llvm.DefaultTargetTriple() } if len(config.BuildTags) == 0 { config.BuildTags = []string{runtime.GOOS, runtime.GOARCH} } c := &Compiler{ Config: config, difiles: make(map[string]llvm.Metadata), ditypes: make(map[string]llvm.Metadata), } target, err := llvm.GetTargetFromTriple(config.Triple) if err != nil { return nil, err } c.machine = target.CreateTargetMachine(config.Triple, "", "", llvm.CodeGenLevelDefault, llvm.RelocStatic, llvm.CodeModelDefault) c.targetData = c.machine.CreateTargetData() c.ctx = llvm.NewContext() c.mod = c.ctx.NewModule(pkgName) c.mod.SetTarget(config.Triple) c.mod.SetDataLayout(c.targetData.String()) c.builder = c.ctx.NewBuilder() c.dibuilder = llvm.NewDIBuilder(c.mod) c.uintptrType = c.ctx.IntType(c.targetData.PointerSize() * 8) if c.targetData.PointerSize() <= 4 { // 8, 16, 32 bits targets c.intType = c.ctx.Int32Type() } else if c.targetData.PointerSize() == 8 { // 64 bits target c.intType = c.ctx.Int64Type() } else { panic("unknown pointer size") } c.i8ptrType = llvm.PointerType(c.ctx.Int8Type(), 0) coroIdType := llvm.FunctionType(c.ctx.TokenType(), []llvm.Type{c.ctx.Int32Type(), c.i8ptrType, c.i8ptrType, c.i8ptrType}, false) c.coroIdFunc = llvm.AddFunction(c.mod, "llvm.coro.id", coroIdType) coroSizeType := llvm.FunctionType(c.ctx.Int32Type(), nil, false) c.coroSizeFunc = llvm.AddFunction(c.mod, "llvm.coro.size.i32", coroSizeType) coroBeginType := llvm.FunctionType(c.i8ptrType, []llvm.Type{c.ctx.TokenType(), c.i8ptrType}, false) c.coroBeginFunc = llvm.AddFunction(c.mod, "llvm.coro.begin", coroBeginType) coroSuspendType := llvm.FunctionType(c.ctx.Int8Type(), []llvm.Type{c.ctx.TokenType(), c.ctx.Int1Type()}, false) c.coroSuspendFunc = llvm.AddFunction(c.mod, "llvm.coro.suspend", coroSuspendType) coroEndType := llvm.FunctionType(c.ctx.Int1Type(), []llvm.Type{c.i8ptrType, c.ctx.Int1Type()}, false) c.coroEndFunc = llvm.AddFunction(c.mod, "llvm.coro.end", coroEndType) coroFreeType := llvm.FunctionType(c.i8ptrType, []llvm.Type{c.ctx.TokenType(), c.i8ptrType}, false) c.coroFreeFunc = llvm.AddFunction(c.mod, "llvm.coro.free", coroFreeType) return c, nil } // Return the LLVM module. Only valid after a successful compile. func (c *Compiler) Module() llvm.Module { return c.mod } // Return the LLVM target data object. Only valid after a successful compile. func (c *Compiler) TargetData() llvm.TargetData { return c.targetData } // Compile the given package path or .go file path. Return an error when this // fails (in any stage). func (c *Compiler) Compile(mainPath string) error { tripleSplit := strings.Split(c.Triple, "-") // Prefix the GOPATH with the system GOROOT, as GOROOT is already set to // the TinyGo root. gopath := c.GOPATH if gopath == "" { gopath = runtime.GOROOT() } else { gopath = runtime.GOROOT() + string(filepath.ListSeparator) + gopath } config := loader.Config{ TypeChecker: types.Config{ Sizes: &StdSizes{ IntSize: int64(c.targetData.TypeAllocSize(c.intType)), PtrSize: int64(c.targetData.PointerSize()), MaxAlign: int64(c.targetData.PrefTypeAlignment(c.i8ptrType)), }, }, Build: &build.Context{ GOARCH: tripleSplit[0], GOOS: tripleSplit[2], GOROOT: c.RootDir, GOPATH: gopath, CgoEnabled: true, UseAllFiles: false, Compiler: "gc", // must be one of the recognized compilers BuildTags: append([]string{"tgo"}, c.BuildTags...), }, ParserMode: parser.ParseComments, } config.Import("runtime") if strings.HasSuffix(mainPath, ".go") { config.CreateFromFilenames("main", mainPath) } else { config.Import(mainPath) } lprogram, err := config.Load() if err != nil { return err } c.ir = ir.NewProgram(lprogram, mainPath) // Run some DCE and analysis passes. The results are later used by the // compiler. c.ir.SimpleDCE() // remove most dead code c.ir.AnalyseCallgraph() // set up callgraph c.ir.AnalyseInterfaceConversions() // determine which types are converted to an interface c.ir.AnalyseFunctionPointers() // determine which function pointer signatures need context c.ir.AnalyseBlockingRecursive() // make all parents of blocking calls blocking (transitively) c.ir.AnalyseGoCalls() // check whether we need a scheduler // Initialize debug information. c.cu = c.dibuilder.CreateCompileUnit(llvm.DICompileUnit{ Language: llvm.DW_LANG_Go, File: mainPath, Dir: "", Producer: "TinyGo", Optimized: true, }) var frames []*Frame // Declare all named struct types. for _, t := range c.ir.NamedTypes { if named, ok := t.Type.Type().(*types.Named); ok { if _, ok := named.Underlying().(*types.Struct); ok { t.LLVMType = c.ctx.StructCreateNamed(named.Obj().Pkg().Path() + "." + named.Obj().Name()) } } } // Define all named struct types. for _, t := range c.ir.NamedTypes { if named, ok := t.Type.Type().(*types.Named); ok { if st, ok := named.Underlying().(*types.Struct); ok { llvmType, err := c.getLLVMType(st) if err != nil { return err } t.LLVMType.StructSetBody(llvmType.StructElementTypes(), false) } } } // Declare all globals. These will get an initializer when parsing "package // initializer" functions. for _, g := range c.ir.Globals { typ := g.Type().(*types.Pointer).Elem() llvmType, err := c.getLLVMType(typ) if err != nil { return err } global := c.mod.NamedGlobal(g.LinkName()) if global.IsNil() { global = llvm.AddGlobal(c.mod, llvmType, g.LinkName()) } g.LLVMGlobal = global if !g.IsExtern() { global.SetLinkage(llvm.InternalLinkage) initializer, err := c.getZeroValue(llvmType) if err != nil { return err } global.SetInitializer(initializer) } } // Declare all functions. for _, f := range c.ir.Functions { frame, err := c.parseFuncDecl(f) if err != nil { return err } frames = append(frames, frame) } // Find and interpret package initializers. for _, frame := range frames { if frame.fn.Synthetic == "package initializer" { c.initFuncs = append(c.initFuncs, frame.fn.LLVMFn) // Try to interpret as much as possible of the init() function. // Whenever it hits an instruction that it doesn't understand, it // bails out and leaves the rest to the compiler (so initialization // continues at runtime). // This should only happen when it hits a function call or the end // of the block, ideally. if !c.InitInterp { err := c.ir.Interpret(frame.fn.Blocks[0], c.DumpSSA) if err != nil { return err } } err = c.parseFunc(frame) if err != nil { return err } } } // Set values for globals (after package initializer has been interpreted). for _, g := range c.ir.Globals { if g.Initializer() == nil { continue } err := c.parseGlobalInitializer(g) if err != nil { return err } } // Add definitions to declarations. for _, frame := range frames { if frame.fn.CName() != "" { continue } if frame.fn.Blocks == nil { continue // external function } var err error if frame.fn.Synthetic == "package initializer" { continue // already done } else { err = c.parseFunc(frame) } if err != nil { return err } } // Create deferred function wrappers. for _, fn := range c.deferFuncs { // This function gets a single parameter which is a pointer to a struct // (the defer frame). // This struct starts with the values of runtime._defer, but after that // follow the real function parameters. // The job of this wrapper is to extract these parameters and to call // the real function with them. llvmFn := c.mod.NamedFunction(fn.LinkName() + "$defer") llvmFn.SetLinkage(llvm.InternalLinkage) llvmFn.SetUnnamedAddr(true) entry := c.ctx.AddBasicBlock(llvmFn, "entry") c.builder.SetInsertPointAtEnd(entry) deferRawPtr := llvmFn.Param(0) // Get the real param type and cast to it. valueTypes := []llvm.Type{llvmFn.Type(), llvm.PointerType(c.mod.GetTypeByName("runtime._defer"), 0)} for _, param := range fn.Params { llvmType, err := c.getLLVMType(param.Type()) if err != nil { return err } valueTypes = append(valueTypes, llvmType) } deferFrameType := c.ctx.StructType(valueTypes, false) deferFramePtr := c.builder.CreateBitCast(deferRawPtr, llvm.PointerType(deferFrameType, 0), "deferFrame") // Extract the params from the struct. forwardParams := []llvm.Value{} zero := llvm.ConstInt(c.ctx.Int32Type(), 0, false) for i := range fn.Params { gep := c.builder.CreateGEP(deferFramePtr, []llvm.Value{zero, llvm.ConstInt(c.ctx.Int32Type(), uint64(i+2), false)}, "gep") forwardParam := c.builder.CreateLoad(gep, "param") forwardParams = append(forwardParams, forwardParam) } // Call real function (of which this is a wrapper). c.createCall(fn.LLVMFn, forwardParams, "") c.builder.CreateRetVoid() } // Create wrapper for deferred interface call. for _, thunk := range c.deferInvokeFuncs { // This function gets a single parameter which is a pointer to a struct // (the defer frame). // This struct starts with the values of runtime._defer, but after that // follow the real function parameters. // The job of this wrapper is to extract these parameters and to call // the real function with them. llvmFn := c.mod.NamedFunction(thunk.method.FullName() + "$defer") llvmFn.SetLinkage(llvm.InternalLinkage) llvmFn.SetUnnamedAddr(true) entry := c.ctx.AddBasicBlock(llvmFn, "entry") c.builder.SetInsertPointAtEnd(entry) deferRawPtr := llvmFn.Param(0) // Get the real param type and cast to it. deferFrameType := c.ctx.StructType(thunk.valueTypes, false) deferFramePtr := c.builder.CreateBitCast(deferRawPtr, llvm.PointerType(deferFrameType, 0), "deferFrame") // Extract the params from the struct. forwardParams := []llvm.Value{} zero := llvm.ConstInt(c.ctx.Int32Type(), 0, false) for i := range thunk.valueTypes[3:] { gep := c.builder.CreateGEP(deferFramePtr, []llvm.Value{zero, llvm.ConstInt(c.ctx.Int32Type(), uint64(i+3), false)}, "gep") forwardParam := c.builder.CreateLoad(gep, "param") forwardParams = append(forwardParams, forwardParam) } // Call real function (of which this is a wrapper). fnGEP := c.builder.CreateGEP(deferFramePtr, []llvm.Value{zero, llvm.ConstInt(c.ctx.Int32Type(), 2, false)}, "fn.gep") fn := c.builder.CreateLoad(fnGEP, "fn") c.createCall(fn, forwardParams, "") c.builder.CreateRetVoid() } // Create wrapper for deferred function pointer call. for _, thunk := range c.ctxDeferFuncs { // This function gets a single parameter which is a pointer to a struct // (the defer frame). // This struct starts with the values of runtime._defer, but after that // follows the closure and then the real parameters. // The job of this wrapper is to extract this closure and these // parameters and to call the function pointer with them. llvmFn := thunk.fn llvmFn.SetLinkage(llvm.InternalLinkage) llvmFn.SetUnnamedAddr(true) entry := c.ctx.AddBasicBlock(llvmFn, "entry") // TODO: set the debug location - perhaps the location of the rundefers // call? c.builder.SetInsertPointAtEnd(entry) deferRawPtr := llvmFn.Param(0) // Get the real param type and cast to it. deferFrameType := c.ctx.StructType(thunk.deferStruct, false) deferFramePtr := c.builder.CreateBitCast(deferRawPtr, llvm.PointerType(deferFrameType, 0), "defer.frame") // Extract the params from the struct. forwardParams := []llvm.Value{} zero := llvm.ConstInt(c.ctx.Int32Type(), 0, false) for i := 3; i < len(thunk.deferStruct); i++ { gep := c.builder.CreateGEP(deferFramePtr, []llvm.Value{zero, llvm.ConstInt(c.ctx.Int32Type(), uint64(i), false)}, "") forwardParam := c.builder.CreateLoad(gep, "param") forwardParams = append(forwardParams, forwardParam) } // Extract the closure from the struct. fpGEP := c.builder.CreateGEP(deferFramePtr, []llvm.Value{ zero, llvm.ConstInt(c.ctx.Int32Type(), 2, false), llvm.ConstInt(c.ctx.Int32Type(), 1, false), }, "closure.fp.ptr") fp := c.builder.CreateLoad(fpGEP, "closure.fp") contextGEP := c.builder.CreateGEP(deferFramePtr, []llvm.Value{ zero, llvm.ConstInt(c.ctx.Int32Type(), 2, false), llvm.ConstInt(c.ctx.Int32Type(), 0, false), }, "closure.context.ptr") context := c.builder.CreateLoad(contextGEP, "closure.context") forwardParams = append(forwardParams, context) // Cast the function pointer in the closure to the correct function // pointer type. closureType, err := c.getLLVMType(thunk.signature) if err != nil { return err } fpType := closureType.StructElementTypes()[1] fpCast := c.builder.CreateBitCast(fp, fpType, "closure.fp.cast") // Call real function (of which this is a wrapper). c.createCall(fpCast, forwardParams, "") c.builder.CreateRetVoid() } // After all packages are imported, add a synthetic initializer function // that calls the initializer of each package. initFn := c.ir.GetFunction(c.ir.Program.ImportedPackage("runtime").Members["initAll"].(*ssa.Function)) initFn.LLVMFn.SetLinkage(llvm.InternalLinkage) initFn.LLVMFn.SetUnnamedAddr(true) if c.Debug { difunc, err := c.attachDebugInfo(initFn) if err != nil { return err } pos := c.ir.Program.Fset.Position(initFn.Pos()) c.builder.SetCurrentDebugLocation(uint(pos.Line), uint(pos.Column), difunc, llvm.Metadata{}) } block := c.ctx.AddBasicBlock(initFn.LLVMFn, "entry") c.builder.SetInsertPointAtEnd(block) for _, fn := range c.initFuncs { c.builder.CreateCall(fn, nil, "") } c.builder.CreateRetVoid() // Add a wrapper for the main.main function, either calling it directly or // setting up the scheduler with it. mainWrapper := c.ir.GetFunction(c.ir.Program.ImportedPackage("runtime").Members["mainWrapper"].(*ssa.Function)) mainWrapper.LLVMFn.SetLinkage(llvm.InternalLinkage) mainWrapper.LLVMFn.SetUnnamedAddr(true) if c.Debug { difunc, err := c.attachDebugInfo(mainWrapper) if err != nil { return err } pos := c.ir.Program.Fset.Position(mainWrapper.Pos()) c.builder.SetCurrentDebugLocation(uint(pos.Line), uint(pos.Column), difunc, llvm.Metadata{}) } block = c.ctx.AddBasicBlock(mainWrapper.LLVMFn, "entry") c.builder.SetInsertPointAtEnd(block) realMain := c.mod.NamedFunction(c.ir.MainPkg().Pkg.Path() + ".main") if c.ir.NeedsScheduler() { coroutine := c.builder.CreateCall(realMain, []llvm.Value{llvm.ConstPointerNull(c.i8ptrType)}, "") scheduler := c.mod.NamedFunction("runtime.scheduler") c.builder.CreateCall(scheduler, []llvm.Value{coroutine}, "") } else { c.builder.CreateCall(realMain, nil, "") } c.builder.CreateRetVoid() // Add runtime type information for interfaces: interface calls and type // asserts. err = c.createInterfaceRTTI() if err != nil { return err } // see: https://reviews.llvm.org/D18355 c.mod.AddNamedMetadataOperand("llvm.module.flags", c.ctx.MDNode([]llvm.Metadata{ llvm.ConstInt(c.ctx.Int32Type(), 1, false).ConstantAsMetadata(), // Error on mismatch llvm.GlobalContext().MDString("Debug Info Version"), llvm.ConstInt(c.ctx.Int32Type(), 3, false).ConstantAsMetadata(), // DWARF version }), ) c.dibuilder.Finalize() return nil } func (c *Compiler) getLLVMType(goType types.Type) (llvm.Type, error) { switch typ := goType.(type) { case *types.Array: elemType, err := c.getLLVMType(typ.Elem()) if err != nil { return llvm.Type{}, err } return llvm.ArrayType(elemType, int(typ.Len())), nil case *types.Basic: switch typ.Kind() { case types.Bool, types.UntypedBool: return c.ctx.Int1Type(), nil case types.Int8, types.Uint8: return c.ctx.Int8Type(), nil case types.Int16, types.Uint16: return c.ctx.Int16Type(), nil case types.Int32, types.Uint32: return c.ctx.Int32Type(), nil case types.Int, types.Uint: return c.intType, nil case types.Int64, types.Uint64: return c.ctx.Int64Type(), nil case types.Float32: return c.ctx.FloatType(), nil case types.Float64: return c.ctx.DoubleType(), nil case types.Complex64: return llvm.VectorType(c.ctx.FloatType(), 2), nil case types.Complex128: return llvm.VectorType(c.ctx.DoubleType(), 2), nil case types.String, types.UntypedString: return c.mod.GetTypeByName("runtime._string"), nil case types.Uintptr: return c.uintptrType, nil case types.UnsafePointer: return c.i8ptrType, nil default: return llvm.Type{}, errors.New("todo: unknown basic type: " + typ.String()) } case *types.Chan: return llvm.PointerType(c.mod.GetTypeByName("runtime.channel"), 0), nil case *types.Interface: return c.mod.GetTypeByName("runtime._interface"), nil case *types.Map: return llvm.PointerType(c.mod.GetTypeByName("runtime.hashmap"), 0), nil case *types.Named: if _, ok := typ.Underlying().(*types.Struct); ok { llvmType := c.mod.GetTypeByName(typ.Obj().Pkg().Path() + "." + typ.Obj().Name()) if llvmType.IsNil() { return llvm.Type{}, errors.New("type not found: " + typ.Obj().Pkg().Path() + "." + typ.Obj().Name()) } return llvmType, nil } return c.getLLVMType(typ.Underlying()) case *types.Pointer: ptrTo, err := c.getLLVMType(typ.Elem()) if err != nil { return llvm.Type{}, err } return llvm.PointerType(ptrTo, 0), nil case *types.Signature: // function pointer // return value var err error var returnType llvm.Type if typ.Results().Len() == 0 { returnType = c.ctx.VoidType() } else if typ.Results().Len() == 1 { returnType, err = c.getLLVMType(typ.Results().At(0).Type()) if err != nil { return llvm.Type{}, err } } else { // Multiple return values. Put them together in a struct. members := make([]llvm.Type, typ.Results().Len()) for i := 0; i < typ.Results().Len(); i++ { returnType, err := c.getLLVMType(typ.Results().At(i).Type()) if err != nil { return llvm.Type{}, err } members[i] = returnType } returnType = c.ctx.StructType(members, false) } // param values var paramTypes []llvm.Type if typ.Recv() != nil { recv, err := c.getLLVMType(typ.Recv().Type()) if err != nil { return llvm.Type{}, err } if recv.StructName() == "runtime._interface" { // This is a call on an interface, not a concrete type. // The receiver is not an interface, but a i8* type. recv = c.i8ptrType } paramTypes = append(paramTypes, c.expandFormalParamType(recv)...) } params := typ.Params() for i := 0; i < params.Len(); i++ { subType, err := c.getLLVMType(params.At(i).Type()) if err != nil { return llvm.Type{}, err } paramTypes = append(paramTypes, c.expandFormalParamType(subType)...) } var ptr llvm.Type if c.ir.SignatureNeedsContext(typ) { // make a closure type (with a function pointer type inside): // {context, funcptr} paramTypes = append(paramTypes, c.i8ptrType) ptr = llvm.PointerType(llvm.FunctionType(returnType, paramTypes, false), 0) ptr = c.ctx.StructType([]llvm.Type{c.i8ptrType, ptr}, false) } else { // make a simple function pointer ptr = llvm.PointerType(llvm.FunctionType(returnType, paramTypes, false), 0) } return ptr, nil case *types.Slice: elemType, err := c.getLLVMType(typ.Elem()) if err != nil { return llvm.Type{}, err } members := []llvm.Type{ llvm.PointerType(elemType, 0), c.uintptrType, // len c.uintptrType, // cap } return c.ctx.StructType(members, false), nil case *types.Struct: members := make([]llvm.Type, typ.NumFields()) for i := 0; i < typ.NumFields(); i++ { member, err := c.getLLVMType(typ.Field(i).Type()) if err != nil { return llvm.Type{}, err } members[i] = member } return c.ctx.StructType(members, false), nil default: return llvm.Type{}, errors.New("todo: unknown type: " + goType.String()) } } // Return a zero LLVM value for any LLVM type. Setting this value as an // initializer has the same effect as setting 'zeroinitializer' on a value. // Sadly, I haven't found a way to do it directly with the Go API but this works // just fine. func (c *Compiler) getZeroValue(typ llvm.Type) (llvm.Value, error) { switch typ.TypeKind() { case llvm.ArrayTypeKind: subTyp := typ.ElementType() subVal, err := c.getZeroValue(subTyp) if err != nil { return llvm.Value{}, err } vals := make([]llvm.Value, typ.ArrayLength()) for i := range vals { vals[i] = subVal } return llvm.ConstArray(subTyp, vals), nil case llvm.FloatTypeKind, llvm.DoubleTypeKind: return llvm.ConstFloat(typ, 0.0), nil case llvm.IntegerTypeKind: return llvm.ConstInt(typ, 0, false), nil case llvm.PointerTypeKind: return llvm.ConstPointerNull(typ), nil case llvm.StructTypeKind: types := typ.StructElementTypes() vals := make([]llvm.Value, len(types)) for i, subTyp := range types { val, err := c.getZeroValue(subTyp) if err != nil { return llvm.Value{}, err } vals[i] = val } if typ.StructName() != "" { return llvm.ConstNamedStruct(typ, vals), nil } else { return c.ctx.ConstStruct(vals, false), nil } case llvm.VectorTypeKind: zero, err := c.getZeroValue(typ.ElementType()) if err != nil { return llvm.Value{}, err } vals := make([]llvm.Value, typ.VectorSize()) for i := range vals { vals[i] = zero } return llvm.ConstVector(vals, false), nil default: return llvm.Value{}, errors.New("todo: LLVM zero initializer: " + typ.String()) } } // Is this a pointer type of some sort? Can be unsafe.Pointer or any *T pointer. func isPointer(typ types.Type) bool { if _, ok := typ.(*types.Pointer); ok { return true } else if typ, ok := typ.(*types.Basic); ok && typ.Kind() == types.UnsafePointer { return true } else { return false } } // Get the DWARF type for this Go type. func (c *Compiler) getDIType(typ types.Type) (llvm.Metadata, error) { name := typ.String() if dityp, ok := c.ditypes[name]; ok { return dityp, nil } else { llvmType, err := c.getLLVMType(typ) if err != nil { return llvm.Metadata{}, err } sizeInBytes := c.targetData.TypeAllocSize(llvmType) var encoding llvm.DwarfTypeEncoding switch typ := typ.(type) { case *types.Basic: if typ.Info()&types.IsBoolean != 0 { encoding = llvm.DW_ATE_boolean } else if typ.Info()&types.IsFloat != 0 { encoding = llvm.DW_ATE_float } else if typ.Info()&types.IsComplex != 0 { encoding = llvm.DW_ATE_complex_float } else if typ.Info()&types.IsUnsigned != 0 { encoding = llvm.DW_ATE_unsigned } else if typ.Info()&types.IsInteger != 0 { encoding = llvm.DW_ATE_signed } else if typ.Kind() == types.UnsafePointer { encoding = llvm.DW_ATE_address } case *types.Pointer: encoding = llvm.DW_ATE_address } // TODO: other types dityp = c.dibuilder.CreateBasicType(llvm.DIBasicType{ Name: name, SizeInBits: sizeInBytes * 8, Encoding: encoding, }) c.ditypes[name] = dityp return dityp, nil } } func (c *Compiler) parseFuncDecl(f *ir.Function) (*Frame, error) { frame := &Frame{ fn: f, locals: make(map[ssa.Value]llvm.Value), blockEntries: make(map[*ssa.BasicBlock]llvm.BasicBlock), blockExits: make(map[*ssa.BasicBlock]llvm.BasicBlock), blocking: c.ir.IsBlocking(f), } var retType llvm.Type if frame.blocking { if f.Signature.Results() != nil { return nil, errors.New("todo: return values in blocking function") } retType = c.i8ptrType } else if f.Signature.Results() == nil { retType = c.ctx.VoidType() } else if f.Signature.Results().Len() == 1 { var err error retType, err = c.getLLVMType(f.Signature.Results().At(0).Type()) if err != nil { return nil, err } } else { results := make([]llvm.Type, 0, f.Signature.Results().Len()) for i := 0; i < f.Signature.Results().Len(); i++ { typ, err := c.getLLVMType(f.Signature.Results().At(i).Type()) if err != nil { return nil, err } results = append(results, typ) } retType = c.ctx.StructType(results, false) } var paramTypes []llvm.Type if frame.blocking { paramTypes = append(paramTypes, c.i8ptrType) // parent coroutine } for _, param := range f.Params { paramType, err := c.getLLVMType(param.Type()) if err != nil { return nil, err } paramTypeFragments := c.expandFormalParamType(paramType) paramTypes = append(paramTypes, paramTypeFragments...) } if c.ir.FunctionNeedsContext(f) { // This function gets an extra parameter: the context pointer (for // closures and bound methods). Add it as an extra paramter here. paramTypes = append(paramTypes, c.i8ptrType) } fnType := llvm.FunctionType(retType, paramTypes, false) name := f.LinkName() frame.fn.LLVMFn = c.mod.NamedFunction(name) if frame.fn.LLVMFn.IsNil() { frame.fn.LLVMFn = llvm.AddFunction(c.mod, name, fnType) } if c.Debug && f.Synthetic == "package initializer" { difunc, err := c.attachDebugInfoRaw(f, f.LLVMFn, "", "", 0) if err != nil { return nil, err } frame.difunc = difunc } else if c.Debug && f.Syntax() != nil && len(f.Blocks) != 0 { // Create debug info file if needed. difunc, err := c.attachDebugInfo(f) if err != nil { return nil, err } frame.difunc = difunc } return frame, nil } func (c *Compiler) attachDebugInfo(f *ir.Function) (llvm.Metadata, error) { pos := c.ir.Program.Fset.Position(f.Syntax().Pos()) return c.attachDebugInfoRaw(f, f.LLVMFn, "", pos.Filename, pos.Line) } func (c *Compiler) attachDebugInfoRaw(f *ir.Function, llvmFn llvm.Value, suffix, filename string, line int) (llvm.Metadata, error) { if _, ok := c.difiles[filename]; !ok { dir, file := filepath.Split(filename) if dir != "" { dir = dir[:len(dir)-1] } c.difiles[filename] = c.dibuilder.CreateFile(file, dir) } // Debug info for this function. diparams := make([]llvm.Metadata, 0, len(f.Params)) for _, param := range f.Params { ditype, err := c.getDIType(param.Type()) if err != nil { return llvm.Metadata{}, err } diparams = append(diparams, ditype) } diFuncType := c.dibuilder.CreateSubroutineType(llvm.DISubroutineType{ File: c.difiles[filename], Parameters: diparams, Flags: 0, // ? }) difunc := c.dibuilder.CreateFunction(c.difiles[filename], llvm.DIFunction{ Name: f.RelString(nil) + suffix, LinkageName: f.LinkName() + suffix, File: c.difiles[filename], Line: line, Type: diFuncType, LocalToUnit: true, IsDefinition: true, ScopeLine: 0, Flags: llvm.FlagPrototyped, Optimized: true, }) llvmFn.SetSubprogram(difunc) return difunc, nil } // Create a new global hashmap bucket, for map initialization. func (c *Compiler) initMapNewBucket(prefix string, mapType *types.Map) (llvm.Value, uint64, uint64, error) { llvmKeyType, err := c.getLLVMType(mapType.Key().Underlying()) if err != nil { return llvm.Value{}, 0, 0, err } llvmValueType, err := c.getLLVMType(mapType.Elem().Underlying()) if err != nil { return llvm.Value{}, 0, 0, err } keySize := c.targetData.TypeAllocSize(llvmKeyType) valueSize := c.targetData.TypeAllocSize(llvmValueType) bucketType := c.ctx.StructType([]llvm.Type{ llvm.ArrayType(c.ctx.Int8Type(), 8), // tophash c.i8ptrType, // next bucket llvm.ArrayType(llvmKeyType, 8), // key type llvm.ArrayType(llvmValueType, 8), // value type }, false) bucketValue, err := c.getZeroValue(bucketType) if err != nil { return llvm.Value{}, 0, 0, err } bucket := llvm.AddGlobal(c.mod, bucketType, prefix+"$hashmap$bucket") bucket.SetInitializer(bucketValue) bucket.SetLinkage(llvm.InternalLinkage) return bucket, keySize, valueSize, nil } func (c *Compiler) parseGlobalInitializer(g *ir.Global) error { if g.IsExtern() { return nil } llvmValue, err := c.getInterpretedValue(g.LinkName(), g.Initializer()) if err != nil { return err } g.LLVMGlobal.SetInitializer(llvmValue) return nil } // Turn a computed Value type (ConstValue, ArrayValue, etc.) into a LLVM value. // This is used to set the initializer of globals after they have been // calculated by the package initializer interpreter. func (c *Compiler) getInterpretedValue(prefix string, value ir.Value) (llvm.Value, error) { switch value := value.(type) { case *ir.ArrayValue: vals := make([]llvm.Value, len(value.Elems)) for i, elem := range value.Elems { val, err := c.getInterpretedValue(prefix+"$arrayval", elem) if err != nil { return llvm.Value{}, err } vals[i] = val } subTyp, err := c.getLLVMType(value.ElemType) if err != nil { return llvm.Value{}, err } return llvm.ConstArray(subTyp, vals), nil case *ir.ConstValue: return c.parseConst(prefix, value.Expr) case *ir.FunctionValue: if value.Elem == nil { llvmType, err := c.getLLVMType(value.Type) if err != nil { return llvm.Value{}, err } return c.getZeroValue(llvmType) } fn := c.ir.GetFunction(value.Elem) ptr := fn.LLVMFn if c.ir.SignatureNeedsContext(fn.Signature) { // Create closure value: {context, function pointer} ptr = c.ctx.ConstStruct([]llvm.Value{llvm.ConstPointerNull(c.i8ptrType), ptr}, false) } return ptr, nil case *ir.GlobalValue: zero := llvm.ConstInt(c.ctx.Int32Type(), 0, false) ptr := llvm.ConstInBoundsGEP(value.Global.LLVMGlobal, []llvm.Value{zero}) return ptr, nil case *ir.InterfaceValue: underlying := llvm.ConstPointerNull(c.i8ptrType) // could be any 0 value if value.Elem != nil { elem, err := c.getInterpretedValue(prefix, value.Elem) if err != nil { return llvm.Value{}, err } underlying = elem } return c.parseMakeInterface(underlying, value.Type, prefix) case *ir.MapValue: // Create initial bucket. firstBucketGlobal, keySize, valueSize, err := c.initMapNewBucket(prefix, value.Type) if err != nil { return llvm.Value{}, err } // Insert each key/value pair in the hashmap. bucketGlobal := firstBucketGlobal for i, key := range value.Keys { llvmKey, err := c.getInterpretedValue(prefix, key) if err != nil { return llvm.Value{}, nil } llvmValue, err := c.getInterpretedValue(prefix, value.Values[i]) if err != nil { return llvm.Value{}, nil } constVal := key.(*ir.ConstValue).Expr var keyBuf []byte switch constVal.Type().Underlying().(*types.Basic).Kind() { case types.String, types.UntypedString: keyBuf = []byte(constant.StringVal(constVal.Value)) case types.Int: keyBuf = make([]byte, c.targetData.TypeAllocSize(c.intType)) n, _ := constant.Uint64Val(constVal.Value) for i := range keyBuf { keyBuf[i] = byte(n) n >>= 8 } default: return llvm.Value{}, errors.New("todo: init: map key not implemented: " + constVal.Type().Underlying().String()) } hash := hashmapHash(keyBuf) if i%8 == 0 && i != 0 { // Bucket is full, create a new one. newBucketGlobal, _, _, err := c.initMapNewBucket(prefix, value.Type) if err != nil { return llvm.Value{}, err } zero := llvm.ConstInt(c.ctx.Int32Type(), 0, false) newBucketPtr := llvm.ConstInBoundsGEP(newBucketGlobal, []llvm.Value{zero}) newBucketPtrCast := llvm.ConstBitCast(newBucketPtr, c.i8ptrType) // insert pointer into old bucket bucket := bucketGlobal.Initializer() bucket = llvm.ConstInsertValue(bucket, newBucketPtrCast, []uint32{1}) bucketGlobal.SetInitializer(bucket) // switch to next bucket bucketGlobal = newBucketGlobal } tophashValue := llvm.ConstInt(c.ctx.Int8Type(), uint64(hashmapTopHash(hash)), false) bucket := bucketGlobal.Initializer() bucket = llvm.ConstInsertValue(bucket, tophashValue, []uint32{0, uint32(i % 8)}) bucket = llvm.ConstInsertValue(bucket, llvmKey, []uint32{2, uint32(i % 8)}) bucket = llvm.ConstInsertValue(bucket, llvmValue, []uint32{3, uint32(i % 8)}) bucketGlobal.SetInitializer(bucket) } // Create the hashmap itself. zero := llvm.ConstInt(c.ctx.Int32Type(), 0, false) bucketPtr := llvm.ConstInBoundsGEP(firstBucketGlobal, []llvm.Value{zero}) hashmapType := c.mod.GetTypeByName("runtime.hashmap") hashmap := llvm.ConstNamedStruct(hashmapType, []llvm.Value{ llvm.ConstPointerNull(llvm.PointerType(hashmapType, 0)), // next llvm.ConstBitCast(bucketPtr, c.i8ptrType), // buckets llvm.ConstInt(c.uintptrType, uint64(len(value.Keys)), false), // count llvm.ConstInt(c.ctx.Int8Type(), keySize, false), // keySize llvm.ConstInt(c.ctx.Int8Type(), valueSize, false), // valueSize llvm.ConstInt(c.ctx.Int8Type(), 0, false), // bucketBits }) // Create a pointer to this hashmap. hashmapPtr := llvm.AddGlobal(c.mod, hashmap.Type(), prefix+"$hashmap") hashmapPtr.SetInitializer(hashmap) hashmapPtr.SetLinkage(llvm.InternalLinkage) return llvm.ConstInBoundsGEP(hashmapPtr, []llvm.Value{zero}), nil case *ir.PointerBitCastValue: elem, err := c.getInterpretedValue(prefix, value.Elem) if err != nil { return llvm.Value{}, err } llvmType, err := c.getLLVMType(value.Type) if err != nil { return llvm.Value{}, err } return llvm.ConstBitCast(elem, llvmType), nil case *ir.PointerToUintptrValue: elem, err := c.getInterpretedValue(prefix, value.Elem) if err != nil { return llvm.Value{}, err } return llvm.ConstPtrToInt(elem, c.uintptrType), nil case *ir.PointerValue: if value.Elem == nil { typ, err := c.getLLVMType(value.Type) if err != nil { return llvm.Value{}, err } return llvm.ConstPointerNull(typ), nil } elem, err := c.getInterpretedValue(prefix, *value.Elem) if err != nil { return llvm.Value{}, err } obj := llvm.AddGlobal(c.mod, elem.Type(), prefix+"$ptrvalue") obj.SetInitializer(elem) obj.SetLinkage(llvm.InternalLinkage) elem = obj zero := llvm.ConstInt(c.ctx.Int32Type(), 0, false) ptr := llvm.ConstInBoundsGEP(elem, []llvm.Value{zero}) return ptr, nil case *ir.SliceValue: var globalPtr llvm.Value var arrayLength uint64 if value.Array == nil { arrayType, err := c.getLLVMType(value.Type.Elem()) if err != nil { return llvm.Value{}, err } globalPtr = llvm.ConstPointerNull(llvm.PointerType(arrayType, 0)) } else { // make array array, err := c.getInterpretedValue(prefix, value.Array) if err != nil { return llvm.Value{}, err } // make global from array global := llvm.AddGlobal(c.mod, array.Type(), prefix+"$array") global.SetInitializer(array) global.SetLinkage(llvm.InternalLinkage) // get pointer to global zero := llvm.ConstInt(c.ctx.Int32Type(), 0, false) globalPtr = c.builder.CreateInBoundsGEP(global, []llvm.Value{zero, zero}, "") arrayLength = uint64(len(value.Array.Elems)) } // make slice sliceTyp, err := c.getLLVMType(value.Type) if err != nil { return llvm.Value{}, err } llvmLen := llvm.ConstInt(c.uintptrType, arrayLength, false) slice := llvm.ConstNamedStruct(sliceTyp, []llvm.Value{ globalPtr, // ptr llvmLen, // len llvmLen, // cap }) return slice, nil case *ir.StructValue: fields := make([]llvm.Value, len(value.Fields)) for i, elem := range value.Fields { field, err := c.getInterpretedValue(prefix, elem) if err != nil { return llvm.Value{}, err } fields[i] = field } switch value.Type.(type) { case *types.Named: llvmType, err := c.getLLVMType(value.Type) if err != nil { return llvm.Value{}, err } return llvm.ConstNamedStruct(llvmType, fields), nil case *types.Struct: return c.ctx.ConstStruct(fields, false), nil default: return llvm.Value{}, errors.New("init: unknown struct type: " + value.Type.String()) } case *ir.ZeroBasicValue: llvmType, err := c.getLLVMType(value.Type) if err != nil { return llvm.Value{}, err } return c.getZeroValue(llvmType) default: return llvm.Value{}, errors.New("init: unknown initializer type: " + fmt.Sprintf("%#v", value)) } } func (c *Compiler) parseFunc(frame *Frame) error { if c.DumpSSA { fmt.Printf("\nfunc %s:\n", frame.fn.Function) } if !frame.fn.IsExported() { frame.fn.LLVMFn.SetLinkage(llvm.InternalLinkage) frame.fn.LLVMFn.SetUnnamedAddr(true) } if frame.fn.IsInterrupt() && strings.HasPrefix(c.Triple, "avr") { frame.fn.LLVMFn.SetFunctionCallConv(85) // CallingConv::AVR_SIGNAL } if c.Debug { pos := c.ir.Program.Fset.Position(frame.fn.Pos()) c.builder.SetCurrentDebugLocation(uint(pos.Line), uint(pos.Column), frame.difunc, llvm.Metadata{}) } // Pre-create all basic blocks in the function. for _, block := range frame.fn.DomPreorder() { llvmBlock := c.ctx.AddBasicBlock(frame.fn.LLVMFn, block.Comment) frame.blockEntries[block] = llvmBlock frame.blockExits[block] = llvmBlock } if frame.blocking { frame.cleanupBlock = c.ctx.AddBasicBlock(frame.fn.LLVMFn, "task.cleanup") frame.suspendBlock = c.ctx.AddBasicBlock(frame.fn.LLVMFn, "task.suspend") } entryBlock := frame.blockEntries[frame.fn.Blocks[0]] c.builder.SetInsertPointAtEnd(entryBlock) // Load function parameters llvmParamIndex := 0 for i, param := range frame.fn.Params { llvmType, err := c.getLLVMType(param.Type()) if err != nil { return err } fields := make([]llvm.Value, 0, 1) for range c.expandFormalParamType(llvmType) { fields = append(fields, frame.fn.LLVMFn.Param(llvmParamIndex)) llvmParamIndex++ } frame.locals[param] = c.collapseFormalParam(llvmType, fields) // Add debug information to this parameter (if available) if c.Debug && frame.fn.Syntax() != nil { pos := c.ir.Program.Fset.Position(frame.fn.Syntax().Pos()) dityp, err := c.getDIType(param.Type()) if err != nil { return err } c.dibuilder.CreateParameterVariable(frame.difunc, llvm.DIParameterVariable{ Name: param.Name(), File: c.difiles[pos.Filename], Line: pos.Line, Type: dityp, AlwaysPreserve: true, ArgNo: i + 1, }) // TODO: set the value of this parameter. } } // Load free variables from the context. This is a closure (or bound // method). if len(frame.fn.FreeVars) != 0 { if !c.ir.FunctionNeedsContext(frame.fn) { panic("free variables on function without context") } context := frame.fn.LLVMFn.LastParam() context.SetName("context") // Determine the context type. It's a struct containing all variables. freeVarTypes := make([]llvm.Type, 0, len(frame.fn.FreeVars)) for _, freeVar := range frame.fn.FreeVars { typ, err := c.getLLVMType(freeVar.Type()) if err != nil { return err } freeVarTypes = append(freeVarTypes, typ) } contextType := c.ctx.StructType(freeVarTypes, false) // Get a correctly-typed pointer to the context. contextAlloc := llvm.Value{} if c.targetData.TypeAllocSize(contextType) <= c.targetData.TypeAllocSize(c.i8ptrType) { // Context stored directly in pointer. Load it using an alloca. contextRawAlloc := c.builder.CreateAlloca(llvm.PointerType(c.i8ptrType, 0), "") contextRawValue := c.builder.CreateBitCast(context, llvm.PointerType(c.i8ptrType, 0), "") c.builder.CreateStore(contextRawValue, contextRawAlloc) contextAlloc = c.builder.CreateBitCast(contextRawAlloc, llvm.PointerType(contextType, 0), "") } else { // Context stored in the heap. Bitcast the passed-in pointer to the // correct pointer type. contextAlloc = c.builder.CreateBitCast(context, llvm.PointerType(contextType, 0), "") } // Load each free variable from the context. // A free variable is always a pointer when this is a closure, but it // can be another type when it is a wrapper for a bound method (these // wrappers are generated by the ssa package). for i, freeVar := range frame.fn.FreeVars { indices := []llvm.Value{ llvm.ConstInt(c.ctx.Int32Type(), 0, false), llvm.ConstInt(c.ctx.Int32Type(), uint64(i), false), } gep := c.builder.CreateInBoundsGEP(contextAlloc, indices, "") frame.locals[freeVar] = c.builder.CreateLoad(gep, "") } } if frame.fn.Recover != nil { // Create defer list pointer. deferType := llvm.PointerType(c.mod.GetTypeByName("runtime._defer"), 0) frame.deferPtr = c.builder.CreateAlloca(deferType, "deferPtr") c.builder.CreateStore(llvm.ConstPointerNull(deferType), frame.deferPtr) } if frame.blocking { // Coroutine initialization. taskState := c.builder.CreateAlloca(c.mod.GetTypeByName("runtime.taskState"), "task.state") stateI8 := c.builder.CreateBitCast(taskState, c.i8ptrType, "task.state.i8") id := c.builder.CreateCall(c.coroIdFunc, []llvm.Value{ llvm.ConstInt(c.ctx.Int32Type(), 0, false), stateI8, llvm.ConstNull(c.i8ptrType), llvm.ConstNull(c.i8ptrType), }, "task.token") size := c.builder.CreateCall(c.coroSizeFunc, nil, "task.size") if c.targetData.TypeAllocSize(size.Type()) > c.targetData.TypeAllocSize(c.uintptrType) { size = c.builder.CreateTrunc(size, c.uintptrType, "task.size.uintptr") } else if c.targetData.TypeAllocSize(size.Type()) < c.targetData.TypeAllocSize(c.uintptrType) { size = c.builder.CreateZExt(size, c.uintptrType, "task.size.uintptr") } data := c.createRuntimeCall("alloc", []llvm.Value{size}, "task.data") frame.taskHandle = c.builder.CreateCall(c.coroBeginFunc, []llvm.Value{id, data}, "task.handle") // Coroutine cleanup. Free resources associated with this coroutine. c.builder.SetInsertPointAtEnd(frame.cleanupBlock) mem := c.builder.CreateCall(c.coroFreeFunc, []llvm.Value{id, frame.taskHandle}, "task.data.free") c.createRuntimeCall("free", []llvm.Value{mem}, "") // re-insert parent coroutine c.createRuntimeCall("yieldToScheduler", []llvm.Value{frame.fn.LLVMFn.FirstParam()}, "") c.builder.CreateBr(frame.suspendBlock) // Coroutine suspend. A call to llvm.coro.suspend() will branch here. c.builder.SetInsertPointAtEnd(frame.suspendBlock) c.builder.CreateCall(c.coroEndFunc, []llvm.Value{frame.taskHandle, llvm.ConstInt(c.ctx.Int1Type(), 0, false)}, "unused") c.builder.CreateRet(frame.taskHandle) } // Fill blocks with instructions. for _, block := range frame.fn.DomPreorder() { if c.DumpSSA { fmt.Printf("%d: %s:\n", block.Index, block.Comment) } c.builder.SetInsertPointAtEnd(frame.blockEntries[block]) frame.currentBlock = block for _, instr := range block.Instrs { if _, ok := instr.(*ssa.DebugRef); ok { continue } if c.DumpSSA { if val, ok := instr.(ssa.Value); ok && val.Name() != "" { fmt.Printf("\t%s = %s\n", val.Name(), val.String()) } else { fmt.Printf("\t%s\n", instr.String()) } } err := c.parseInstr(frame, instr) if err != nil { return err } } if frame.fn.Name() == "init" && len(block.Instrs) == 0 { c.builder.CreateRetVoid() } } // Resolve phi nodes for _, phi := range frame.phis { block := phi.ssa.Block() for i, edge := range phi.ssa.Edges { llvmVal, err := c.parseExpr(frame, edge) if err != nil { return err } llvmBlock := frame.blockExits[block.Preds[i]] phi.llvm.AddIncoming([]llvm.Value{llvmVal}, []llvm.BasicBlock{llvmBlock}) } } return nil } func (c *Compiler) parseInstr(frame *Frame, instr ssa.Instruction) error { if c.Debug { pos := c.ir.Program.Fset.Position(instr.Pos()) c.builder.SetCurrentDebugLocation(uint(pos.Line), uint(pos.Column), frame.difunc, llvm.Metadata{}) } switch instr := instr.(type) { case ssa.Value: value, err := c.parseExpr(frame, instr) if err == ir.ErrCGoWrapper { // Ignore CGo global variables which we don't use. return nil } frame.locals[instr] = value return err case *ssa.DebugRef: return nil // ignore case *ssa.Defer: // The pointer to the previous defer struct, which we will replace to // make a linked list. next := c.builder.CreateLoad(frame.deferPtr, "defer.next") deferFuncType := llvm.FunctionType(c.ctx.VoidType(), []llvm.Type{next.Type()}, false) var values []llvm.Value var valueTypes []llvm.Type if instr.Call.IsInvoke() { // Function call on an interface. fnPtr, args, err := c.getInvokeCall(frame, &instr.Call) if err != nil { return err } valueTypes = []llvm.Type{llvm.PointerType(deferFuncType, 0), next.Type(), fnPtr.Type()} for _, param := range args { valueTypes = append(valueTypes, param.Type()) } // Create a thunk. deferName := instr.Call.Method.FullName() + "$defer" callback := c.mod.NamedFunction(deferName) if callback.IsNil() { // Not found, have to add it. callback = llvm.AddFunction(c.mod, deferName, deferFuncType) thunk := InvokeDeferFunction{ method: instr.Call.Method, valueTypes: valueTypes, } c.deferInvokeFuncs = append(c.deferInvokeFuncs, thunk) } // Collect all values to be put in the struct (starting with // runtime._defer fields, followed by the function pointer to be // called). values = append([]llvm.Value{callback, next, fnPtr}, args...) } else if callee, ok := instr.Call.Value.(*ssa.Function); ok { // Regular function call. fn := c.ir.GetFunction(callee) // Try to find the wrapper $defer function. deferName := fn.LinkName() + "$defer" callback := c.mod.NamedFunction(deferName) if callback.IsNil() { // Not found, have to add it. callback = llvm.AddFunction(c.mod, deferName, deferFuncType) c.deferFuncs = append(c.deferFuncs, fn) } // Collect all values to be put in the struct (starting with // runtime._defer fields). values = []llvm.Value{callback, next} valueTypes = []llvm.Type{callback.Type(), next.Type()} for _, param := range instr.Call.Args { llvmParam, err := c.parseExpr(frame, param) if err != nil { return err } values = append(values, llvmParam) valueTypes = append(valueTypes, llvmParam.Type()) } } else if makeClosure, ok := instr.Call.Value.(*ssa.MakeClosure); ok { // Immediately applied function literal with free variables. closure, err := c.parseExpr(frame, instr.Call.Value) if err != nil { return err } // Hopefully, LLVM will merge equivalent functions. deferName := frame.fn.LinkName() + "$fpdefer" callback := llvm.AddFunction(c.mod, deferName, deferFuncType) // Collect all values to be put in the struct (starting with // runtime._defer fields, followed by the closure). values = []llvm.Value{callback, next, closure} valueTypes = []llvm.Type{callback.Type(), next.Type(), closure.Type()} for _, param := range instr.Call.Args { llvmParam, err := c.parseExpr(frame, param) if err != nil { return err } values = append(values, llvmParam) valueTypes = append(valueTypes, llvmParam.Type()) } thunk := ContextDeferFunction{ callback, valueTypes, makeClosure.Fn.(*ssa.Function).Signature, } c.ctxDeferFuncs = append(c.ctxDeferFuncs, thunk) } else { return errors.New("todo: defer on uncommon function call type") } // Make a struct out of the collected values to put in the defer frame. deferFrameType := c.ctx.StructType(valueTypes, false) deferFrame, err := c.getZeroValue(deferFrameType) if err != nil { return err } for i, value := range values { deferFrame = c.builder.CreateInsertValue(deferFrame, value, i, "") } // Put this struct in an alloca. alloca := c.builder.CreateAlloca(deferFrameType, "defer.alloca") c.builder.CreateStore(deferFrame, alloca) // Push it on top of the linked list by replacing deferPtr. allocaCast := c.builder.CreateBitCast(alloca, next.Type(), "defer.alloca.cast") c.builder.CreateStore(allocaCast, frame.deferPtr) return nil case *ssa.Go: if instr.Common().Method != nil { return errors.New("todo: go on method receiver") } // Execute non-blocking calls (including builtins) directly. // parentHandle param is ignored. if !c.ir.IsBlocking(c.ir.GetFunction(instr.Common().Value.(*ssa.Function))) { _, err := c.parseCall(frame, instr.Common(), llvm.Value{}) return err // probably nil } // Start this goroutine. // parentHandle is nil, as the goroutine has no parent frame (it's a new // stack). handle, err := c.parseCall(frame, instr.Common(), llvm.Value{}) if err != nil { return err } c.createRuntimeCall("yieldToScheduler", []llvm.Value{handle}, "") return nil case *ssa.If: cond, err := c.parseExpr(frame, instr.Cond) if err != nil { return err } block := instr.Block() blockThen := frame.blockEntries[block.Succs[0]] blockElse := frame.blockEntries[block.Succs[1]] c.builder.CreateCondBr(cond, blockThen, blockElse) return nil case *ssa.Jump: blockJump := frame.blockEntries[instr.Block().Succs[0]] c.builder.CreateBr(blockJump) return nil case *ssa.MapUpdate: m, err := c.parseExpr(frame, instr.Map) if err != nil { return err } key, err := c.parseExpr(frame, instr.Key) if err != nil { return err } value, err := c.parseExpr(frame, instr.Value) if err != nil { return err } mapType := instr.Map.Type().Underlying().(*types.Map) return c.emitMapUpdate(mapType.Key(), m, key, value) case *ssa.Panic: value, err := c.parseExpr(frame, instr.X) if err != nil { return err } c.createRuntimeCall("_panic", []llvm.Value{value}, "") c.builder.CreateUnreachable() return nil case *ssa.Return: if frame.blocking { if len(instr.Results) != 0 { return errors.New("todo: return values from blocking function") } // Final suspend. continuePoint := c.builder.CreateCall(c.coroSuspendFunc, []llvm.Value{ llvm.ConstNull(c.ctx.TokenType()), llvm.ConstInt(c.ctx.Int1Type(), 1, false), // final=true }, "") sw := c.builder.CreateSwitch(continuePoint, frame.suspendBlock, 2) sw.AddCase(llvm.ConstInt(c.ctx.Int8Type(), 1, false), frame.cleanupBlock) return nil } else { if len(instr.Results) == 0 { c.builder.CreateRetVoid() return nil } else if len(instr.Results) == 1 { val, err := c.parseExpr(frame, instr.Results[0]) if err != nil { return err } c.builder.CreateRet(val) return nil } else { // Multiple return values. Put them all in a struct. retVal, err := c.getZeroValue(frame.fn.LLVMFn.Type().ElementType().ReturnType()) if err != nil { return err } for i, result := range instr.Results { val, err := c.parseExpr(frame, result) if err != nil { return err } retVal = c.builder.CreateInsertValue(retVal, val, i, "") } c.builder.CreateRet(retVal) return nil } } case *ssa.RunDefers: deferData := c.builder.CreateLoad(frame.deferPtr, "") c.createRuntimeCall("rundefers", []llvm.Value{deferData}, "") return nil case *ssa.Store: llvmAddr, err := c.parseExpr(frame, instr.Addr) if err == ir.ErrCGoWrapper { // Ignore CGo global variables which we don't use. return nil } if err != nil { return err } llvmVal, err := c.parseExpr(frame, instr.Val) if err != nil { return err } if c.targetData.TypeAllocSize(llvmVal.Type()) == 0 { // nothing to store return nil } store := c.builder.CreateStore(llvmVal, llvmAddr) valType := instr.Addr.Type().(*types.Pointer).Elem() if c.ir.IsVolatile(valType) { // Volatile store, for memory-mapped registers. store.SetVolatile(true) } return nil default: return errors.New("unknown instruction: " + instr.String()) } } func (c *Compiler) parseBuiltin(frame *Frame, args []ssa.Value, callName string) (llvm.Value, error) { switch callName { case "append": src, err := c.parseExpr(frame, args[0]) if err != nil { return llvm.Value{}, err } elems, err := c.parseExpr(frame, args[1]) if err != nil { return llvm.Value{}, err } srcBuf := c.builder.CreateExtractValue(src, 0, "append.srcBuf") srcPtr := c.builder.CreateBitCast(srcBuf, c.i8ptrType, "append.srcPtr") srcLen := c.builder.CreateExtractValue(src, 1, "append.srcLen") srcCap := c.builder.CreateExtractValue(src, 2, "append.srcCap") elemsBuf := c.builder.CreateExtractValue(elems, 0, "append.elemsBuf") elemsPtr := c.builder.CreateBitCast(elemsBuf, c.i8ptrType, "append.srcPtr") elemsLen := c.builder.CreateExtractValue(elems, 1, "append.elemsLen") elemType := srcBuf.Type().ElementType() elemSize := llvm.ConstInt(c.uintptrType, c.targetData.TypeAllocSize(elemType), false) result := c.createRuntimeCall("sliceAppend", []llvm.Value{srcPtr, elemsPtr, srcLen, srcCap, elemsLen, elemSize}, "append.new") newPtr := c.builder.CreateExtractValue(result, 0, "append.newPtr") newBuf := c.builder.CreateBitCast(newPtr, srcBuf.Type(), "append.newBuf") newLen := c.builder.CreateExtractValue(result, 1, "append.newLen") newCap := c.builder.CreateExtractValue(result, 2, "append.newCap") newSlice := llvm.Undef(src.Type()) newSlice = c.builder.CreateInsertValue(newSlice, newBuf, 0, "") newSlice = c.builder.CreateInsertValue(newSlice, newLen, 1, "") newSlice = c.builder.CreateInsertValue(newSlice, newCap, 2, "") return newSlice, nil case "cap": value, err := c.parseExpr(frame, args[0]) if err != nil { return llvm.Value{}, err } switch args[0].Type().(type) { case *types.Slice: return c.builder.CreateExtractValue(value, 2, "cap"), nil default: return llvm.Value{}, errors.New("todo: cap: unknown type") } case "complex": r, err := c.parseExpr(frame, args[0]) if err != nil { return llvm.Value{}, err } i, err := c.parseExpr(frame, args[1]) if err != nil { return llvm.Value{}, err } t := args[0].Type().Underlying().(*types.Basic) var cplx llvm.Value switch t.Kind() { case types.Float32: cplx = llvm.Undef(llvm.VectorType(c.ctx.FloatType(), 2)) case types.Float64: cplx = llvm.Undef(llvm.VectorType(c.ctx.DoubleType(), 2)) default: return llvm.Value{}, errors.New("unsupported type in complex builtin: " + t.String()) } cplx = c.builder.CreateInsertElement(cplx, r, llvm.ConstInt(c.ctx.Int8Type(), 0, false), "") cplx = c.builder.CreateInsertElement(cplx, i, llvm.ConstInt(c.ctx.Int8Type(), 1, false), "") return cplx, nil case "copy": dst, err := c.parseExpr(frame, args[0]) if err != nil { return llvm.Value{}, err } src, err := c.parseExpr(frame, args[1]) if err != nil { return llvm.Value{}, err } dstLen := c.builder.CreateExtractValue(dst, 1, "copy.dstLen") srcLen := c.builder.CreateExtractValue(src, 1, "copy.srcLen") dstBuf := c.builder.CreateExtractValue(dst, 0, "copy.dstArray") srcBuf := c.builder.CreateExtractValue(src, 0, "copy.srcArray") elemType := dstBuf.Type().ElementType() dstBuf = c.builder.CreateBitCast(dstBuf, c.i8ptrType, "copy.dstPtr") srcBuf = c.builder.CreateBitCast(srcBuf, c.i8ptrType, "copy.srcPtr") elemSize := llvm.ConstInt(c.uintptrType, c.targetData.TypeAllocSize(elemType), false) return c.createRuntimeCall("sliceCopy", []llvm.Value{dstBuf, srcBuf, dstLen, srcLen, elemSize}, "copy.n"), nil case "delete": m, err := c.parseExpr(frame, args[0]) if err != nil { return llvm.Value{}, err } key, err := c.parseExpr(frame, args[1]) if err != nil { return llvm.Value{}, err } return llvm.Value{}, c.emitMapDelete(args[1].Type(), m, key) case "imag": cplx, err := c.parseExpr(frame, args[0]) if err != nil { return llvm.Value{}, err } index := llvm.ConstInt(c.ctx.Int32Type(), 1, false) return c.builder.CreateExtractElement(cplx, index, "imag"), nil case "len": value, err := c.parseExpr(frame, args[0]) if err != nil { return llvm.Value{}, err } var llvmLen llvm.Value switch args[0].Type().Underlying().(type) { case *types.Basic, *types.Slice: // string or slice llvmLen = c.builder.CreateExtractValue(value, 1, "len") case *types.Map: llvmLen = c.createRuntimeCall("hashmapLen", []llvm.Value{value}, "len") default: return llvm.Value{}, errors.New("todo: len: unknown type") } if c.targetData.TypeAllocSize(llvmLen.Type()) < c.targetData.TypeAllocSize(c.intType) { llvmLen = c.builder.CreateZExt(llvmLen, c.intType, "len.int") } return llvmLen, nil case "print", "println": for i, arg := range args { if i >= 1 && callName == "println" { c.createRuntimeCall("printspace", nil, "") } value, err := c.parseExpr(frame, arg) if err != nil { return llvm.Value{}, err } typ := arg.Type().Underlying() switch typ := typ.(type) { case *types.Basic: switch typ.Kind() { case types.String, types.UntypedString: c.createRuntimeCall("printstring", []llvm.Value{value}, "") case types.Uintptr: c.createRuntimeCall("printptr", []llvm.Value{value}, "") case types.UnsafePointer: ptrValue := c.builder.CreatePtrToInt(value, c.uintptrType, "") c.createRuntimeCall("printptr", []llvm.Value{ptrValue}, "") default: // runtime.print{int,uint}{8,16,32,64} if typ.Info()&types.IsInteger != 0 { name := "print" if typ.Info()&types.IsUnsigned != 0 { name += "uint" } else { name += "int" } name += strconv.FormatUint(c.targetData.TypeAllocSize(value.Type())*8, 10) c.createRuntimeCall(name, []llvm.Value{value}, "") } else if typ.Kind() == types.Bool { c.createRuntimeCall("printbool", []llvm.Value{value}, "") } else if typ.Kind() == types.Float32 { c.createRuntimeCall("printfloat32", []llvm.Value{value}, "") } else if typ.Kind() == types.Float64 { c.createRuntimeCall("printfloat64", []llvm.Value{value}, "") } else if typ.Kind() == types.Complex64 { c.createRuntimeCall("printcomplex64", []llvm.Value{value}, "") } else if typ.Kind() == types.Complex128 { c.createRuntimeCall("printcomplex128", []llvm.Value{value}, "") } else { return llvm.Value{}, errors.New("unknown basic arg type: " + typ.String()) } } case *types.Interface: c.createRuntimeCall("printitf", []llvm.Value{value}, "") case *types.Map: c.createRuntimeCall("printmap", []llvm.Value{value}, "") case *types.Pointer: ptrValue := c.builder.CreatePtrToInt(value, c.uintptrType, "") c.createRuntimeCall("printptr", []llvm.Value{ptrValue}, "") default: return llvm.Value{}, errors.New("unknown arg type: " + typ.String()) } } if callName == "println" { c.createRuntimeCall("printnl", nil, "") } return llvm.Value{}, nil // print() or println() returns void case "real": cplx, err := c.parseExpr(frame, args[0]) if err != nil { return llvm.Value{}, err } index := llvm.ConstInt(c.ctx.Int32Type(), 0, false) return c.builder.CreateExtractElement(cplx, index, "real"), nil case "recover": return c.createRuntimeCall("_recover", nil, ""), nil case "ssa:wrapnilchk": // TODO: do an actual nil check? return c.parseExpr(frame, args[0]) default: return llvm.Value{}, errors.New("todo: builtin: " + callName) } } func (c *Compiler) parseFunctionCall(frame *Frame, args []ssa.Value, llvmFn, context llvm.Value, blocking bool, parentHandle llvm.Value) (llvm.Value, error) { var params []llvm.Value if blocking { if parentHandle.IsNil() { // Started from 'go' statement. params = append(params, llvm.ConstNull(c.i8ptrType)) } else { // Blocking function calls another blocking function. params = append(params, parentHandle) } } for _, param := range args { val, err := c.parseExpr(frame, param) if err != nil { return llvm.Value{}, err } params = append(params, val) } if !context.IsNil() { // This function takes a context parameter. // Add it to the end of the parameter list. params = append(params, context) } if frame.blocking && llvmFn.Name() == "time.Sleep" { // Set task state to TASK_STATE_SLEEP and set the duration. c.createRuntimeCall("sleepTask", []llvm.Value{frame.taskHandle, params[0]}, "") // Yield to scheduler. continuePoint := c.builder.CreateCall(c.coroSuspendFunc, []llvm.Value{ llvm.ConstNull(c.ctx.TokenType()), llvm.ConstInt(c.ctx.Int1Type(), 0, false), }, "") wakeup := c.ctx.InsertBasicBlock(llvm.NextBasicBlock(c.builder.GetInsertBlock()), "task.wakeup") sw := c.builder.CreateSwitch(continuePoint, frame.suspendBlock, 2) sw.AddCase(llvm.ConstInt(c.ctx.Int8Type(), 0, false), wakeup) sw.AddCase(llvm.ConstInt(c.ctx.Int8Type(), 1, false), frame.cleanupBlock) c.builder.SetInsertPointAtEnd(wakeup) return llvm.Value{}, nil } result := c.createCall(llvmFn, params, "") if blocking && !parentHandle.IsNil() { // Calling a blocking function as a regular function call. // This is done by passing the current coroutine as a parameter to the // new coroutine and dropping the current coroutine from the scheduler // (with the TASK_STATE_CALL state). When the subroutine is finished, it // will reactivate the parent (this frame) in it's destroy function. c.createRuntimeCall("yieldToScheduler", []llvm.Value{result}, "") // Set task state to TASK_STATE_CALL. c.createRuntimeCall("waitForAsyncCall", []llvm.Value{frame.taskHandle}, "") // Yield to the scheduler. continuePoint := c.builder.CreateCall(c.coroSuspendFunc, []llvm.Value{ llvm.ConstNull(c.ctx.TokenType()), llvm.ConstInt(c.ctx.Int1Type(), 0, false), }, "") resume := c.ctx.InsertBasicBlock(llvm.NextBasicBlock(c.builder.GetInsertBlock()), "task.callComplete") sw := c.builder.CreateSwitch(continuePoint, frame.suspendBlock, 2) sw.AddCase(llvm.ConstInt(c.ctx.Int8Type(), 0, false), resume) sw.AddCase(llvm.ConstInt(c.ctx.Int8Type(), 1, false), frame.cleanupBlock) c.builder.SetInsertPointAtEnd(resume) } return result, nil } func (c *Compiler) parseCall(frame *Frame, instr *ssa.CallCommon, parentHandle llvm.Value) (llvm.Value, error) { if instr.IsInvoke() { // TODO: blocking methods (needs analysis) fnCast, args, err := c.getInvokeCall(frame, instr) if err != nil { return llvm.Value{}, err } return c.createCall(fnCast, args, ""), nil } // Try to call the function directly for trivially static calls. if fn := instr.StaticCallee(); fn != nil { if fn.RelString(nil) == "device/arm.Asm" || fn.RelString(nil) == "device/avr.Asm" { // Magic function: insert inline assembly instead of calling it. fnType := llvm.FunctionType(c.ctx.VoidType(), []llvm.Type{}, false) asm := constant.StringVal(instr.Args[0].(*ssa.Const).Value) target := llvm.InlineAsm(fnType, asm, "", true, false, 0) return c.builder.CreateCall(target, nil, ""), nil } if fn.RelString(nil) == "device/arm.AsmFull" || fn.RelString(nil) == "device/avr.AsmFull" { asmString := constant.StringVal(instr.Args[0].(*ssa.Const).Value) registers := map[string]llvm.Value{} registerMap := instr.Args[1].(*ssa.MakeMap) for _, r := range *registerMap.Referrers() { switch r := r.(type) { case *ssa.DebugRef: // ignore case *ssa.MapUpdate: if r.Block() != registerMap.Block() { return llvm.Value{}, errors.New("register value map must be created in the same basic block") } key := constant.StringVal(r.Key.(*ssa.Const).Value) //println("value:", r.Value.(*ssa.MakeInterface).X.String()) value, err := c.parseExpr(frame, r.Value.(*ssa.MakeInterface).X) if err != nil { return llvm.Value{}, err } registers[key] = value case *ssa.Call: if r.Common() == instr { break } default: return llvm.Value{}, errors.New("don't know how to handle argument to inline assembly: " + r.String()) } } // TODO: handle dollar signs in asm string registerNumbers := map[string]int{} var err error argTypes := []llvm.Type{} args := []llvm.Value{} constraints := []string{} asmString = regexp.MustCompile("\\{[a-zA-Z]+\\}").ReplaceAllStringFunc(asmString, func(s string) string { // TODO: skip strings like {r4} etc. that look like ARM push/pop // instructions. name := s[1 : len(s)-1] if _, ok := registers[name]; !ok { if err == nil { err = errors.New("unknown register name: " + name) } return s } if _, ok := registerNumbers[name]; !ok { registerNumbers[name] = len(registerNumbers) argTypes = append(argTypes, registers[name].Type()) args = append(args, registers[name]) switch registers[name].Type().TypeKind() { case llvm.IntegerTypeKind: constraints = append(constraints, "r") case llvm.PointerTypeKind: constraints = append(constraints, "*m") default: err = errors.New("unknown type in inline assembly for value: " + name) return s } } return fmt.Sprintf("${%v}", registerNumbers[name]) }) if err != nil { return llvm.Value{}, err } fnType := llvm.FunctionType(c.ctx.VoidType(), argTypes, false) target := llvm.InlineAsm(fnType, asmString, strings.Join(constraints, ","), true, false, 0) return c.builder.CreateCall(target, args, ""), nil } targetFunc := c.ir.GetFunction(fn) if targetFunc.LLVMFn.IsNil() { return llvm.Value{}, errors.New("undefined function: " + targetFunc.LinkName()) } var context llvm.Value if c.ir.FunctionNeedsContext(targetFunc) { // This function call is to a (potential) closure, not a regular // function. See whether it is a closure and if so, call it as such. // Else, supply a dummy nil pointer as the last parameter. var err error if mkClosure, ok := instr.Value.(*ssa.MakeClosure); ok { // closure is {context, function pointer} closure, err := c.parseExpr(frame, mkClosure) if err != nil { return llvm.Value{}, err } context = c.builder.CreateExtractValue(closure, 0, "") } else { context, err = c.getZeroValue(c.i8ptrType) if err != nil { return llvm.Value{}, err } } } return c.parseFunctionCall(frame, instr.Args, targetFunc.LLVMFn, context, c.ir.IsBlocking(targetFunc), parentHandle) } // Builtin or function pointer. switch call := instr.Value.(type) { case *ssa.Builtin: return c.parseBuiltin(frame, instr.Args, call.Name()) default: // function pointer value, err := c.parseExpr(frame, instr.Value) if err != nil { return llvm.Value{}, err } // TODO: blocking function pointers (needs analysis) var context llvm.Value if c.ir.SignatureNeedsContext(instr.Signature()) { // 'value' is a closure, not a raw function pointer. // Extract the function pointer and the context pointer. // closure: {context, function pointer} context = c.builder.CreateExtractValue(value, 0, "") value = c.builder.CreateExtractValue(value, 1, "") } return c.parseFunctionCall(frame, instr.Args, value, context, false, parentHandle) } } func (c *Compiler) emitBoundsCheck(frame *Frame, arrayLen, index llvm.Value, indexType types.Type) { if frame.fn.IsNoBounds() { // The //go:nobounds pragma was added to the function to avoid bounds // checking. return } // Sometimes, the index can be e.g. an uint8 or int8, and we have to // correctly extend that type. if index.Type().IntTypeWidth() < arrayLen.Type().IntTypeWidth() { if indexType.(*types.Basic).Info()&types.IsUnsigned == 0 { index = c.builder.CreateZExt(index, arrayLen.Type(), "") } else { index = c.builder.CreateSExt(index, arrayLen.Type(), "") } } // Optimize away trivial cases. // LLVM would do this anyway with interprocedural optimizations, but it // helps to see cases where bounds check elimination would really help. if index.IsConstant() && arrayLen.IsConstant() && !arrayLen.IsUndef() { index := index.SExtValue() arrayLen := arrayLen.SExtValue() if index >= 0 && index < arrayLen { return } } if index.Type().IntTypeWidth() > c.intType.IntTypeWidth() { // Index is too big for the regular bounds check. Use the one for int64. c.createRuntimeCall("lookupBoundsCheckLong", []llvm.Value{arrayLen, index}, "") } else { c.createRuntimeCall("lookupBoundsCheck", []llvm.Value{arrayLen, index}, "") } } func (c *Compiler) emitSliceBoundsCheck(frame *Frame, capacity, low, high llvm.Value, lowType, highType *types.Basic) { if frame.fn.IsNoBounds() { // The //go:nobounds pragma was added to the function to avoid bounds // checking. return } uintptrWidth := c.uintptrType.IntTypeWidth() if low.Type().IntTypeWidth() > uintptrWidth || high.Type().IntTypeWidth() > uintptrWidth { if low.Type().IntTypeWidth() < 64 { if lowType.Info()&types.IsUnsigned != 0 { low = c.builder.CreateZExt(low, c.ctx.Int64Type(), "") } else { low = c.builder.CreateSExt(low, c.ctx.Int64Type(), "") } } if high.Type().IntTypeWidth() < 64 { if highType.Info()&types.IsUnsigned != 0 { high = c.builder.CreateZExt(high, c.ctx.Int64Type(), "") } else { high = c.builder.CreateSExt(high, c.ctx.Int64Type(), "") } } // TODO: 32-bit or even 16-bit slice bounds checks for 8-bit platforms c.createRuntimeCall("sliceBoundsCheck64", []llvm.Value{capacity, low, high}, "") } else { c.createRuntimeCall("sliceBoundsCheck", []llvm.Value{capacity, low, high}, "") } } func (c *Compiler) parseExpr(frame *Frame, expr ssa.Value) (llvm.Value, error) { if value, ok := frame.locals[expr]; ok { // Value is a local variable that has already been computed. if value.IsNil() { return llvm.Value{}, errors.New("undefined local var (from cgo?)") } return value, nil } switch expr := expr.(type) { case *ssa.Alloc: typ, err := c.getLLVMType(expr.Type().Underlying().(*types.Pointer).Elem()) if err != nil { return llvm.Value{}, err } var buf llvm.Value if expr.Heap { // TODO: escape analysis size := llvm.ConstInt(c.uintptrType, c.targetData.TypeAllocSize(typ), false) buf = c.createRuntimeCall("alloc", []llvm.Value{size}, expr.Comment) buf = c.builder.CreateBitCast(buf, llvm.PointerType(typ, 0), "") } else { buf = c.builder.CreateAlloca(typ, expr.Comment) if c.targetData.TypeAllocSize(typ) != 0 { zero, err := c.getZeroValue(typ) if err != nil { return llvm.Value{}, err } c.builder.CreateStore(zero, buf) // zero-initialize var } } return buf, nil case *ssa.BinOp: x, err := c.parseExpr(frame, expr.X) if err != nil { return llvm.Value{}, err } y, err := c.parseExpr(frame, expr.Y) if err != nil { return llvm.Value{}, err } return c.parseBinOp(expr.Op, expr.X.Type().Underlying(), x, y) case *ssa.Call: // Passing the current task here to the subroutine. It is only used when // the subroutine is blocking. return c.parseCall(frame, expr.Common(), frame.taskHandle) case *ssa.ChangeInterface: // Do not change between interface types: always use the underlying // (concrete) type in the type number of the interface. Every method // call on an interface will do a lookup which method to call. // This is different from how the official Go compiler works, because of // heap allocation and because it's easier to implement, see: // https://research.swtch.com/interfaces return c.parseExpr(frame, expr.X) case *ssa.ChangeType: x, err := c.parseExpr(frame, expr.X) if err != nil { return llvm.Value{}, err } // The only case when we need to bitcast is when casting between named // struct types, as those are actually different in LLVM. Let's just // bitcast all struct types for ease of use. if _, ok := expr.Type().Underlying().(*types.Struct); ok { llvmType, err := c.getLLVMType(expr.X.Type()) if err != nil { return llvm.Value{}, err } return c.builder.CreateBitCast(x, llvmType, "changetype"), nil } return x, nil case *ssa.Const: return c.parseConst(frame.fn.LinkName(), expr) case *ssa.Convert: x, err := c.parseExpr(frame, expr.X) if err != nil { return llvm.Value{}, err } return c.parseConvert(expr.X.Type(), expr.Type(), x) case *ssa.Extract: value, err := c.parseExpr(frame, expr.Tuple) if err != nil { return llvm.Value{}, err } result := c.builder.CreateExtractValue(value, expr.Index, "") return result, nil case *ssa.Field: value, err := c.parseExpr(frame, expr.X) if err != nil { return llvm.Value{}, err } result := c.builder.CreateExtractValue(value, expr.Field, "") return result, nil case *ssa.FieldAddr: val, err := c.parseExpr(frame, expr.X) if err != nil { return llvm.Value{}, err } indices := []llvm.Value{ llvm.ConstInt(c.ctx.Int32Type(), 0, false), llvm.ConstInt(c.ctx.Int32Type(), uint64(expr.Field), false), } return c.builder.CreateGEP(val, indices, ""), nil case *ssa.Function: fn := c.ir.GetFunction(expr) ptr := fn.LLVMFn if c.ir.FunctionNeedsContext(fn) { // Create closure for function pointer. // Closure is: {context, function pointer} ptr = c.ctx.ConstStruct([]llvm.Value{ llvm.ConstPointerNull(c.i8ptrType), ptr, }, false) } return ptr, nil case *ssa.Global: if strings.HasPrefix(expr.Name(), "__cgofn__cgo_") || strings.HasPrefix(expr.Name(), "_cgo_") { // Ignore CGo global variables which we don't use. return llvm.Value{}, ir.ErrCGoWrapper } value := c.ir.GetGlobal(expr).LLVMGlobal if value.IsNil() { return llvm.Value{}, errors.New("global not found: " + c.ir.GetGlobal(expr).LinkName()) } return value, nil case *ssa.Index: array, err := c.parseExpr(frame, expr.X) if err != nil { return llvm.Value{}, err } index, err := c.parseExpr(frame, expr.Index) if err != nil { return llvm.Value{}, err } // Check bounds. arrayLen := expr.X.Type().(*types.Array).Len() arrayLenLLVM := llvm.ConstInt(c.uintptrType, uint64(arrayLen), false) c.emitBoundsCheck(frame, arrayLenLLVM, index, expr.Index.Type()) // Can't load directly from array (as index is non-constant), so have to // do it using an alloca+gep+load. alloca := c.builder.CreateAlloca(array.Type(), "") c.builder.CreateStore(array, alloca) zero := llvm.ConstInt(c.ctx.Int32Type(), 0, false) ptr := c.builder.CreateGEP(alloca, []llvm.Value{zero, index}, "") return c.builder.CreateLoad(ptr, ""), nil case *ssa.IndexAddr: val, err := c.parseExpr(frame, expr.X) if err != nil { return llvm.Value{}, err } index, err := c.parseExpr(frame, expr.Index) if err != nil { return llvm.Value{}, err } // Get buffer pointer and length var bufptr, buflen llvm.Value switch ptrTyp := expr.X.Type().Underlying().(type) { case *types.Pointer: typ := expr.X.Type().(*types.Pointer).Elem().Underlying() switch typ := typ.(type) { case *types.Array: bufptr = val buflen = llvm.ConstInt(c.uintptrType, uint64(typ.Len()), false) default: return llvm.Value{}, errors.New("todo: indexaddr: " + typ.String()) } case *types.Slice: bufptr = c.builder.CreateExtractValue(val, 0, "indexaddr.ptr") buflen = c.builder.CreateExtractValue(val, 1, "indexaddr.len") default: return llvm.Value{}, errors.New("todo: indexaddr: " + ptrTyp.String()) } // Bounds check. // LLVM optimizes this away in most cases. c.emitBoundsCheck(frame, buflen, index, expr.Index.Type()) switch expr.X.Type().Underlying().(type) { case *types.Pointer: indices := []llvm.Value{ llvm.ConstInt(c.ctx.Int32Type(), 0, false), index, } return c.builder.CreateGEP(bufptr, indices, ""), nil case *types.Slice: return c.builder.CreateGEP(bufptr, []llvm.Value{index}, ""), nil default: panic("unreachable") } case *ssa.Lookup: value, err := c.parseExpr(frame, expr.X) if err != nil { return llvm.Value{}, nil } index, err := c.parseExpr(frame, expr.Index) if err != nil { return llvm.Value{}, nil } switch xType := expr.X.Type().Underlying().(type) { case *types.Basic: // Value type must be a string, which is a basic type. if xType.Info()&types.IsString == 0 { panic("lookup on non-string?") } // Bounds check. // LLVM optimizes this away in most cases. length, err := c.parseBuiltin(frame, []ssa.Value{expr.X}, "len") if err != nil { return llvm.Value{}, err // shouldn't happen } c.emitBoundsCheck(frame, length, index, expr.Index.Type()) // Lookup byte buf := c.builder.CreateExtractValue(value, 0, "") bufPtr := c.builder.CreateGEP(buf, []llvm.Value{index}, "") return c.builder.CreateLoad(bufPtr, ""), nil case *types.Map: valueType := expr.Type() if expr.CommaOk { valueType = valueType.(*types.Tuple).At(0).Type() } return c.emitMapLookup(xType.Key(), valueType, value, index, expr.CommaOk) default: panic("unknown lookup type: " + expr.String()) } case *ssa.MakeClosure: // A closure returns a function pointer with context: // {context, fp} return c.parseMakeClosure(frame, expr) case *ssa.MakeInterface: val, err := c.parseExpr(frame, expr.X) if err != nil { return llvm.Value{}, err } return c.parseMakeInterface(val, expr.X.Type(), "") case *ssa.MakeMap: mapType := expr.Type().Underlying().(*types.Map) llvmKeyType, err := c.getLLVMType(mapType.Key().Underlying()) if err != nil { return llvm.Value{}, err } llvmValueType, err := c.getLLVMType(mapType.Elem().Underlying()) if err != nil { return llvm.Value{}, err } keySize := c.targetData.TypeAllocSize(llvmKeyType) valueSize := c.targetData.TypeAllocSize(llvmValueType) llvmKeySize := llvm.ConstInt(c.ctx.Int8Type(), keySize, false) llvmValueSize := llvm.ConstInt(c.ctx.Int8Type(), valueSize, false) hashmap := c.createRuntimeCall("hashmapMake", []llvm.Value{llvmKeySize, llvmValueSize}, "") return hashmap, nil case *ssa.MakeSlice: sliceLen, err := c.parseExpr(frame, expr.Len) if err != nil { return llvm.Value{}, nil } sliceCap, err := c.parseExpr(frame, expr.Cap) if err != nil { return llvm.Value{}, nil } sliceType := expr.Type().Underlying().(*types.Slice) llvmElemType, err := c.getLLVMType(sliceType.Elem()) if err != nil { return llvm.Value{}, nil } elemSize := c.targetData.TypeAllocSize(llvmElemType) // Bounds checking. if !frame.fn.IsNoBounds() { c.createRuntimeCall("sliceBoundsCheckMake", []llvm.Value{sliceLen, sliceCap}, "") } // Allocate the backing array. // TODO: escape analysis elemSizeValue := llvm.ConstInt(c.uintptrType, elemSize, false) sliceCapCast, err := c.parseConvert(expr.Cap.Type(), types.Typ[types.Uintptr], sliceCap) if err != nil { return llvm.Value{}, err } sliceSize := c.builder.CreateBinOp(llvm.Mul, elemSizeValue, sliceCapCast, "makeslice.cap") slicePtr := c.createRuntimeCall("alloc", []llvm.Value{sliceSize}, "makeslice.buf") slicePtr = c.builder.CreateBitCast(slicePtr, llvm.PointerType(llvmElemType, 0), "makeslice.array") if c.targetData.TypeAllocSize(sliceLen.Type()) > c.targetData.TypeAllocSize(c.uintptrType) { sliceLen = c.builder.CreateTrunc(sliceLen, c.uintptrType, "") sliceCap = c.builder.CreateTrunc(sliceCap, c.uintptrType, "") } // Create the slice. slice := c.ctx.ConstStruct([]llvm.Value{ llvm.Undef(slicePtr.Type()), llvm.Undef(c.uintptrType), llvm.Undef(c.uintptrType), }, false) slice = c.builder.CreateInsertValue(slice, slicePtr, 0, "") slice = c.builder.CreateInsertValue(slice, sliceLen, 1, "") slice = c.builder.CreateInsertValue(slice, sliceCap, 2, "") return slice, nil case *ssa.Next: rangeVal := expr.Iter.(*ssa.Range).X llvmRangeVal, err := c.parseExpr(frame, rangeVal) if err != nil { return llvm.Value{}, err } it, err := c.parseExpr(frame, expr.Iter) if err != nil { return llvm.Value{}, err } if expr.IsString { return c.createRuntimeCall("stringNext", []llvm.Value{llvmRangeVal, it}, "range.next"), nil } else { // map llvmKeyType, err := c.getLLVMType(rangeVal.Type().Underlying().(*types.Map).Key()) if err != nil { return llvm.Value{}, err } llvmValueType, err := c.getLLVMType(rangeVal.Type().Underlying().(*types.Map).Elem()) if err != nil { return llvm.Value{}, err } mapKeyAlloca := c.builder.CreateAlloca(llvmKeyType, "range.key") mapKeyPtr := c.builder.CreateBitCast(mapKeyAlloca, c.i8ptrType, "range.keyptr") mapValueAlloca := c.builder.CreateAlloca(llvmValueType, "range.value") mapValuePtr := c.builder.CreateBitCast(mapValueAlloca, c.i8ptrType, "range.valueptr") ok := c.createRuntimeCall("hashmapNext", []llvm.Value{llvmRangeVal, it, mapKeyPtr, mapValuePtr}, "range.next") tuple := llvm.Undef(c.ctx.StructType([]llvm.Type{c.ctx.Int1Type(), llvmKeyType, llvmValueType}, false)) tuple = c.builder.CreateInsertValue(tuple, ok, 0, "") tuple = c.builder.CreateInsertValue(tuple, c.builder.CreateLoad(mapKeyAlloca, ""), 1, "") tuple = c.builder.CreateInsertValue(tuple, c.builder.CreateLoad(mapValueAlloca, ""), 2, "") return tuple, nil } case *ssa.Phi: t, err := c.getLLVMType(expr.Type()) if err != nil { return llvm.Value{}, err } phi := c.builder.CreatePHI(t, "") frame.phis = append(frame.phis, Phi{expr, phi}) return phi, nil case *ssa.Range: var iteratorType llvm.Type switch typ := expr.X.Type().Underlying().(type) { case *types.Basic: // string iteratorType = c.mod.GetTypeByName("runtime.stringIterator") case *types.Map: iteratorType = c.mod.GetTypeByName("runtime.hashmapIterator") default: panic("unknown type in range: " + typ.String()) } it := c.builder.CreateAlloca(iteratorType, "range.it") zero, err := c.getZeroValue(iteratorType) if err != nil { return llvm.Value{}, nil } c.builder.CreateStore(zero, it) return it, nil case *ssa.Slice: if expr.Max != nil { return llvm.Value{}, errors.New("todo: full slice expressions (with max): " + expr.Type().String()) } value, err := c.parseExpr(frame, expr.X) if err != nil { return llvm.Value{}, err } var lowType, highType *types.Basic var low, high llvm.Value if expr.Low != nil { lowType = expr.Low.Type().(*types.Basic) low, err = c.parseExpr(frame, expr.Low) if err != nil { return llvm.Value{}, nil } if low.Type().IntTypeWidth() < c.uintptrType.IntTypeWidth() { if lowType.Info()&types.IsUnsigned != 0 { low = c.builder.CreateZExt(low, c.uintptrType, "") } else { low = c.builder.CreateSExt(low, c.uintptrType, "") } } } else { lowType = types.Typ[types.Int] low = llvm.ConstInt(c.intType, 0, false) } if expr.High != nil { highType = expr.High.Type().(*types.Basic) high, err = c.parseExpr(frame, expr.High) if err != nil { return llvm.Value{}, nil } if high.Type().IntTypeWidth() < c.uintptrType.IntTypeWidth() { if highType.Info()&types.IsUnsigned != 0 { high = c.builder.CreateZExt(high, c.uintptrType, "") } else { high = c.builder.CreateSExt(high, c.uintptrType, "") } } } else { highType = types.Typ[types.Uintptr] } switch typ := expr.X.Type().Underlying().(type) { case *types.Pointer: // pointer to array // slice an array length := typ.Elem().(*types.Array).Len() llvmLen := llvm.ConstInt(c.uintptrType, uint64(length), false) if high.IsNil() { high = llvmLen } indices := []llvm.Value{ llvm.ConstInt(c.ctx.Int32Type(), 0, false), low, } // This check is optimized away in most cases. c.emitSliceBoundsCheck(frame, llvmLen, low, high, lowType, highType) if c.targetData.TypeAllocSize(high.Type()) > c.targetData.TypeAllocSize(c.uintptrType) { high = c.builder.CreateTrunc(high, c.uintptrType, "") } if c.targetData.TypeAllocSize(low.Type()) > c.targetData.TypeAllocSize(c.uintptrType) { low = c.builder.CreateTrunc(low, c.uintptrType, "") } sliceLen := c.builder.CreateSub(high, low, "slice.len") slicePtr := c.builder.CreateGEP(value, indices, "slice.ptr") sliceCap := c.builder.CreateSub(llvmLen, low, "slice.cap") slice := c.ctx.ConstStruct([]llvm.Value{ llvm.Undef(slicePtr.Type()), llvm.Undef(c.uintptrType), llvm.Undef(c.uintptrType), }, false) slice = c.builder.CreateInsertValue(slice, slicePtr, 0, "") slice = c.builder.CreateInsertValue(slice, sliceLen, 1, "") slice = c.builder.CreateInsertValue(slice, sliceCap, 2, "") return slice, nil case *types.Slice: // slice a slice oldPtr := c.builder.CreateExtractValue(value, 0, "") oldLen := c.builder.CreateExtractValue(value, 1, "") oldCap := c.builder.CreateExtractValue(value, 2, "") if high.IsNil() { high = oldLen } c.emitSliceBoundsCheck(frame, oldCap, low, high, lowType, highType) if c.targetData.TypeAllocSize(low.Type()) > c.targetData.TypeAllocSize(c.uintptrType) { low = c.builder.CreateTrunc(low, c.uintptrType, "") } if c.targetData.TypeAllocSize(high.Type()) > c.targetData.TypeAllocSize(c.uintptrType) { high = c.builder.CreateTrunc(high, c.uintptrType, "") } newPtr := c.builder.CreateGEP(oldPtr, []llvm.Value{low}, "") newLen := c.builder.CreateSub(high, low, "") newCap := c.builder.CreateSub(oldCap, low, "") slice := c.ctx.ConstStruct([]llvm.Value{ llvm.Undef(newPtr.Type()), llvm.Undef(c.uintptrType), llvm.Undef(c.uintptrType), }, false) slice = c.builder.CreateInsertValue(slice, newPtr, 0, "") slice = c.builder.CreateInsertValue(slice, newLen, 1, "") slice = c.builder.CreateInsertValue(slice, newCap, 2, "") return slice, nil case *types.Basic: if typ.Info()&types.IsString == 0 { return llvm.Value{}, errors.New("unknown slice type: " + typ.String()) } // slice a string oldPtr := c.builder.CreateExtractValue(value, 0, "") oldLen := c.builder.CreateExtractValue(value, 1, "") if high.IsNil() { high = oldLen } c.emitSliceBoundsCheck(frame, oldLen, low, high, lowType, highType) newPtr := c.builder.CreateGEP(oldPtr, []llvm.Value{low}, "") newLen := c.builder.CreateSub(high, low, "") str, err := c.getZeroValue(c.mod.GetTypeByName("runtime._string")) if err != nil { return llvm.Value{}, err } str = c.builder.CreateInsertValue(str, newPtr, 0, "") str = c.builder.CreateInsertValue(str, newLen, 1, "") return str, nil default: return llvm.Value{}, errors.New("unknown slice type: " + typ.String()) } case *ssa.TypeAssert: return c.parseTypeAssert(frame, expr) case *ssa.UnOp: return c.parseUnOp(frame, expr) default: return llvm.Value{}, errors.New("todo: unknown expression: " + expr.String()) } } func (c *Compiler) parseBinOp(op token.Token, typ types.Type, x, y llvm.Value) (llvm.Value, error) { switch typ := typ.(type) { case *types.Basic: if typ.Info()&types.IsInteger != 0 { // Operations on integers signed := typ.Info()&types.IsUnsigned == 0 switch op { case token.ADD: // + return c.builder.CreateAdd(x, y, ""), nil case token.SUB: // - return c.builder.CreateSub(x, y, ""), nil case token.MUL: // * return c.builder.CreateMul(x, y, ""), nil case token.QUO: // / if signed { return c.builder.CreateSDiv(x, y, ""), nil } else { return c.builder.CreateUDiv(x, y, ""), nil } case token.REM: // % if signed { return c.builder.CreateSRem(x, y, ""), nil } else { return c.builder.CreateURem(x, y, ""), nil } case token.AND: // & return c.builder.CreateAnd(x, y, ""), nil case token.OR: // | return c.builder.CreateOr(x, y, ""), nil case token.XOR: // ^ return c.builder.CreateXor(x, y, ""), nil case token.SHL, token.SHR: sizeX := c.targetData.TypeAllocSize(x.Type()) sizeY := c.targetData.TypeAllocSize(y.Type()) if sizeX > sizeY { // x and y must have equal sizes, make Y bigger in this case. // y is unsigned, this has been checked by the Go type checker. y = c.builder.CreateZExt(y, x.Type(), "") } else if sizeX < sizeY { // What about shifting more than the integer width? // I'm not entirely sure what the Go spec is on that, but as // Intel CPUs have undefined behavior when shifting more // than the integer width I'm assuming it is also undefined // in Go. y = c.builder.CreateTrunc(y, x.Type(), "") } switch op { case token.SHL: // << return c.builder.CreateShl(x, y, ""), nil case token.SHR: // >> if signed { return c.builder.CreateAShr(x, y, ""), nil } else { return c.builder.CreateLShr(x, y, ""), nil } default: panic("unreachable") } case token.EQL: // == return c.builder.CreateICmp(llvm.IntEQ, x, y, ""), nil case token.NEQ: // != return c.builder.CreateICmp(llvm.IntNE, x, y, ""), nil case token.AND_NOT: // &^ // Go specific. Calculate "and not" with x & (~y) inv := c.builder.CreateNot(y, "") // ~y return c.builder.CreateAnd(x, inv, ""), nil case token.LSS: // < if signed { return c.builder.CreateICmp(llvm.IntSLT, x, y, ""), nil } else { return c.builder.CreateICmp(llvm.IntULT, x, y, ""), nil } case token.LEQ: // <= if signed { return c.builder.CreateICmp(llvm.IntSLE, x, y, ""), nil } else { return c.builder.CreateICmp(llvm.IntULE, x, y, ""), nil } case token.GTR: // > if signed { return c.builder.CreateICmp(llvm.IntSGT, x, y, ""), nil } else { return c.builder.CreateICmp(llvm.IntUGT, x, y, ""), nil } case token.GEQ: // >= if signed { return c.builder.CreateICmp(llvm.IntSGE, x, y, ""), nil } else { return c.builder.CreateICmp(llvm.IntUGE, x, y, ""), nil } default: return llvm.Value{}, errors.New("todo: binop on integer: " + op.String()) } } else if typ.Info()&types.IsFloat != 0 { // Operations on floats switch op { case token.ADD: // + return c.builder.CreateFAdd(x, y, ""), nil case token.SUB: // - return c.builder.CreateFSub(x, y, ""), nil case token.MUL: // * return c.builder.CreateFMul(x, y, ""), nil case token.QUO: // / return c.builder.CreateFDiv(x, y, ""), nil case token.REM: // % return c.builder.CreateFRem(x, y, ""), nil case token.EQL: // == return c.builder.CreateFCmp(llvm.FloatOEQ, x, y, ""), nil case token.NEQ: // != return c.builder.CreateFCmp(llvm.FloatONE, x, y, ""), nil case token.LSS: // < return c.builder.CreateFCmp(llvm.FloatOLT, x, y, ""), nil case token.LEQ: // <= return c.builder.CreateFCmp(llvm.FloatOLE, x, y, ""), nil case token.GTR: // > return c.builder.CreateFCmp(llvm.FloatOGT, x, y, ""), nil case token.GEQ: // >= return c.builder.CreateFCmp(llvm.FloatOGE, x, y, ""), nil default: return llvm.Value{}, errors.New("todo: binop on float: " + op.String()) } } else if typ.Info()&types.IsBoolean != 0 { // Operations on booleans switch op { case token.EQL: // == return c.builder.CreateICmp(llvm.IntEQ, x, y, ""), nil case token.NEQ: // != return c.builder.CreateICmp(llvm.IntNE, x, y, ""), nil default: return llvm.Value{}, errors.New("todo: binop on boolean: " + op.String()) } } else if typ.Kind() == types.UnsafePointer { // Operations on pointers switch op { case token.EQL: // == return c.builder.CreateICmp(llvm.IntEQ, x, y, ""), nil case token.NEQ: // != return c.builder.CreateICmp(llvm.IntNE, x, y, ""), nil default: return llvm.Value{}, errors.New("todo: binop on pointer: " + op.String()) } } else if typ.Info()&types.IsString != 0 { // Operations on strings switch op { case token.ADD: // + return c.createRuntimeCall("stringConcat", []llvm.Value{x, y}, ""), nil case token.EQL: // == return c.createRuntimeCall("stringEqual", []llvm.Value{x, y}, ""), nil case token.NEQ: // != result := c.createRuntimeCall("stringEqual", []llvm.Value{x, y}, "") return c.builder.CreateNot(result, ""), nil case token.LSS: // < return c.createRuntimeCall("stringLess", []llvm.Value{x, y}, ""), nil case token.LEQ: // <= result := c.createRuntimeCall("stringLess", []llvm.Value{y, x}, "") return c.builder.CreateNot(result, ""), nil case token.GTR: // > result := c.createRuntimeCall("stringLess", []llvm.Value{x, y}, "") return c.builder.CreateNot(result, ""), nil case token.GEQ: // >= return c.createRuntimeCall("stringLess", []llvm.Value{y, x}, ""), nil default: return llvm.Value{}, errors.New("todo: binop on string: " + op.String()) } } else { return llvm.Value{}, errors.New("todo: unknown basic type in binop: " + typ.String()) } case *types.Signature: if c.ir.SignatureNeedsContext(typ) { // This is a closure, not a function pointer. Get the underlying // function pointer. // This is safe: function pointers are generally not comparable // against each other, only against nil. So one or both has to be // nil, so we can ignore the contents of the closure. x = c.builder.CreateExtractValue(x, 1, "") y = c.builder.CreateExtractValue(y, 1, "") } switch op { case token.EQL: // == return c.builder.CreateICmp(llvm.IntEQ, x, y, ""), nil case token.NEQ: // != return c.builder.CreateICmp(llvm.IntNE, x, y, ""), nil default: return llvm.Value{}, errors.New("binop on signature: " + op.String()) } case *types.Interface: switch op { case token.EQL, token.NEQ: // ==, != result := c.createRuntimeCall("interfaceEqual", []llvm.Value{x, y}, "") if op == token.NEQ { result = c.builder.CreateNot(result, "") } return result, nil default: return llvm.Value{}, errors.New("binop on interface: " + op.String()) } case *types.Map, *types.Pointer: // Maps are in general not comparable, but can be compared against nil // (which is a nil pointer). This means they can be trivially compared // by treating them as a pointer. switch op { case token.EQL: // == return c.builder.CreateICmp(llvm.IntEQ, x, y, ""), nil case token.NEQ: // != return c.builder.CreateICmp(llvm.IntNE, x, y, ""), nil default: return llvm.Value{}, errors.New("todo: binop on pointer: " + op.String()) } case *types.Slice: // Slices are in general not comparable, but can be compared against // nil. Assume at least one of them is nil to make the code easier. xPtr := c.builder.CreateExtractValue(x, 0, "") yPtr := c.builder.CreateExtractValue(y, 0, "") switch op { case token.EQL: // == return c.builder.CreateICmp(llvm.IntEQ, xPtr, yPtr, ""), nil case token.NEQ: // != return c.builder.CreateICmp(llvm.IntNE, xPtr, yPtr, ""), nil default: return llvm.Value{}, errors.New("todo: binop on slice: " + op.String()) } case *types.Struct: // Compare each struct field and combine the result. From the spec: // Struct values are comparable if all their fields are comparable. // Two struct values are equal if their corresponding non-blank // fields are equal. result := llvm.ConstInt(c.ctx.Int1Type(), 1, true) for i := 0; i < typ.NumFields(); i++ { if typ.Field(i).Name() == "_" { // skip blank fields continue } fieldType := typ.Field(i).Type() xField := c.builder.CreateExtractValue(x, i, "") yField := c.builder.CreateExtractValue(y, i, "") fieldEqual, err := c.parseBinOp(token.EQL, fieldType, xField, yField) if err != nil { return llvm.Value{}, err } result = c.builder.CreateAnd(result, fieldEqual, "") } switch op { case token.EQL: // == return result, nil case token.NEQ: // != return c.builder.CreateNot(result, ""), nil default: return llvm.Value{}, errors.New("unknown: binop on struct: " + op.String()) } return result, nil default: return llvm.Value{}, errors.New("todo: binop type: " + typ.String()) } } func (c *Compiler) parseConst(prefix string, expr *ssa.Const) (llvm.Value, error) { switch typ := expr.Type().Underlying().(type) { case *types.Basic: llvmType, err := c.getLLVMType(typ) if err != nil { return llvm.Value{}, err } if typ.Info()&types.IsBoolean != 0 { b := constant.BoolVal(expr.Value) n := uint64(0) if b { n = 1 } return llvm.ConstInt(llvmType, n, false), nil } else if typ.Info()&types.IsString != 0 { str := constant.StringVal(expr.Value) strLen := llvm.ConstInt(c.uintptrType, uint64(len(str)), false) objname := prefix + "$string" global := llvm.AddGlobal(c.mod, llvm.ArrayType(c.ctx.Int8Type(), len(str)), objname) global.SetInitializer(c.ctx.ConstString(str, false)) global.SetLinkage(llvm.InternalLinkage) global.SetGlobalConstant(true) global.SetUnnamedAddr(true) zero := llvm.ConstInt(c.ctx.Int32Type(), 0, false) strPtr := c.builder.CreateInBoundsGEP(global, []llvm.Value{zero, zero}, "") strObj := llvm.ConstNamedStruct(c.mod.GetTypeByName("runtime._string"), []llvm.Value{strPtr, strLen}) return strObj, nil } else if typ.Kind() == types.UnsafePointer { if !expr.IsNil() { value, _ := constant.Uint64Val(expr.Value) return llvm.ConstIntToPtr(llvm.ConstInt(c.uintptrType, value, false), c.i8ptrType), nil } return llvm.ConstNull(c.i8ptrType), nil } else if typ.Info()&types.IsUnsigned != 0 { n, _ := constant.Uint64Val(expr.Value) return llvm.ConstInt(llvmType, n, false), nil } else if typ.Info()&types.IsInteger != 0 { // signed n, _ := constant.Int64Val(expr.Value) return llvm.ConstInt(llvmType, uint64(n), true), nil } else if typ.Info()&types.IsFloat != 0 { n, _ := constant.Float64Val(expr.Value) return llvm.ConstFloat(llvmType, n), nil } else if typ.Kind() == types.Complex128 { r, err := c.parseConst(prefix, ssa.NewConst(constant.Real(expr.Value), types.Typ[types.Float64])) if err != nil { return llvm.Value{}, err } i, err := c.parseConst(prefix, ssa.NewConst(constant.Imag(expr.Value), types.Typ[types.Float64])) if err != nil { return llvm.Value{}, err } cplx := llvm.Undef(llvm.VectorType(c.ctx.DoubleType(), 2)) cplx = c.builder.CreateInsertElement(cplx, r, llvm.ConstInt(c.ctx.Int8Type(), 0, false), "") cplx = c.builder.CreateInsertElement(cplx, i, llvm.ConstInt(c.ctx.Int8Type(), 1, false), "") return cplx, nil } else { return llvm.Value{}, errors.New("todo: unknown constant: " + expr.String()) } case *types.Signature: if expr.Value != nil { return llvm.Value{}, errors.New("non-nil signature constant") } sig, err := c.getLLVMType(expr.Type()) if err != nil { return llvm.Value{}, err } return c.getZeroValue(sig) case *types.Interface: if expr.Value != nil { return llvm.Value{}, errors.New("non-nil interface constant") } // Create a generic nil interface with no dynamic type (typecode=0). fields := []llvm.Value{ llvm.ConstInt(c.ctx.Int16Type(), 0, false), llvm.ConstPointerNull(c.i8ptrType), } itf := llvm.ConstNamedStruct(c.mod.GetTypeByName("runtime._interface"), fields) return itf, nil case *types.Pointer: if expr.Value != nil { return llvm.Value{}, errors.New("non-nil pointer constant") } llvmType, err := c.getLLVMType(typ) if err != nil { return llvm.Value{}, err } return llvm.ConstPointerNull(llvmType), nil case *types.Slice: if expr.Value != nil { return llvm.Value{}, errors.New("non-nil slice constant") } elemType, err := c.getLLVMType(typ.Elem()) if err != nil { return llvm.Value{}, err } llvmPtr := llvm.ConstPointerNull(llvm.PointerType(elemType, 0)) llvmLen := llvm.ConstInt(c.uintptrType, 0, false) slice := c.ctx.ConstStruct([]llvm.Value{ llvmPtr, // backing array llvmLen, // len llvmLen, // cap }, false) return slice, nil case *types.Map: if !expr.IsNil() { // I believe this is not allowed by the Go spec. panic("non-nil map constant") } llvmType, err := c.getLLVMType(typ) if err != nil { return llvm.Value{}, err } return c.getZeroValue(llvmType) default: return llvm.Value{}, errors.New("todo: unknown constant: " + expr.String()) } } func (c *Compiler) parseConvert(typeFrom, typeTo types.Type, value llvm.Value) (llvm.Value, error) { llvmTypeFrom := value.Type() llvmTypeTo, err := c.getLLVMType(typeTo) if err != nil { return llvm.Value{}, err } // Conversion between unsafe.Pointer and uintptr. isPtrFrom := isPointer(typeFrom.Underlying()) isPtrTo := isPointer(typeTo.Underlying()) if isPtrFrom && !isPtrTo { return c.builder.CreatePtrToInt(value, llvmTypeTo, ""), nil } else if !isPtrFrom && isPtrTo { return c.builder.CreateIntToPtr(value, llvmTypeTo, ""), nil } // Conversion between pointers and unsafe.Pointer. if isPtrFrom && isPtrTo { return c.builder.CreateBitCast(value, llvmTypeTo, ""), nil } switch typeTo := typeTo.Underlying().(type) { case *types.Basic: sizeFrom := c.targetData.TypeAllocSize(llvmTypeFrom) if typeTo.Info()&types.IsString != 0 { switch typeFrom := typeFrom.Underlying().(type) { case *types.Basic: // Assume a Unicode code point, as that is the only possible // value here. // Cast to an i32 value as expected by // runtime.stringFromUnicode. if sizeFrom > 4 { value = c.builder.CreateTrunc(value, c.ctx.Int32Type(), "") } else if sizeFrom < 4 && typeTo.Info()&types.IsUnsigned != 0 { value = c.builder.CreateZExt(value, c.ctx.Int32Type(), "") } else if sizeFrom < 4 { value = c.builder.CreateSExt(value, c.ctx.Int32Type(), "") } return c.createRuntimeCall("stringFromUnicode", []llvm.Value{value}, ""), nil case *types.Slice: switch typeFrom.Elem().(*types.Basic).Kind() { case types.Byte: return c.createRuntimeCall("stringFromBytes", []llvm.Value{value}, ""), nil default: return llvm.Value{}, errors.New("todo: convert to string: " + typeFrom.String()) } default: return llvm.Value{}, errors.New("todo: convert to string: " + typeFrom.String()) } } typeFrom := typeFrom.Underlying().(*types.Basic) sizeTo := c.targetData.TypeAllocSize(llvmTypeTo) if typeFrom.Info()&types.IsInteger != 0 && typeTo.Info()&types.IsInteger != 0 { // Conversion between two integers. if sizeFrom > sizeTo { return c.builder.CreateTrunc(value, llvmTypeTo, ""), nil } else if typeTo.Info()&types.IsUnsigned != 0 { // if unsigned return c.builder.CreateZExt(value, llvmTypeTo, ""), nil } else { // if signed return c.builder.CreateSExt(value, llvmTypeTo, ""), nil } } if typeFrom.Info()&types.IsFloat != 0 && typeTo.Info()&types.IsFloat != 0 { // Conversion between two floats. if sizeFrom > sizeTo { return c.builder.CreateFPTrunc(value, llvmTypeTo, ""), nil } else if sizeFrom < sizeTo { return c.builder.CreateFPExt(value, llvmTypeTo, ""), nil } else { return value, nil } } if typeFrom.Info()&types.IsFloat != 0 && typeTo.Info()&types.IsInteger != 0 { // Conversion from float to int. if typeTo.Info()&types.IsUnsigned != 0 { // if unsigned return c.builder.CreateFPToUI(value, llvmTypeTo, ""), nil } else { // if signed return c.builder.CreateFPToSI(value, llvmTypeTo, ""), nil } } if typeFrom.Info()&types.IsInteger != 0 && typeTo.Info()&types.IsFloat != 0 { // Conversion from int to float. if typeFrom.Info()&types.IsUnsigned != 0 { // if unsigned return c.builder.CreateUIToFP(value, llvmTypeTo, ""), nil } else { // if signed return c.builder.CreateSIToFP(value, llvmTypeTo, ""), nil } } if typeFrom.Kind() == types.Complex128 && typeTo.Kind() == types.Complex64 { // Conversion from complex128 to complex64. r := c.builder.CreateExtractElement(value, llvm.ConstInt(c.ctx.Int32Type(), 0, false), "real.f64") i := c.builder.CreateExtractElement(value, llvm.ConstInt(c.ctx.Int32Type(), 1, false), "imag.f64") r = c.builder.CreateFPTrunc(r, c.ctx.FloatType(), "real.f32") i = c.builder.CreateFPTrunc(i, c.ctx.FloatType(), "imag.f32") cplx := llvm.Undef(llvm.VectorType(c.ctx.FloatType(), 2)) cplx = c.builder.CreateInsertElement(cplx, r, llvm.ConstInt(c.ctx.Int8Type(), 0, false), "") cplx = c.builder.CreateInsertElement(cplx, i, llvm.ConstInt(c.ctx.Int8Type(), 1, false), "") return cplx, nil } if typeFrom.Kind() == types.Complex64 && typeTo.Kind() == types.Complex128 { // Conversion from complex64 to complex128. r := c.builder.CreateExtractElement(value, llvm.ConstInt(c.ctx.Int32Type(), 0, false), "real.f32") i := c.builder.CreateExtractElement(value, llvm.ConstInt(c.ctx.Int32Type(), 1, false), "imag.f32") r = c.builder.CreateFPExt(r, c.ctx.DoubleType(), "real.f64") i = c.builder.CreateFPExt(i, c.ctx.DoubleType(), "imag.f64") cplx := llvm.Undef(llvm.VectorType(c.ctx.DoubleType(), 2)) cplx = c.builder.CreateInsertElement(cplx, r, llvm.ConstInt(c.ctx.Int8Type(), 0, false), "") cplx = c.builder.CreateInsertElement(cplx, i, llvm.ConstInt(c.ctx.Int8Type(), 1, false), "") return cplx, nil } return llvm.Value{}, errors.New("todo: convert: basic non-integer type: " + typeFrom.String() + " -> " + typeTo.String()) case *types.Slice: if basic, ok := typeFrom.(*types.Basic); !ok || basic.Info()&types.IsString == 0 { panic("can only convert from a string to a slice") } elemType := typeTo.Elem().Underlying().(*types.Basic) // must be byte or rune switch elemType.Kind() { case types.Byte: return c.createRuntimeCall("stringToBytes", []llvm.Value{value}, ""), nil default: return llvm.Value{}, errors.New("todo: convert from string: " + elemType.String()) } default: return llvm.Value{}, errors.New("todo: convert " + typeTo.String() + " <- " + typeFrom.String()) } } func (c *Compiler) parseMakeClosure(frame *Frame, expr *ssa.MakeClosure) (llvm.Value, error) { if len(expr.Bindings) == 0 { panic("unexpected: MakeClosure without bound variables") } f := c.ir.GetFunction(expr.Fn.(*ssa.Function)) if !c.ir.FunctionNeedsContext(f) { // Maybe AnalyseFunctionPointers didn't run? panic("MakeClosure on function signature without context") } // Collect all bound variables. boundVars := make([]llvm.Value, 0, len(expr.Bindings)) boundVarTypes := make([]llvm.Type, 0, len(expr.Bindings)) for _, binding := range expr.Bindings { // The context stores the bound variables. llvmBoundVar, err := c.parseExpr(frame, binding) if err != nil { return llvm.Value{}, err } boundVars = append(boundVars, llvmBoundVar) boundVarTypes = append(boundVarTypes, llvmBoundVar.Type()) } contextType := c.ctx.StructType(boundVarTypes, false) // Allocate memory for the context. contextAlloc := llvm.Value{} contextHeapAlloc := llvm.Value{} if c.targetData.TypeAllocSize(contextType) <= c.targetData.TypeAllocSize(c.i8ptrType) { // Context fits in a pointer - e.g. when it is a pointer. Store it // directly in the stack after a convert. // Because contextType is a struct and we have to cast it to a *i8, // store it in an alloca first for bitcasting (store+bitcast+load). contextAlloc = c.builder.CreateAlloca(contextType, "") } else { // Context is bigger than a pointer, so allocate it on the heap. size := c.targetData.TypeAllocSize(contextType) sizeValue := llvm.ConstInt(c.uintptrType, size, false) contextHeapAlloc = c.createRuntimeCall("alloc", []llvm.Value{sizeValue}, "") contextAlloc = c.builder.CreateBitCast(contextHeapAlloc, llvm.PointerType(contextType, 0), "") } // Store all bound variables in the alloca or heap pointer. for i, boundVar := range boundVars { indices := []llvm.Value{ llvm.ConstInt(c.ctx.Int32Type(), 0, false), llvm.ConstInt(c.ctx.Int32Type(), uint64(i), false), } gep := c.builder.CreateInBoundsGEP(contextAlloc, indices, "") c.builder.CreateStore(boundVar, gep) } context := llvm.Value{} if c.targetData.TypeAllocSize(contextType) <= c.targetData.TypeAllocSize(c.i8ptrType) { // Load value (as *i8) from the alloca. contextAlloc = c.builder.CreateBitCast(contextAlloc, llvm.PointerType(c.i8ptrType, 0), "") context = c.builder.CreateLoad(contextAlloc, "") } else { // Get the original heap allocation pointer, which already is an // *i8. context = contextHeapAlloc } // Get the function signature type, which is a closure type. // A closure is a tuple of {context, function pointer}. typ, err := c.getLLVMType(f.Signature) if err != nil { return llvm.Value{}, err } // Create the closure, which is a struct: {context, function pointer}. closure, err := c.getZeroValue(typ) if err != nil { return llvm.Value{}, err } closure = c.builder.CreateInsertValue(closure, f.LLVMFn, 1, "") closure = c.builder.CreateInsertValue(closure, context, 0, "") return closure, nil } func (c *Compiler) parseUnOp(frame *Frame, unop *ssa.UnOp) (llvm.Value, error) { x, err := c.parseExpr(frame, unop.X) if err != nil { return llvm.Value{}, err } switch unop.Op { case token.NOT: // !x return c.builder.CreateNot(x, ""), nil case token.SUB: // -x if typ, ok := unop.X.Type().Underlying().(*types.Basic); ok { if typ.Info()&types.IsInteger != 0 { return c.builder.CreateSub(llvm.ConstInt(x.Type(), 0, false), x, ""), nil } else if typ.Info()&types.IsFloat != 0 { return c.builder.CreateFSub(llvm.ConstFloat(x.Type(), 0.0), x, ""), nil } else { return llvm.Value{}, errors.New("todo: unknown basic type for negate: " + typ.String()) } } else { return llvm.Value{}, errors.New("todo: unknown type for negate: " + unop.X.Type().Underlying().String()) } case token.MUL: // *x, dereference pointer valType := unop.X.Type().(*types.Pointer).Elem() if c.targetData.TypeAllocSize(x.Type().ElementType()) == 0 { // zero-length data return c.getZeroValue(x.Type().ElementType()) } else { load := c.builder.CreateLoad(x, "") if c.ir.IsVolatile(valType) { // Volatile load, for memory-mapped registers. load.SetVolatile(true) } return load, nil } case token.XOR: // ^x, toggle all bits in integer return c.builder.CreateXor(x, llvm.ConstInt(x.Type(), ^uint64(0), false), ""), nil default: return llvm.Value{}, errors.New("todo: unknown unop") } } // IR returns the whole IR as a human-readable string. func (c *Compiler) IR() string { return c.mod.String() } func (c *Compiler) Verify() error { return llvm.VerifyModule(c.mod, llvm.PrintMessageAction) } func (c *Compiler) ApplyFunctionSections() { // Put every function in a separate section. This makes it possible for the // linker to remove dead code (-ffunction-sections). llvmFn := c.mod.FirstFunction() for !llvmFn.IsNil() { if !llvmFn.IsDeclaration() { name := llvmFn.Name() llvmFn.SetSection(".text." + name) } llvmFn = llvm.NextFunction(llvmFn) } } // Turn all global constants into global variables. This works around a // limitation on Harvard architectures (e.g. AVR), where constant and // non-constant pointers point to a different address space. func (c *Compiler) NonConstGlobals() { global := c.mod.FirstGlobal() for !global.IsNil() { global.SetGlobalConstant(false) global = llvm.NextGlobal(global) } } // Replace i64 in an external function with a stack-allocated i64*, to work // around the lack of 64-bit integers in JavaScript (commonly used together with // WebAssembly). Once that's resolved, this pass may be avoided. // https://github.com/WebAssembly/design/issues/1172 func (c *Compiler) ExternalInt64AsPtr() error { int64Type := c.ctx.Int64Type() int64PtrType := llvm.PointerType(int64Type, 0) for fn := c.mod.FirstFunction(); !fn.IsNil(); fn = llvm.NextFunction(fn) { if fn.Linkage() != llvm.ExternalLinkage { // Only change externally visible functions (exports and imports). continue } if strings.HasPrefix(fn.Name(), "llvm.") { // Do not try to modify the signature of internal LLVM functions. continue } hasInt64 := false paramTypes := []llvm.Type{} // Check return type for 64-bit integer. fnType := fn.Type().ElementType() returnType := fnType.ReturnType() if returnType == int64Type { hasInt64 = true paramTypes = append(paramTypes, int64PtrType) returnType = c.ctx.VoidType() } // Check param types for 64-bit integers. for param := fn.FirstParam(); !param.IsNil(); param = llvm.NextParam(param) { if param.Type() == int64Type { hasInt64 = true paramTypes = append(paramTypes, int64PtrType) } else { paramTypes = append(paramTypes, param.Type()) } } if !hasInt64 { // No i64 in the paramter list. continue } // Add $i64wrapper to the real function name as it is only used // internally. // Add a new function with the correct signature that is exported. name := fn.Name() fn.SetName(name + "$i64wrap") externalFnType := llvm.FunctionType(returnType, paramTypes, fnType.IsFunctionVarArg()) externalFn := llvm.AddFunction(c.mod, name, externalFnType) if fn.IsDeclaration() { // Just a declaration: the definition doesn't exist on the Go side // so it cannot be called from external code. // Update all users to call the external function. // The old $i64wrapper function could be removed, but it may as well // be left in place. for use := fn.FirstUse(); !use.IsNil(); use = use.NextUse() { call := use.User() c.builder.SetInsertPointBefore(call) callParams := []llvm.Value{} var retvalAlloca llvm.Value if fnType.ReturnType() == int64Type { retvalAlloca = c.builder.CreateAlloca(int64Type, "i64asptr") callParams = append(callParams, retvalAlloca) } for i := 0; i < call.OperandsCount()-1; i++ { operand := call.Operand(i) if operand.Type() == int64Type { // Pass a stack-allocated pointer instead of the value // itself. alloca := c.builder.CreateAlloca(int64Type, "i64asptr") c.builder.CreateStore(operand, alloca) callParams = append(callParams, alloca) } else { // Unchanged parameter. callParams = append(callParams, operand) } } if fnType.ReturnType() == int64Type { // Pass a stack-allocated pointer as the first parameter // where the return value should be stored, instead of using // the regular return value. c.builder.CreateCall(externalFn, callParams, call.Name()) returnValue := c.builder.CreateLoad(retvalAlloca, "retval") call.ReplaceAllUsesWith(returnValue) call.EraseFromParentAsInstruction() } else { newCall := c.builder.CreateCall(externalFn, callParams, call.Name()) call.ReplaceAllUsesWith(newCall) call.EraseFromParentAsInstruction() } } } else { // The function has a definition in Go. This means that it may still // be called both Go and from external code. // Keep existing calls with the existing convention in place (for // better performance), but export a new wrapper function with the // correct calling convention. fn.SetLinkage(llvm.InternalLinkage) fn.SetUnnamedAddr(true) entryBlock := llvm.AddBasicBlock(externalFn, "entry") c.builder.SetInsertPointAtEnd(entryBlock) var callParams []llvm.Value if fnType.ReturnType() == int64Type { return errors.New("todo: i64 return value in exported function") } for i, origParam := range fn.Params() { paramValue := externalFn.Param(i) if origParam.Type() == int64Type { paramValue = c.builder.CreateLoad(paramValue, "i64") } callParams = append(callParams, paramValue) } retval := c.builder.CreateCall(fn, callParams, "") if retval.Type().TypeKind() == llvm.VoidTypeKind { c.builder.CreateRetVoid() } else { c.builder.CreateRet(retval) } } } return nil } // Emit object file (.o). func (c *Compiler) EmitObject(path string) error { llvmBuf, err := c.machine.EmitToMemoryBuffer(c.mod, llvm.ObjectFile) if err != nil { return err } return c.writeFile(llvmBuf.Bytes(), path) } // Emit LLVM bitcode file (.bc). func (c *Compiler) EmitBitcode(path string) error { data := llvm.WriteBitcodeToMemoryBuffer(c.mod).Bytes() return c.writeFile(data, path) } // Emit LLVM IR source file (.ll). func (c *Compiler) EmitText(path string) error { data := []byte(c.mod.String()) return c.writeFile(data, path) } // Write the data to the file specified by path. func (c *Compiler) writeFile(data []byte, path string) error { // Write output to file f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666) if err != nil { return err } _, err = f.Write(data) if err != nil { return err } return f.Close() }
1
6,100
There is a very similar line `lowType = expr.Low.Type().(*types.Basic)` a few lines above this line. Can you change that in the same way?
tinygo-org-tinygo
go
@@ -0,0 +1,19 @@ +/* + * Copyright ConsenSys AG. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ +package org.hyperledger.besu.consensus.merge.blockcreation; + +import org.hyperledger.besu.ethereum.blockcreation.MiningCoordinator; + +public interface MergeMiningCoordinator extends MiningCoordinator {}
1
1
26,393
New files should be copyright Hyperledger Besu Contributors.
hyperledger-besu
java
@@ -34,5 +34,18 @@ module Bolt sftp.upload!(source, destination) end end + + def make_tempdir + @session.exec!('mktemp -d').chomp + end + + def run_script(script) + dir = make_tempdir + remote_path = "#{dir}/#{File.basename(script)}" + copy(script, remote_path) + execute("chmod u+x \"#{remote_path}\"") + execute("\"#{remote_path}\"") + execute("rm -rf \"#{dir}\"") + end end end
1
require 'net/ssh' require 'net/sftp' module Bolt class SSH < Node def initialize(host, user, port = nil, password = nil) @host = host @user = user @port = port @password = password end def connect options = {} options[:port] = @port if @port options[:password] = @password if @password @session = Net::SSH.start(@host, @user, **options) end def disconnect @session.close if @session && [email protected]? end def execute(command) @session.exec!(command) do |_, stream, data| $stdout << data if stream == :stdout $stderr << data if stream == :stderr end end def copy(source, destination) Net::SFTP::Session.new(@session).connect! do |sftp| sftp.upload!(source, destination) end end end end
1
6,373
if I give a non-existent script, then I don't get an errors. I would have expected the `copy` method to raise, but maybe `net-sftp` silently exits?
puppetlabs-bolt
rb
@@ -4343,10 +4343,12 @@ class Series(Frame, IndexOpsMixin, Generic[T]): """ if to_replace is None: return self.fillna(method="ffill") - if not isinstance(to_replace, (str, list, dict, int, float)): - raise ValueError("'to_replace' should be one of str, list, dict, int, float") + if not isinstance(to_replace, (str, list, tuple, dict, int, float)): + raise ValueError("'to_replace' should be one of str, list, tuple, dict, int, float") if regex: raise NotImplementedError("replace currently not support for regex") + to_replace = list(to_replace) if isinstance(to_replace, tuple) else to_replace + value = list(value) if isinstance(value, tuple) else value if isinstance(to_replace, list) and isinstance(value, list): if not len(to_replace) == len(value): raise ValueError(
1
# # Copyright (C) 2019 Databricks, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # """ A wrapper class for Spark Column to behave similar to pandas Series. """ import re import inspect import sys import warnings from collections.abc import Mapping from distutils.version import LooseVersion from functools import partial, wraps, reduce from itertools import chain from typing import Any, Generic, Iterable, List, Optional, Tuple, TypeVar, Union, cast import numpy as np import pandas as pd from pandas.core.accessor import CachedAccessor from pandas.io.formats.printing import pprint_thing from pandas.api.types import is_list_like, is_hashable import pyspark from pyspark import sql as spark from pyspark.sql import functions as F, Column from pyspark.sql.types import ( BooleanType, DoubleType, FloatType, IntegerType, LongType, NumericType, StructType, IntegralType, ArrayType, ) from pyspark.sql.window import Window from databricks import koalas as ks # For running doctests and reference resolution in PyCharm. from databricks.koalas.accessors import KoalasSeriesMethods from databricks.koalas.config import get_option from databricks.koalas.base import IndexOpsMixin from databricks.koalas.exceptions import SparkPandasIndexingError from databricks.koalas.frame import DataFrame from databricks.koalas.generic import Frame from databricks.koalas.internal import ( InternalFrame, DEFAULT_SERIES_NAME, NATURAL_ORDER_COLUMN_NAME, SPARK_DEFAULT_INDEX_NAME, SPARK_DEFAULT_SERIES_NAME, ) from databricks.koalas.missing.series import MissingPandasLikeSeries from databricks.koalas.plot import KoalasPlotAccessor from databricks.koalas.ml import corr from databricks.koalas.utils import ( combine_frames, is_name_like_tuple, is_name_like_value, name_like_string, same_anchor, scol_for, validate_arguments_and_invoke_function, validate_axis, validate_bool_kwarg, verify_temp_column_name, ) from databricks.koalas.datetimes import DatetimeMethods from databricks.koalas.spark import functions as SF from databricks.koalas.spark.accessors import SparkSeriesMethods from databricks.koalas.strings import StringMethods from databricks.koalas.typedef import ( infer_return_type, spark_type_to_pandas_dtype, SeriesType, ScalarType, Scalar, ) # This regular expression pattern is complied and defined here to avoid to compile the same # pattern every time it is used in _repr_ in Series. # This pattern basically seeks the footer string from pandas' REPR_PATTERN = re.compile(r"Length: (?P<length>[0-9]+)") _flex_doc_SERIES = """ Return {desc} of series and other, element-wise (binary operator `{op_name}`). Equivalent to ``{equiv}`` Parameters ---------- other : Series or scalar value Returns ------- Series The result of the operation. See Also -------- Series.{reverse} {series_examples} """ _add_example_SERIES = """ Examples -------- >>> df = ks.DataFrame({'a': [2, 2, 4, np.nan], ... 'b': [2, np.nan, 2, np.nan]}, ... index=['a', 'b', 'c', 'd'], columns=['a', 'b']) >>> df a b a 2.0 2.0 b 2.0 NaN c 4.0 2.0 d NaN NaN >>> df.a.add(df.b) a 4.0 b NaN c 6.0 d NaN dtype: float64 >>> df.a.radd(df.b) a 4.0 b NaN c 6.0 d NaN dtype: float64 """ _sub_example_SERIES = """ Examples -------- >>> df = ks.DataFrame({'a': [2, 2, 4, np.nan], ... 'b': [2, np.nan, 2, np.nan]}, ... index=['a', 'b', 'c', 'd'], columns=['a', 'b']) >>> df a b a 2.0 2.0 b 2.0 NaN c 4.0 2.0 d NaN NaN >>> df.a.subtract(df.b) a 0.0 b NaN c 2.0 d NaN dtype: float64 >>> df.a.rsub(df.b) a 0.0 b NaN c -2.0 d NaN dtype: float64 """ _mul_example_SERIES = """ Examples -------- >>> df = ks.DataFrame({'a': [2, 2, 4, np.nan], ... 'b': [2, np.nan, 2, np.nan]}, ... index=['a', 'b', 'c', 'd'], columns=['a', 'b']) >>> df a b a 2.0 2.0 b 2.0 NaN c 4.0 2.0 d NaN NaN >>> df.a.multiply(df.b) a 4.0 b NaN c 8.0 d NaN dtype: float64 >>> df.a.rmul(df.b) a 4.0 b NaN c 8.0 d NaN dtype: float64 """ _div_example_SERIES = """ Examples -------- >>> df = ks.DataFrame({'a': [2, 2, 4, np.nan], ... 'b': [2, np.nan, 2, np.nan]}, ... index=['a', 'b', 'c', 'd'], columns=['a', 'b']) >>> df a b a 2.0 2.0 b 2.0 NaN c 4.0 2.0 d NaN NaN >>> df.a.divide(df.b) a 1.0 b NaN c 2.0 d NaN dtype: float64 >>> df.a.rdiv(df.b) a 1.0 b NaN c 0.5 d NaN dtype: float64 """ _pow_example_SERIES = """ Examples -------- >>> df = ks.DataFrame({'a': [2, 2, 4, np.nan], ... 'b': [2, np.nan, 2, np.nan]}, ... index=['a', 'b', 'c', 'd'], columns=['a', 'b']) >>> df a b a 2.0 2.0 b 2.0 NaN c 4.0 2.0 d NaN NaN >>> df.a.pow(df.b) a 4.0 b NaN c 16.0 d NaN dtype: float64 >>> df.a.rpow(df.b) a 4.0 b NaN c 16.0 d NaN dtype: float64 """ _mod_example_SERIES = """ Examples -------- >>> df = ks.DataFrame({'a': [2, 2, 4, np.nan], ... 'b': [2, np.nan, 2, np.nan]}, ... index=['a', 'b', 'c', 'd'], columns=['a', 'b']) >>> df a b a 2.0 2.0 b 2.0 NaN c 4.0 2.0 d NaN NaN >>> df.a.mod(df.b) a 0.0 b NaN c 0.0 d NaN dtype: float64 >>> df.a.rmod(df.b) a 0.0 b NaN c 2.0 d NaN dtype: float64 """ _floordiv_example_SERIES = """ Examples -------- >>> df = ks.DataFrame({'a': [2, 2, 4, np.nan], ... 'b': [2, np.nan, 2, np.nan]}, ... index=['a', 'b', 'c', 'd'], columns=['a', 'b']) >>> df a b a 2.0 2.0 b 2.0 NaN c 4.0 2.0 d NaN NaN >>> df.a.floordiv(df.b) a 1.0 b NaN c 2.0 d NaN dtype: float64 >>> df.a.rfloordiv(df.b) a 1.0 b NaN c 0.0 d NaN dtype: float64 """ T = TypeVar("T") # Needed to disambiguate Series.str and str type str_type = str class Series(Frame, IndexOpsMixin, Generic[T]): """ Koalas Series that corresponds to pandas Series logically. This holds Spark Column internally. :ivar _internal: an internal immutable Frame to manage metadata. :type _internal: InternalFrame :ivar _kdf: Parent's Koalas DataFrame :type _kdf: ks.DataFrame Parameters ---------- data : array-like, dict, or scalar value, pandas Series Contains data stored in Series If data is a dict, argument order is maintained for Python 3.6 and later. Note that if `data` is a pandas Series, other arguments should not be used. index : array-like or Index (1d) Values must be hashable and have the same length as `data`. Non-unique index values are allowed. Will default to RangeIndex (0, 1, 2, ..., n) if not provided. If both a dict and index sequence are used, the index will override the keys found in the dict. dtype : numpy.dtype or None If None, dtype will be inferred copy : boolean, default False Copy input data """ def __init__(self, data=None, index=None, dtype=None, name=None, copy=False, fastpath=False): assert data is not None if isinstance(data, DataFrame): assert dtype is None assert name is None assert not copy assert not fastpath self._anchor = data self._col_label = index else: if isinstance(data, pd.Series): assert index is None assert dtype is None assert name is None assert not copy assert not fastpath s = data else: s = pd.Series( data=data, index=index, dtype=dtype, name=name, copy=copy, fastpath=fastpath ) internal = InternalFrame.from_pandas(pd.DataFrame(s)) if s.name is None: internal = internal.copy(column_labels=[None]) anchor = DataFrame(internal) self._anchor = anchor self._col_label = anchor._internal.column_labels[0] object.__setattr__(anchor, "_kseries", {self._column_label: self}) @property def _kdf(self) -> DataFrame: return self._anchor @property def _internal(self) -> InternalFrame: return self._kdf._internal.select_column(self._column_label) @property def _column_label(self) -> Tuple: return self._col_label def _update_anchor(self, kdf: DataFrame): assert kdf._internal.column_labels == [self._column_label], ( kdf._internal.column_labels, [self._column_label], ) self._anchor = kdf object.__setattr__(kdf, "_kseries", {self._column_label: self}) def _with_new_scol(self, scol: spark.Column, *, dtype=None) -> "Series": """ Copy Koalas Series with the new Spark Column. :param scol: the new Spark Column :return: the copied Series """ internal = self._internal.copy( data_spark_columns=[scol.alias(name_like_string(self._column_label))], data_dtypes=[dtype], ) return first_series(DataFrame(internal)) spark = CachedAccessor("spark", SparkSeriesMethods) @property def dtypes(self) -> np.dtype: """Return the dtype object of the underlying data. >>> s = ks.Series(list('abc')) >>> s.dtype == s.dtypes True """ return self.dtype @property def axes(self) -> List: """ Return a list of the row axis labels. Examples -------- >>> kser = ks.Series([1, 2, 3]) >>> kser.axes [Int64Index([0, 1, 2], dtype='int64')] """ return [self.index] @property def spark_type(self): warnings.warn( "Series.spark_type is deprecated as of Series.spark.data_type. " "Please use the API instead.", FutureWarning, ) return self.spark.data_type spark_type.__doc__ = SparkSeriesMethods.data_type.__doc__ # Arithmetic Operators def add(self, other) -> "Series": return self + other add.__doc__ = _flex_doc_SERIES.format( desc="Addition", op_name="+", equiv="series + other", reverse="radd", series_examples=_add_example_SERIES, ) def radd(self, other) -> "Series": return other + self radd.__doc__ = _flex_doc_SERIES.format( desc="Reverse Addition", op_name="+", equiv="other + series", reverse="add", series_examples=_add_example_SERIES, ) def div(self, other) -> "Series": return self / other div.__doc__ = _flex_doc_SERIES.format( desc="Floating division", op_name="/", equiv="series / other", reverse="rdiv", series_examples=_div_example_SERIES, ) divide = div def rdiv(self, other) -> "Series": return other / self rdiv.__doc__ = _flex_doc_SERIES.format( desc="Reverse Floating division", op_name="/", equiv="other / series", reverse="div", series_examples=_div_example_SERIES, ) def truediv(self, other) -> "Series": return self / other truediv.__doc__ = _flex_doc_SERIES.format( desc="Floating division", op_name="/", equiv="series / other", reverse="rtruediv", series_examples=_div_example_SERIES, ) def rtruediv(self, other) -> "Series": return other / self rtruediv.__doc__ = _flex_doc_SERIES.format( desc="Reverse Floating division", op_name="/", equiv="other / series", reverse="truediv", series_examples=_div_example_SERIES, ) def mul(self, other) -> "Series": return self * other mul.__doc__ = _flex_doc_SERIES.format( desc="Multiplication", op_name="*", equiv="series * other", reverse="rmul", series_examples=_mul_example_SERIES, ) multiply = mul def rmul(self, other) -> "Series": return other * self rmul.__doc__ = _flex_doc_SERIES.format( desc="Reverse Multiplication", op_name="*", equiv="other * series", reverse="mul", series_examples=_mul_example_SERIES, ) def sub(self, other) -> "Series": return self - other sub.__doc__ = _flex_doc_SERIES.format( desc="Subtraction", op_name="-", equiv="series - other", reverse="rsub", series_examples=_sub_example_SERIES, ) subtract = sub def rsub(self, other) -> "Series": return other - self rsub.__doc__ = _flex_doc_SERIES.format( desc="Reverse Subtraction", op_name="-", equiv="other - series", reverse="sub", series_examples=_sub_example_SERIES, ) def mod(self, other) -> "Series": return self % other mod.__doc__ = _flex_doc_SERIES.format( desc="Modulo", op_name="%", equiv="series % other", reverse="rmod", series_examples=_mod_example_SERIES, ) def rmod(self, other) -> "Series": return other % self rmod.__doc__ = _flex_doc_SERIES.format( desc="Reverse Modulo", op_name="%", equiv="other % series", reverse="mod", series_examples=_mod_example_SERIES, ) def pow(self, other) -> "Series": return self ** other pow.__doc__ = _flex_doc_SERIES.format( desc="Exponential power of series", op_name="**", equiv="series ** other", reverse="rpow", series_examples=_pow_example_SERIES, ) def rpow(self, other) -> "Series": return other ** self rpow.__doc__ = _flex_doc_SERIES.format( desc="Reverse Exponential power", op_name="**", equiv="other ** series", reverse="pow", series_examples=_pow_example_SERIES, ) def floordiv(self, other) -> "Series": return self // other floordiv.__doc__ = _flex_doc_SERIES.format( desc="Integer division", op_name="//", equiv="series // other", reverse="rfloordiv", series_examples=_floordiv_example_SERIES, ) def rfloordiv(self, other) -> "Series": return other // self rfloordiv.__doc__ = _flex_doc_SERIES.format( desc="Reverse Integer division", op_name="//", equiv="other // series", reverse="floordiv", series_examples=_floordiv_example_SERIES, ) # create accessor for Koalas specific methods. koalas = CachedAccessor("koalas", KoalasSeriesMethods) # Comparison Operators def eq(self, other) -> bool: """ Compare if the current value is equal to the other. >>> df = ks.DataFrame({'a': [1, 2, 3, 4], ... 'b': [1, np.nan, 1, np.nan]}, ... index=['a', 'b', 'c', 'd'], columns=['a', 'b']) >>> df.a == 1 a True b False c False d False Name: a, dtype: bool >>> df.b.eq(1) a True b False c True d False Name: b, dtype: bool """ return self == other equals = eq def gt(self, other) -> "Series": """ Compare if the current value is greater than the other. >>> df = ks.DataFrame({'a': [1, 2, 3, 4], ... 'b': [1, np.nan, 1, np.nan]}, ... index=['a', 'b', 'c', 'd'], columns=['a', 'b']) >>> df.a > 1 a False b True c True d True Name: a, dtype: bool >>> df.b.gt(1) a False b False c False d False Name: b, dtype: bool """ return self > other def ge(self, other) -> "Series": """ Compare if the current value is greater than or equal to the other. >>> df = ks.DataFrame({'a': [1, 2, 3, 4], ... 'b': [1, np.nan, 1, np.nan]}, ... index=['a', 'b', 'c', 'd'], columns=['a', 'b']) >>> df.a >= 2 a False b True c True d True Name: a, dtype: bool >>> df.b.ge(2) a False b False c False d False Name: b, dtype: bool """ return self >= other def lt(self, other) -> "Series": """ Compare if the current value is less than the other. >>> df = ks.DataFrame({'a': [1, 2, 3, 4], ... 'b': [1, np.nan, 1, np.nan]}, ... index=['a', 'b', 'c', 'd'], columns=['a', 'b']) >>> df.a < 1 a False b False c False d False Name: a, dtype: bool >>> df.b.lt(2) a True b False c True d False Name: b, dtype: bool """ return self < other def le(self, other) -> "Series": """ Compare if the current value is less than or equal to the other. >>> df = ks.DataFrame({'a': [1, 2, 3, 4], ... 'b': [1, np.nan, 1, np.nan]}, ... index=['a', 'b', 'c', 'd'], columns=['a', 'b']) >>> df.a <= 2 a True b True c False d False Name: a, dtype: bool >>> df.b.le(2) a True b False c True d False Name: b, dtype: bool """ return self <= other def ne(self, other) -> "Series": """ Compare if the current value is not equal to the other. >>> df = ks.DataFrame({'a': [1, 2, 3, 4], ... 'b': [1, np.nan, 1, np.nan]}, ... index=['a', 'b', 'c', 'd'], columns=['a', 'b']) >>> df.a != 1 a False b True c True d True Name: a, dtype: bool >>> df.b.ne(1) a False b True c False d True Name: b, dtype: bool """ return self != other def divmod(self, other) -> Tuple["Series", "Series"]: """ Return Integer division and modulo of series and other, element-wise (binary operator `divmod`). Parameters ---------- other : Series or scalar value Returns ------- 2-Tuple of Series The result of the operation. See Also -------- Series.rdivmod """ return (self.floordiv(other), self.mod(other)) def rdivmod(self, other) -> Tuple["Series", "Series"]: """ Return Integer division and modulo of series and other, element-wise (binary operator `rdivmod`). Parameters ---------- other : Series or scalar value Returns ------- 2-Tuple of Series The result of the operation. See Also -------- Series.divmod """ return (self.rfloordiv(other), self.rmod(other)) def between(self, left, right, inclusive=True) -> "Series": """ Return boolean Series equivalent to left <= series <= right. This function returns a boolean vector containing `True` wherever the corresponding Series element is between the boundary values `left` and `right`. NA values are treated as `False`. Parameters ---------- left : scalar or list-like Left boundary. right : scalar or list-like Right boundary. inclusive : bool, default True Include boundaries. Returns ------- Series Series representing whether each element is between left and right (inclusive). See Also -------- Series.gt : Greater than of series and other. Series.lt : Less than of series and other. Notes ----- This function is equivalent to ``(left <= ser) & (ser <= right)`` Examples -------- >>> s = ks.Series([2, 0, 4, 8, np.nan]) Boundary values are included by default: >>> s.between(1, 4) 0 True 1 False 2 True 3 False 4 False dtype: bool With `inclusive` set to ``False`` boundary values are excluded: >>> s.between(1, 4, inclusive=False) 0 True 1 False 2 False 3 False 4 False dtype: bool `left` and `right` can be any scalar value: >>> s = ks.Series(['Alice', 'Bob', 'Carol', 'Eve']) >>> s.between('Anna', 'Daniel') 0 False 1 True 2 True 3 False dtype: bool """ if inclusive: lmask = self >= left rmask = self <= right else: lmask = self > left rmask = self < right return lmask & rmask # TODO: arg should support Series # TODO: NaN and None def map(self, arg) -> "Series": """ Map values of Series according to input correspondence. Used for substituting each value in a Series with another value, that may be derived from a function, a ``dict``. .. note:: make sure the size of the dictionary is not huge because it could downgrade the performance or throw OutOfMemoryError due to a huge expression within Spark. Consider the input as a functions as an alternative instead in this case. Parameters ---------- arg : function or dict Mapping correspondence. Returns ------- Series Same index as caller. See Also -------- Series.apply : For applying more complex functions on a Series. DataFrame.applymap : Apply a function elementwise on a whole DataFrame. Notes ----- When ``arg`` is a dictionary, values in Series that are not in the dictionary (as keys) are converted to ``None``. However, if the dictionary is a ``dict`` subclass that defines ``__missing__`` (i.e. provides a method for default values), then this default is used rather than ``None``. Examples -------- >>> s = ks.Series(['cat', 'dog', None, 'rabbit']) >>> s 0 cat 1 dog 2 None 3 rabbit dtype: object ``map`` accepts a ``dict``. Values that are not found in the ``dict`` are converted to ``None``, unless the dict has a default value (e.g. ``defaultdict``): >>> s.map({'cat': 'kitten', 'dog': 'puppy'}) 0 kitten 1 puppy 2 None 3 None dtype: object It also accepts a function: >>> def format(x) -> str: ... return 'I am a {}'.format(x) >>> s.map(format) 0 I am a cat 1 I am a dog 2 I am a None 3 I am a rabbit dtype: object """ if isinstance(arg, dict): is_start = True # In case dictionary is empty. current = F.when(F.lit(False), F.lit(None).cast(self.spark.data_type)) for to_replace, value in arg.items(): if is_start: current = F.when(self.spark.column == F.lit(to_replace), value) is_start = False else: current = current.when(self.spark.column == F.lit(to_replace), value) if hasattr(arg, "__missing__"): tmp_val = arg[np._NoValue] del arg[np._NoValue] # Remove in case it's set in defaultdict. current = current.otherwise(F.lit(tmp_val)) else: current = current.otherwise(F.lit(None).cast(self.spark.data_type)) return self._with_new_scol(current) else: return self.apply(arg) def alias(self, name) -> "Series": """An alias for :meth:`Series.rename`.""" warnings.warn( "Series.alias is deprecated as of Series.rename. Please use the API instead.", FutureWarning, ) return self.rename(name) @property def shape(self): """Return a tuple of the shape of the underlying data.""" return (len(self),) @property def name(self) -> Union[Any, Tuple]: """Return name of the Series.""" name = self._column_label if name is not None and len(name) == 1: return name[0] else: return name @name.setter def name(self, name: Union[Any, Tuple]): self.rename(name, inplace=True) # TODO: Functionality and documentation should be matched. Currently, changing index labels # taking dictionary and function to change index are not supported. def rename(self, index=None, **kwargs) -> "Series": """ Alter Series name. Parameters ---------- index : scalar Scalar will alter the ``Series.name`` attribute. inplace : bool, default False Whether to return a new Series. If True then value of copy is ignored. Returns ------- Series Series with name altered. Examples -------- >>> s = ks.Series([1, 2, 3]) >>> s 0 1 1 2 2 3 dtype: int64 >>> s.rename("my_name") # scalar, changes Series.name 0 1 1 2 2 3 Name: my_name, dtype: int64 """ if index is None: pass elif not is_hashable(index): raise TypeError("Series.name must be a hashable type") elif not isinstance(index, tuple): index = (index,) scol = self.spark.column.alias(name_like_string(index)) internal = self._internal.copy( column_labels=[index], data_spark_columns=[scol], column_label_names=None ) kdf = DataFrame(internal) # type: DataFrame if kwargs.get("inplace", False): self._col_label = index self._update_anchor(kdf) return self else: return first_series(kdf) def rename_axis( self, mapper: Optional[Any] = None, index: Optional[Any] = None, inplace: bool = False ) -> Optional["Series"]: """ Set the name of the axis for the index or columns. Parameters ---------- mapper, index : scalar, list-like, dict-like or function, optional A scalar, list-like, dict-like or functions transformations to apply to the index values. inplace : bool, default False Modifies the object directly, instead of creating a new Series. Returns ------- Series, or None if `inplace` is True. See Also -------- Series.rename : Alter Series index labels or name. DataFrame.rename : Alter DataFrame index labels or name. Index.rename : Set new names on index. Examples -------- >>> s = ks.Series(["dog", "cat", "monkey"], name="animal") >>> s # doctest: +NORMALIZE_WHITESPACE 0 dog 1 cat 2 monkey Name: animal, dtype: object >>> s.rename_axis("index").sort_index() # doctest: +NORMALIZE_WHITESPACE index 0 dog 1 cat 2 monkey Name: animal, dtype: object **MultiIndex** >>> index = pd.MultiIndex.from_product([['mammal'], ... ['dog', 'cat', 'monkey']], ... names=['type', 'name']) >>> s = ks.Series([4, 4, 2], index=index, name='num_legs') >>> s # doctest: +NORMALIZE_WHITESPACE type name mammal dog 4 cat 4 monkey 2 Name: num_legs, dtype: int64 >>> s.rename_axis(index={'type': 'class'}).sort_index() # doctest: +NORMALIZE_WHITESPACE class name mammal cat 4 dog 4 monkey 2 Name: num_legs, dtype: int64 >>> s.rename_axis(index=str.upper).sort_index() # doctest: +NORMALIZE_WHITESPACE TYPE NAME mammal cat 4 dog 4 monkey 2 Name: num_legs, dtype: int64 """ kdf = self.to_frame().rename_axis(mapper=mapper, index=index, inplace=False) if inplace: self._update_anchor(kdf) return None else: return first_series(kdf) @property def index(self) -> "ks.Index": """The index (axis labels) Column of the Series. See Also -------- Index """ return self._kdf.index @property def is_unique(self) -> bool: """ Return boolean if values in the object are unique Returns ------- is_unique : boolean >>> ks.Series([1, 2, 3]).is_unique True >>> ks.Series([1, 2, 2]).is_unique False >>> ks.Series([1, 2, 3, None]).is_unique True """ scol = self.spark.column # Here we check: # 1. the distinct count without nulls and count without nulls for non-null values # 2. count null values and see if null is a distinct value. # # This workaround is in order to calculate the distinct count including nulls in # single pass. Note that COUNT(DISTINCT expr) in Spark is designed to ignore nulls. return self._internal.spark_frame.select( (F.count(scol) == F.countDistinct(scol)) & (F.count(F.when(scol.isNull(), 1).otherwise(None)) <= 1) ).collect()[0][0] def reset_index( self, level=None, drop=False, name=None, inplace=False ) -> Optional[Union["Series", DataFrame]]: """ Generate a new DataFrame or Series with the index reset. This is useful when the index needs to be treated as a column, or when the index is meaningless and needs to be reset to the default before another operation. Parameters ---------- level : int, str, tuple, or list, default optional For a Series with a MultiIndex, only remove the specified levels from the index. Removes all levels by default. drop : bool, default False Just reset the index, without inserting it as a column in the new DataFrame. name : object, optional The name to use for the column containing the original Series values. Uses self.name by default. This argument is ignored when drop is True. inplace : bool, default False Modify the Series in place (do not create a new object). Returns ------- Series or DataFrame When `drop` is False (the default), a DataFrame is returned. The newly created columns will come first in the DataFrame, followed by the original Series values. When `drop` is True, a `Series` is returned. In either case, if ``inplace=True``, no value is returned. Examples -------- >>> s = ks.Series([1, 2, 3, 4], index=pd.Index(['a', 'b', 'c', 'd'], name='idx')) Generate a DataFrame with default index. >>> s.reset_index() idx 0 0 a 1 1 b 2 2 c 3 3 d 4 To specify the name of the new column use `name`. >>> s.reset_index(name='values') idx values 0 a 1 1 b 2 2 c 3 3 d 4 To generate a new Series with the default set `drop` to True. >>> s.reset_index(drop=True) 0 1 1 2 2 3 3 4 dtype: int64 To update the Series in place, without generating a new one set `inplace` to True. Note that it also requires ``drop=True``. >>> s.reset_index(inplace=True, drop=True) >>> s 0 1 1 2 2 3 3 4 dtype: int64 """ inplace = validate_bool_kwarg(inplace, "inplace") if inplace and not drop: raise TypeError("Cannot reset_index inplace on a Series to create a DataFrame") if drop: kdf = self._kdf[[self.name]] else: kser = self if name is not None: kser = kser.rename(name) kdf = kser.to_frame() kdf = kdf.reset_index(level=level, drop=drop) if drop: if inplace: self._update_anchor(kdf) return None else: return first_series(kdf) else: return kdf def to_frame(self, name: Union[Any, Tuple] = None) -> DataFrame: """ Convert Series to DataFrame. Parameters ---------- name : object, default None The passed name should substitute for the series name (if it has one). Returns ------- DataFrame DataFrame representation of Series. Examples -------- >>> s = ks.Series(["a", "b", "c"]) >>> s.to_frame() 0 0 a 1 b 2 c >>> s = ks.Series(["a", "b", "c"], name="vals") >>> s.to_frame() vals 0 a 1 b 2 c """ if name is not None: renamed = self.rename(name) elif self._column_label is None: renamed = self.rename(DEFAULT_SERIES_NAME) else: renamed = self return DataFrame(renamed._internal) to_dataframe = to_frame def to_string( self, buf=None, na_rep="NaN", float_format=None, header=True, index=True, length=False, dtype=False, name=False, max_rows=None, ) -> str: """ Render a string representation of the Series. .. note:: This method should only be used if the resulting pandas object is expected to be small, as all the data is loaded into the driver's memory. If the input is large, set max_rows parameter. Parameters ---------- buf : StringIO-like, optional buffer to write to na_rep : string, optional string representation of NAN to use, default 'NaN' float_format : one-parameter function, optional formatter function to apply to columns' elements if they are floats default None header : boolean, default True Add the Series header (index name) index : bool, optional Add index (row) labels, default True length : boolean, default False Add the Series length dtype : boolean, default False Add the Series dtype name : boolean, default False Add the Series name if not None max_rows : int, optional Maximum number of rows to show before truncating. If None, show all. Returns ------- formatted : string (if not buffer passed) Examples -------- >>> df = ks.DataFrame([(.2, .3), (.0, .6), (.6, .0), (.2, .1)], columns=['dogs', 'cats']) >>> print(df['dogs'].to_string()) 0 0.2 1 0.0 2 0.6 3 0.2 >>> print(df['dogs'].to_string(max_rows=2)) 0 0.2 1 0.0 """ # Make sure locals() call is at the top of the function so we don't capture local variables. args = locals() if max_rows is not None: kseries = self.head(max_rows) else: kseries = self return validate_arguments_and_invoke_function( kseries._to_internal_pandas(), self.to_string, pd.Series.to_string, args ) def to_clipboard(self, excel=True, sep=None, **kwargs) -> None: # Docstring defined below by reusing DataFrame.to_clipboard's. args = locals() kseries = self return validate_arguments_and_invoke_function( kseries._to_internal_pandas(), self.to_clipboard, pd.Series.to_clipboard, args ) to_clipboard.__doc__ = DataFrame.to_clipboard.__doc__ def to_dict(self, into=dict) -> Mapping: """ Convert Series to {label -> value} dict or dict-like object. .. note:: This method should only be used if the resulting pandas DataFrame is expected to be small, as all the data is loaded into the driver's memory. Parameters ---------- into : class, default dict The collections.abc.Mapping subclass to use as the return object. Can be the actual class or an empty instance of the mapping type you want. If you want a collections.defaultdict, you must pass it initialized. Returns ------- collections.abc.Mapping Key-value representation of Series. Examples -------- >>> s = ks.Series([1, 2, 3, 4]) >>> s_dict = s.to_dict() >>> sorted(s_dict.items()) [(0, 1), (1, 2), (2, 3), (3, 4)] >>> from collections import OrderedDict, defaultdict >>> s.to_dict(OrderedDict) OrderedDict([(0, 1), (1, 2), (2, 3), (3, 4)]) >>> dd = defaultdict(list) >>> s.to_dict(dd) # doctest: +ELLIPSIS defaultdict(<class 'list'>, {...}) """ # Make sure locals() call is at the top of the function so we don't capture local variables. args = locals() kseries = self return validate_arguments_and_invoke_function( kseries._to_internal_pandas(), self.to_dict, pd.Series.to_dict, args ) def to_latex( self, buf=None, columns=None, col_space=None, header=True, index=True, na_rep="NaN", formatters=None, float_format=None, sparsify=None, index_names=True, bold_rows=False, column_format=None, longtable=None, escape=None, encoding=None, decimal=".", multicolumn=None, multicolumn_format=None, multirow=None, ) -> Optional[str]: args = locals() kseries = self return validate_arguments_and_invoke_function( kseries._to_internal_pandas(), self.to_latex, pd.Series.to_latex, args ) to_latex.__doc__ = DataFrame.to_latex.__doc__ def to_pandas(self) -> pd.Series: """ Return a pandas Series. .. note:: This method should only be used if the resulting pandas object is expected to be small, as all the data is loaded into the driver's memory. Examples -------- >>> df = ks.DataFrame([(.2, .3), (.0, .6), (.6, .0), (.2, .1)], columns=['dogs', 'cats']) >>> df['dogs'].to_pandas() 0 0.2 1 0.0 2 0.6 3 0.2 Name: dogs, dtype: float64 """ return self._to_internal_pandas().copy() # Alias to maintain backward compatibility with Spark def toPandas(self) -> pd.Series: warnings.warn( "Series.toPandas is deprecated as of Series.to_pandas. Please use the API instead.", FutureWarning, ) return self.to_pandas() toPandas.__doc__ = to_pandas.__doc__ def to_list(self) -> List: """ Return a list of the values. These are each a scalar type, which is a Python scalar (for str, int, float) or a pandas scalar (for Timestamp/Timedelta/Interval/Period) .. note:: This method should only be used if the resulting list is expected to be small, as all the data is loaded into the driver's memory. """ return self._to_internal_pandas().tolist() tolist = to_list def drop_duplicates(self, keep="first", inplace=False) -> Optional["Series"]: """ Return Series with duplicate values removed. Parameters ---------- keep : {'first', 'last', ``False``}, default 'first' Method to handle dropping duplicates: - 'first' : Drop duplicates except for the first occurrence. - 'last' : Drop duplicates except for the last occurrence. - ``False`` : Drop all duplicates. inplace : bool, default ``False`` If ``True``, performs operation inplace and returns None. Returns ------- Series Series with duplicates dropped. Examples -------- Generate a Series with duplicated entries. >>> s = ks.Series(['lama', 'cow', 'lama', 'beetle', 'lama', 'hippo'], ... name='animal') >>> s.sort_index() 0 lama 1 cow 2 lama 3 beetle 4 lama 5 hippo Name: animal, dtype: object With the 'keep' parameter, the selection behaviour of duplicated values can be changed. The value 'first' keeps the first occurrence for each set of duplicated entries. The default value of keep is 'first'. >>> s.drop_duplicates().sort_index() 0 lama 1 cow 3 beetle 5 hippo Name: animal, dtype: object The value 'last' for parameter 'keep' keeps the last occurrence for each set of duplicated entries. >>> s.drop_duplicates(keep='last').sort_index() 1 cow 3 beetle 4 lama 5 hippo Name: animal, dtype: object The value ``False`` for parameter 'keep' discards all sets of duplicated entries. Setting the value of 'inplace' to ``True`` performs the operation inplace and returns ``None``. >>> s.drop_duplicates(keep=False, inplace=True) >>> s.sort_index() 1 cow 3 beetle 5 hippo Name: animal, dtype: object """ inplace = validate_bool_kwarg(inplace, "inplace") kdf = self._kdf[[self.name]].drop_duplicates(keep=keep) if inplace: self._update_anchor(kdf) return None else: return first_series(kdf) def reindex(self, index: Optional[Any] = None, fill_value: Optional[Any] = None,) -> "Series": """ Conform Series to new index with optional filling logic, placing NA/NaN in locations having no value in the previous index. A new object is produced. Parameters ---------- index: array-like, optional New labels / index to conform to, should be specified using keywords. Preferably an Index object to avoid duplicating data fill_value : scalar, default np.NaN Value to use for missing values. Defaults to NaN, but can be any "compatible" value. Returns ------- Series with changed index. See Also -------- Series.reset_index : Remove row labels or move them to new columns. Examples -------- Create a series with some fictional data. >>> index = ['Firefox', 'Chrome', 'Safari', 'IE10', 'Konqueror'] >>> ser = ks.Series([200, 200, 404, 404, 301], ... index=index, name='http_status') >>> ser Firefox 200 Chrome 200 Safari 404 IE10 404 Konqueror 301 Name: http_status, dtype: int64 Create a new index and reindex the Series. By default values in the new index that do not have corresponding records in the Series are assigned ``NaN``. >>> new_index= ['Safari', 'Iceweasel', 'Comodo Dragon', 'IE10', ... 'Chrome'] >>> ser.reindex(new_index).sort_index() Chrome 200.0 Comodo Dragon NaN IE10 404.0 Iceweasel NaN Safari 404.0 Name: http_status, dtype: float64 We can fill in the missing values by passing a value to the keyword ``fill_value``. >>> ser.reindex(new_index, fill_value=0).sort_index() Chrome 200 Comodo Dragon 0 IE10 404 Iceweasel 0 Safari 404 Name: http_status, dtype: int64 To further illustrate the filling functionality in ``reindex``, we will create a Series with a monotonically increasing index (for example, a sequence of dates). >>> date_index = pd.date_range('1/1/2010', periods=6, freq='D') >>> ser2 = ks.Series([100, 101, np.nan, 100, 89, 88], ... name='prices', index=date_index) >>> ser2.sort_index() 2010-01-01 100.0 2010-01-02 101.0 2010-01-03 NaN 2010-01-04 100.0 2010-01-05 89.0 2010-01-06 88.0 Name: prices, dtype: float64 Suppose we decide to expand the series to cover a wider date range. >>> date_index2 = pd.date_range('12/29/2009', periods=10, freq='D') >>> ser2.reindex(date_index2).sort_index() 2009-12-29 NaN 2009-12-30 NaN 2009-12-31 NaN 2010-01-01 100.0 2010-01-02 101.0 2010-01-03 NaN 2010-01-04 100.0 2010-01-05 89.0 2010-01-06 88.0 2010-01-07 NaN Name: prices, dtype: float64 """ return first_series(self.to_frame().reindex(index=index, fill_value=fill_value)).rename( self.name ) def reindex_like(self, other: Union["Series", "DataFrame"]) -> "Series": """ Return a Series with matching indices as other object. Conform the object to the same index on all axes. Places NA/NaN in locations having no value in the previous index. Parameters ---------- other : Series or DataFrame Its row and column indices are used to define the new indices of this object. Returns ------- Series Series with changed indices on each axis. See Also -------- DataFrame.set_index : Set row labels. DataFrame.reset_index : Remove row labels or move them to new columns. DataFrame.reindex : Change to new indices or expand indices. Notes ----- Same as calling ``.reindex(index=other.index, ...)``. Examples -------- >>> s1 = ks.Series([24.3, 31.0, 22.0, 35.0], ... index=pd.date_range(start='2014-02-12', ... end='2014-02-15', freq='D'), ... name="temp_celsius") >>> s1 2014-02-12 24.3 2014-02-13 31.0 2014-02-14 22.0 2014-02-15 35.0 Name: temp_celsius, dtype: float64 >>> s2 = ks.Series(["low", "low", "medium"], ... index=pd.DatetimeIndex(['2014-02-12', '2014-02-13', ... '2014-02-15']), ... name="winspeed") >>> s2 2014-02-12 low 2014-02-13 low 2014-02-15 medium Name: winspeed, dtype: object >>> s2.reindex_like(s1).sort_index() 2014-02-12 low 2014-02-13 low 2014-02-14 None 2014-02-15 medium Name: winspeed, dtype: object """ if isinstance(other, (Series, DataFrame)): return self.reindex(index=other.index) else: raise TypeError("other must be a Koalas Series or DataFrame") def fillna( self, value=None, method=None, axis=None, inplace=False, limit=None ) -> Optional["Series"]: """Fill NA/NaN values. .. note:: the current implementation of 'method' parameter in fillna uses Spark's Window without specifying partition specification. This leads to move all data into single partition in single machine and could cause serious performance degradation. Avoid this method against very large dataset. Parameters ---------- value : scalar, dict, Series Value to use to fill holes. alternately a dict/Series of values specifying which value to use for each column. DataFrame is not supported. method : {'backfill', 'bfill', 'pad', 'ffill', None}, default None Method to use for filling holes in reindexed Series pad / ffill: propagate last valid observation forward to next valid backfill / bfill: use NEXT valid observation to fill gap axis : {0 or `index`} 1 and `columns` are not supported. inplace : boolean, default False Fill in place (do not create a new object) limit : int, default None If method is specified, this is the maximum number of consecutive NaN values to forward/backward fill. In other words, if there is a gap with more than this number of consecutive NaNs, it will only be partially filled. If method is not specified, this is the maximum number of entries along the entire axis where NaNs will be filled. Must be greater than 0 if not None Returns ------- Series Series with NA entries filled. Examples -------- >>> s = ks.Series([np.nan, 2, 3, 4, np.nan, 6], name='x') >>> s 0 NaN 1 2.0 2 3.0 3 4.0 4 NaN 5 6.0 Name: x, dtype: float64 Replace all NaN elements with 0s. >>> s.fillna(0) 0 0.0 1 2.0 2 3.0 3 4.0 4 0.0 5 6.0 Name: x, dtype: float64 We can also propagate non-null values forward or backward. >>> s.fillna(method='ffill') 0 NaN 1 2.0 2 3.0 3 4.0 4 4.0 5 6.0 Name: x, dtype: float64 >>> s = ks.Series([np.nan, 'a', 'b', 'c', np.nan], name='x') >>> s.fillna(method='ffill') 0 None 1 a 2 b 3 c 4 c Name: x, dtype: object """ kser = self._fillna(value=value, method=method, axis=axis, limit=limit) if method is not None: kser = DataFrame(kser._kdf._internal.resolved_copy)._kser_for(self._column_label) inplace = validate_bool_kwarg(inplace, "inplace") if inplace: self._kdf._update_internal_frame(kser._kdf._internal, requires_same_anchor=False) return None else: return kser._with_new_scol(kser.spark.column) # TODO: dtype? def _fillna(self, value=None, method=None, axis=None, limit=None, part_cols=()): axis = validate_axis(axis) if axis != 0: raise NotImplementedError("fillna currently only works for axis=0 or axis='index'") if (value is None) and (method is None): raise ValueError("Must specify a fillna 'value' or 'method' parameter.") if (method is not None) and (method not in ["ffill", "pad", "backfill", "bfill"]): raise ValueError("Expecting 'pad', 'ffill', 'backfill' or 'bfill'.") scol = self.spark.column if isinstance(self.spark.data_type, (FloatType, DoubleType)): cond = scol.isNull() | F.isnan(scol) else: if not self.spark.nullable: return self.copy() cond = scol.isNull() if value is not None: if not isinstance(value, (float, int, str, bool)): raise TypeError("Unsupported type %s" % type(value).__name__) if limit is not None: raise ValueError("limit parameter for value is not support now") scol = F.when(cond, value).otherwise(scol) else: if method in ["ffill", "pad"]: func = F.last end = Window.currentRow - 1 if limit is not None: begin = Window.currentRow - limit else: begin = Window.unboundedPreceding elif method in ["bfill", "backfill"]: func = F.first begin = Window.currentRow + 1 if limit is not None: end = Window.currentRow + limit else: end = Window.unboundedFollowing window = ( Window.partitionBy(*part_cols) .orderBy(NATURAL_ORDER_COLUMN_NAME) .rowsBetween(begin, end) ) scol = F.when(cond, func(scol, True).over(window)).otherwise(scol) return DataFrame( self._kdf._internal.with_new_spark_column( self._column_label, scol.alias(name_like_string(self.name)) # TODO: dtype? ) )._kser_for(self._column_label) def factorize( self, sort: bool = True, na_sentinel: Optional[int] = -1 ) -> Tuple["Series", pd.Index]: """ Encode the object as an enumerated type or categorical variable. This method is useful for obtaining a numeric representation of an array when all that matters is identifying distinct values. Parameters ---------- sort : bool, default True na_sentinel : int or None, default -1 Value to mark "not found". If None, will not drop the NaN from the uniques of the values. Returns ------- codes : Series A Series that's an indexer into `uniques`. ``uniques.take(codes)`` will have the same values as `values`. uniques : pd.Index The unique valid values. .. note :: Even if there's a missing value in `values`, `uniques` will *not* contain an entry for it. Examples -------- >>> kser = ks.Series(['b', None, 'a', 'c', 'b']) >>> codes, uniques = kser.factorize() >>> codes 0 1 1 -1 2 0 3 2 4 1 dtype: int32 >>> uniques Index(['a', 'b', 'c'], dtype='object') >>> codes, uniques = kser.factorize(na_sentinel=None) >>> codes 0 1 1 3 2 0 3 2 4 1 dtype: int32 >>> uniques Index(['a', 'b', 'c', None], dtype='object') >>> codes, uniques = kser.factorize(na_sentinel=-2) >>> codes 0 1 1 -2 2 0 3 2 4 1 dtype: int32 >>> uniques Index(['a', 'b', 'c'], dtype='object') """ assert (na_sentinel is None) or isinstance(na_sentinel, int) assert sort is True uniq_sdf = self._internal.spark_frame.select(self.spark.column).distinct() # Check number of uniques and constructs sorted `uniques_list` max_compute_count = get_option("compute.max_rows") if max_compute_count is not None: uniq_pdf = uniq_sdf.limit(max_compute_count + 1).toPandas() if len(uniq_pdf) > max_compute_count: raise ValueError( "Current Series has more then {0} unique values. " "Please set 'compute.max_rows' by using 'databricks.koalas.config.set_option' " "to more than {0} rows. Note that, before changing the " "'compute.max_rows', this operation is considerably expensive.".format( max_compute_count ) ) else: uniq_pdf = uniq_sdf.toPandas() # pandas takes both NaN and null in Spark to np.nan, so de-duplication is required uniq_series = first_series(uniq_pdf).drop_duplicates() uniques_list = uniq_series.tolist() uniques_list = sorted(uniques_list, key=lambda x: (pd.isna(x), x)) # Constructs `unique_to_code` mapping non-na unique to code unique_to_code = {} if na_sentinel is not None: na_sentinel_code = na_sentinel code = 0 for unique in uniques_list: if pd.isna(unique): if na_sentinel is None: na_sentinel_code = code else: unique_to_code[unique] = code code += 1 kvs = list( chain(*([(F.lit(unique), F.lit(code)) for unique, code in unique_to_code.items()])) ) if len(kvs) == 0: # uniques are all missing values new_scol = F.lit(na_sentinel_code) else: scol = self.spark.column if isinstance(self.spark.data_type, (FloatType, DoubleType)): cond = scol.isNull() | F.isnan(scol) else: cond = scol.isNull() map_scol = F.create_map(kvs) null_scol = F.when(cond, F.lit(na_sentinel_code)) new_scol = null_scol.otherwise(map_scol.getItem(scol)) internal = self._internal.with_new_columns( [new_scol.alias(self._internal.data_spark_column_names[0])] ) codes = first_series(DataFrame(internal)) if na_sentinel is not None: # Drops the NaN from the uniques of the values uniques_list = [x for x in uniques_list if not pd.isna(x)] uniques = pd.Index(uniques_list) return codes, uniques def dropna(self, axis=0, inplace=False, **kwargs) -> Optional["Series"]: """ Return a new Series with missing values removed. Parameters ---------- axis : {0 or 'index'}, default 0 There is only one axis to drop values from. inplace : bool, default False If True, do operation inplace and return None. **kwargs Not in use. Returns ------- Series Series with NA entries dropped from it. Examples -------- >>> ser = ks.Series([1., 2., np.nan]) >>> ser 0 1.0 1 2.0 2 NaN dtype: float64 Drop NA values from a Series. >>> ser.dropna() 0 1.0 1 2.0 dtype: float64 Keep the Series with valid entries in the same variable. >>> ser.dropna(inplace=True) >>> ser 0 1.0 1 2.0 dtype: float64 """ inplace = validate_bool_kwarg(inplace, "inplace") # TODO: last two examples from pandas produce different results. kdf = self._kdf[[self.name]].dropna(axis=axis, inplace=False) if inplace: self._update_anchor(kdf) return None else: return first_series(kdf) def clip(self, lower: Union[float, int] = None, upper: Union[float, int] = None) -> "Series": """ Trim values at input threshold(s). Assigns values outside boundary to boundary values. Parameters ---------- lower : float or int, default None Minimum threshold value. All values below this threshold will be set to it. upper : float or int, default None Maximum threshold value. All values above this threshold will be set to it. Returns ------- Series Series with the values outside the clip boundaries replaced Examples -------- >>> ks.Series([0, 2, 4]).clip(1, 3) 0 1 1 2 2 3 dtype: int64 Notes ----- One difference between this implementation and pandas is that running `pd.Series(['a', 'b']).clip(0, 1)` will crash with "TypeError: '<=' not supported between instances of 'str' and 'int'" while `ks.Series(['a', 'b']).clip(0, 1)` will output the original Series, simply ignoring the incompatible types. """ if is_list_like(lower) or is_list_like(upper): raise ValueError( "List-like value are not supported for 'lower' and 'upper' at the " + "moment" ) if lower is None and upper is None: return self if isinstance(self.spark.data_type, NumericType): scol = self.spark.column if lower is not None: scol = F.when(scol < lower, lower).otherwise(scol) if upper is not None: scol = F.when(scol > upper, upper).otherwise(scol) return self._with_new_scol(scol, dtype=self.dtype) else: return self def drop( self, labels=None, index: Union[Any, Tuple, List[Any], List[Tuple]] = None, level=None ) -> "Series": """ Return Series with specified index labels removed. Remove elements of a Series based on specifying the index labels. When using a multi-index, labels on different levels can be removed by specifying the level. Parameters ---------- labels : single label or list-like Index labels to drop. index : None Redundant for application on Series, but index can be used instead of labels. level : int or level name, optional For MultiIndex, level for which the labels will be removed. Returns ------- Series Series with specified index labels removed. See Also -------- Series.dropna Examples -------- >>> s = ks.Series(data=np.arange(3), index=['A', 'B', 'C']) >>> s A 0 B 1 C 2 dtype: int64 Drop single label A >>> s.drop('A') B 1 C 2 dtype: int64 Drop labels B and C >>> s.drop(labels=['B', 'C']) A 0 dtype: int64 With 'index' rather than 'labels' returns exactly same result. >>> s.drop(index='A') B 1 C 2 dtype: int64 >>> s.drop(index=['B', 'C']) A 0 dtype: int64 Also support for MultiIndex >>> midx = pd.MultiIndex([['lama', 'cow', 'falcon'], ... ['speed', 'weight', 'length']], ... [[0, 0, 0, 1, 1, 1, 2, 2, 2], ... [0, 1, 2, 0, 1, 2, 0, 1, 2]]) >>> s = ks.Series([45, 200, 1.2, 30, 250, 1.5, 320, 1, 0.3], ... index=midx) >>> s lama speed 45.0 weight 200.0 length 1.2 cow speed 30.0 weight 250.0 length 1.5 falcon speed 320.0 weight 1.0 length 0.3 dtype: float64 >>> s.drop(labels='weight', level=1) lama speed 45.0 length 1.2 cow speed 30.0 length 1.5 falcon speed 320.0 length 0.3 dtype: float64 >>> s.drop(('lama', 'weight')) lama speed 45.0 length 1.2 cow speed 30.0 weight 250.0 length 1.5 falcon speed 320.0 weight 1.0 length 0.3 dtype: float64 >>> s.drop([('lama', 'speed'), ('falcon', 'weight')]) lama weight 200.0 length 1.2 cow speed 30.0 weight 250.0 length 1.5 falcon speed 320.0 length 0.3 dtype: float64 """ return first_series(self._drop(labels=labels, index=index, level=level)) def _drop( self, labels=None, index: Union[Any, Tuple, List[Any], List[Tuple]] = None, level=None ): if labels is not None: if index is not None: raise ValueError("Cannot specify both 'labels' and 'index'") return self._drop(index=labels, level=level) if index is not None: internal = self._internal if level is None: level = 0 if level >= internal.index_level: raise ValueError("'level' should be less than the number of indexes") if is_name_like_tuple(index): # type: ignore index = [index] elif is_name_like_value(index): index = [(index,)] elif all(is_name_like_value(idxes, allow_tuple=False) for idxes in index): index = [(idex,) for idex in index] elif not all(is_name_like_tuple(idxes) for idxes in index): raise ValueError( "If the given index is a list, it " "should only contains names as all tuples or all non tuples " "that contain index names" ) drop_index_scols = [] for idxes in index: try: index_scols = [ internal.index_spark_columns[lvl] == idx for lvl, idx in enumerate(idxes, level) ] except IndexError: raise KeyError( "Key length ({}) exceeds index depth ({})".format( internal.index_level, len(idxes) ) ) drop_index_scols.append(reduce(lambda x, y: x & y, index_scols)) cond = ~reduce(lambda x, y: x | y, drop_index_scols) return DataFrame(internal.with_filter(cond)) else: raise ValueError("Need to specify at least one of 'labels' or 'index'") def head(self, n: int = 5) -> "Series": """ Return the first n rows. This function returns the first n rows for the object based on position. It is useful for quickly testing if your object has the right type of data in it. Parameters ---------- n : Integer, default = 5 Returns ------- The first n rows of the caller object. Examples -------- >>> df = ks.DataFrame({'animal':['alligator', 'bee', 'falcon', 'lion']}) >>> df.animal.head(2) # doctest: +NORMALIZE_WHITESPACE 0 alligator 1 bee Name: animal, dtype: object """ return first_series(self.to_frame().head(n)).rename(self.name) # TODO: Categorical type isn't supported (due to PySpark's limitation) and # some doctests related with timestamps were not added. def unique(self) -> "Series": """ Return unique values of Series object. Uniques are returned in order of appearance. Hash table-based unique, therefore does NOT sort. .. note:: This method returns newly created Series whereas pandas returns the unique values as a NumPy array. Returns ------- Returns the unique values as a Series. See Also -------- Index.unique groupby.SeriesGroupBy.unique Examples -------- >>> kser = ks.Series([2, 1, 3, 3], name='A') >>> kser.unique().sort_values() # doctest: +NORMALIZE_WHITESPACE, +ELLIPSIS <BLANKLINE> ... 1 ... 2 ... 3 Name: A, dtype: int64 >>> ks.Series([pd.Timestamp('2016-01-01') for _ in range(3)]).unique() 0 2016-01-01 dtype: datetime64[ns] >>> kser.name = ('x', 'a') >>> kser.unique().sort_values() # doctest: +NORMALIZE_WHITESPACE, +ELLIPSIS <BLANKLINE> ... 1 ... 2 ... 3 Name: (x, a), dtype: int64 """ sdf = self._internal.spark_frame.select(self.spark.column).distinct() internal = InternalFrame( spark_frame=sdf, index_spark_columns=None, column_labels=[self._column_label], data_spark_columns=[scol_for(sdf, self._internal.data_spark_column_names[0])], data_dtypes=[self.dtype], column_label_names=self._internal.column_label_names, ) return first_series(DataFrame(internal)) def sort_values( self, ascending: bool = True, inplace: bool = False, na_position: str = "last" ) -> Optional["Series"]: """ Sort by the values. Sort a Series in ascending or descending order by some criterion. Parameters ---------- ascending : bool or list of bool, default True Sort ascending vs. descending. Specify list for multiple sort orders. If this is a list of bools, must match the length of the by. inplace : bool, default False if True, perform operation in-place na_position : {'first', 'last'}, default 'last' `first` puts NaNs at the beginning, `last` puts NaNs at the end Returns ------- sorted_obj : Series ordered by values. Examples -------- >>> s = ks.Series([np.nan, 1, 3, 10, 5]) >>> s 0 NaN 1 1.0 2 3.0 3 10.0 4 5.0 dtype: float64 Sort values ascending order (default behaviour) >>> s.sort_values(ascending=True) 1 1.0 2 3.0 4 5.0 3 10.0 0 NaN dtype: float64 Sort values descending order >>> s.sort_values(ascending=False) 3 10.0 4 5.0 2 3.0 1 1.0 0 NaN dtype: float64 Sort values inplace >>> s.sort_values(ascending=False, inplace=True) >>> s 3 10.0 4 5.0 2 3.0 1 1.0 0 NaN dtype: float64 Sort values putting NAs first >>> s.sort_values(na_position='first') 0 NaN 1 1.0 2 3.0 4 5.0 3 10.0 dtype: float64 Sort a series of strings >>> s = ks.Series(['z', 'b', 'd', 'a', 'c']) >>> s 0 z 1 b 2 d 3 a 4 c dtype: object >>> s.sort_values() 3 a 1 b 4 c 2 d 0 z dtype: object """ inplace = validate_bool_kwarg(inplace, "inplace") kdf = self._kdf[[self.name]]._sort( by=[self.spark.column], ascending=ascending, inplace=False, na_position=na_position ) if inplace: self._update_anchor(kdf) return None else: return first_series(kdf) def sort_index( self, axis: int = 0, level: Optional[Union[int, List[int]]] = None, ascending: bool = True, inplace: bool = False, kind: str = None, na_position: str = "last", ) -> Optional["Series"]: """ Sort object by labels (along an axis) Parameters ---------- axis : index, columns to direct sorting. Currently, only axis = 0 is supported. level : int or level name or list of ints or list of level names if not None, sort on values in specified index level(s) ascending : boolean, default True Sort ascending vs. descending inplace : bool, default False if True, perform operation in-place kind : str, default None Koalas does not allow specifying the sorting algorithm at the moment, default None na_position : {‘first’, ‘last’}, default ‘last’ first puts NaNs at the beginning, last puts NaNs at the end. Not implemented for MultiIndex. Returns ------- sorted_obj : Series Examples -------- >>> df = ks.Series([2, 1, np.nan], index=['b', 'a', np.nan]) >>> df.sort_index() a 1.0 b 2.0 NaN NaN dtype: float64 >>> df.sort_index(ascending=False) b 2.0 a 1.0 NaN NaN dtype: float64 >>> df.sort_index(na_position='first') NaN NaN a 1.0 b 2.0 dtype: float64 >>> df.sort_index(inplace=True) >>> df a 1.0 b 2.0 NaN NaN dtype: float64 >>> df = ks.Series(range(4), index=[['b', 'b', 'a', 'a'], [1, 0, 1, 0]], name='0') >>> df.sort_index() a 0 3 1 2 b 0 1 1 0 Name: 0, dtype: int64 >>> df.sort_index(level=1) # doctest: +SKIP a 0 3 b 0 1 a 1 2 b 1 0 Name: 0, dtype: int64 >>> df.sort_index(level=[1, 0]) a 0 3 b 0 1 a 1 2 b 1 0 Name: 0, dtype: int64 """ inplace = validate_bool_kwarg(inplace, "inplace") kdf = self._kdf[[self.name]].sort_index( axis=axis, level=level, ascending=ascending, kind=kind, na_position=na_position ) if inplace: self._update_anchor(kdf) return None else: return first_series(kdf) def swaplevel(self, i=-2, j=-1, copy: bool = True) -> "Series": """ Swap levels i and j in a MultiIndex. Default is to swap the two innermost levels of the index. Parameters ---------- i, j : int, str Level of the indices to be swapped. Can pass level name as string. copy : bool, default True Whether to copy underlying data. Must be True. Returns ------- Series Series with levels swapped in MultiIndex. Examples -------- >>> midx = pd.MultiIndex.from_arrays([['a', 'b'], [1, 2]], names = ['word', 'number']) >>> midx # doctest: +SKIP MultiIndex([('a', 1), ('b', 2)], names=['word', 'number']) >>> kser = ks.Series(['x', 'y'], index=midx) >>> kser word number a 1 x b 2 y dtype: object >>> kser.swaplevel() number word 1 a x 2 b y dtype: object >>> kser.swaplevel(0, 1) number word 1 a x 2 b y dtype: object >>> kser.swaplevel('number', 'word') number word 1 a x 2 b y dtype: object """ assert copy is True return first_series(self.to_frame().swaplevel(i, j, axis=0)).rename(self.name) def swapaxes(self, i: Union[str, int], j: Union[str, int], copy: bool = True) -> "Series": """ Interchange axes and swap values axes appropriately. Parameters ---------- i: {0 or 'index', 1 or 'columns'}. The axis to swap. j: {0 or 'index', 1 or 'columns'}. The axis to swap. copy : bool, default True. Returns ------- Series Examples -------- >>> kser = ks.Series([1, 2, 3], index=["x", "y", "z"]) >>> kser x 1 y 2 z 3 dtype: int64 >>> >>> kser.swapaxes(0, 0) x 1 y 2 z 3 dtype: int64 """ assert copy is True i = validate_axis(i) j = validate_axis(j) if not i == j == 0: raise ValueError("Axis must be 0 for Series") return self.copy() def add_prefix(self, prefix) -> "Series": """ Prefix labels with string `prefix`. For Series, the row labels are prefixed. For DataFrame, the column labels are prefixed. Parameters ---------- prefix : str The string to add before each label. Returns ------- Series New Series with updated labels. See Also -------- Series.add_suffix: Suffix column labels with string `suffix`. DataFrame.add_suffix: Suffix column labels with string `suffix`. DataFrame.add_prefix: Prefix column labels with string `prefix`. Examples -------- >>> s = ks.Series([1, 2, 3, 4]) >>> s 0 1 1 2 2 3 3 4 dtype: int64 >>> s.add_prefix('item_') item_0 1 item_1 2 item_2 3 item_3 4 dtype: int64 """ assert isinstance(prefix, str) internal = self._internal.resolved_copy sdf = internal.spark_frame.select( [ F.concat(F.lit(prefix), index_spark_column).alias(index_spark_column_name) for index_spark_column, index_spark_column_name in zip( internal.index_spark_columns, internal.index_spark_column_names ) ] + internal.data_spark_columns ) return first_series( DataFrame(internal.with_new_sdf(sdf, index_dtypes=([None] * internal.index_level))) ) def add_suffix(self, suffix) -> "Series": """ Suffix labels with string suffix. For Series, the row labels are suffixed. For DataFrame, the column labels are suffixed. Parameters ---------- suffix : str The string to add after each label. Returns ------- Series New Series with updated labels. See Also -------- Series.add_prefix: Prefix row labels with string `prefix`. DataFrame.add_prefix: Prefix column labels with string `prefix`. DataFrame.add_suffix: Suffix column labels with string `suffix`. Examples -------- >>> s = ks.Series([1, 2, 3, 4]) >>> s 0 1 1 2 2 3 3 4 dtype: int64 >>> s.add_suffix('_item') 0_item 1 1_item 2 2_item 3 3_item 4 dtype: int64 """ assert isinstance(suffix, str) internal = self._internal.resolved_copy sdf = internal.spark_frame.select( [ F.concat(index_spark_column, F.lit(suffix)).alias(index_spark_column_name) for index_spark_column, index_spark_column_name in zip( internal.index_spark_columns, internal.index_spark_column_names ) ] + internal.data_spark_columns ) return first_series( DataFrame(internal.with_new_sdf(sdf, index_dtypes=([None] * internal.index_level))) ) def corr(self, other, method="pearson") -> float: """ Compute correlation with `other` Series, excluding missing values. Parameters ---------- other : Series method : {'pearson', 'spearman'} * pearson : standard correlation coefficient * spearman : Spearman rank correlation Returns ------- correlation : float Examples -------- >>> df = ks.DataFrame({'s1': [.2, .0, .6, .2], ... 's2': [.3, .6, .0, .1]}) >>> s1 = df.s1 >>> s2 = df.s2 >>> s1.corr(s2, method='pearson') # doctest: +ELLIPSIS -0.851064... >>> s1.corr(s2, method='spearman') # doctest: +ELLIPSIS -0.948683... Notes ----- There are behavior differences between Koalas and pandas. * the `method` argument only accepts 'pearson', 'spearman' * the data should not contain NaNs. Koalas will return an error. * Koalas doesn't support the following argument(s). * `min_periods` argument is not supported """ # This implementation is suboptimal because it computes more than necessary, # but it should be a start columns = ["__corr_arg1__", "__corr_arg2__"] kdf = self._kdf.assign(__corr_arg1__=self, __corr_arg2__=other)[columns] kdf.columns = columns c = corr(kdf, method=method) return c.loc[tuple(columns)] def nsmallest(self, n: int = 5) -> "Series": """ Return the smallest `n` elements. Parameters ---------- n : int, default 5 Return this many ascending sorted values. Returns ------- Series The `n` smallest values in the Series, sorted in increasing order. See Also -------- Series.nlargest: Get the `n` largest elements. Series.sort_values: Sort Series by values. Series.head: Return the first `n` rows. Notes ----- Faster than ``.sort_values().head(n)`` for small `n` relative to the size of the ``Series`` object. In Koalas, thanks to Spark's lazy execution and query optimizer, the two would have same performance. Examples -------- >>> data = [1, 2, 3, 4, np.nan ,6, 7, 8] >>> s = ks.Series(data) >>> s 0 1.0 1 2.0 2 3.0 3 4.0 4 NaN 5 6.0 6 7.0 7 8.0 dtype: float64 The `n` largest elements where ``n=5`` by default. >>> s.nsmallest() 0 1.0 1 2.0 2 3.0 3 4.0 5 6.0 dtype: float64 >>> s.nsmallest(3) 0 1.0 1 2.0 2 3.0 dtype: float64 """ return self.sort_values(ascending=True).head(n) def nlargest(self, n: int = 5) -> "Series": """ Return the largest `n` elements. Parameters ---------- n : int, default 5 Returns ------- Series The `n` largest values in the Series, sorted in decreasing order. See Also -------- Series.nsmallest: Get the `n` smallest elements. Series.sort_values: Sort Series by values. Series.head: Return the first `n` rows. Notes ----- Faster than ``.sort_values(ascending=False).head(n)`` for small `n` relative to the size of the ``Series`` object. In Koalas, thanks to Spark's lazy execution and query optimizer, the two would have same performance. Examples -------- >>> data = [1, 2, 3, 4, np.nan ,6, 7, 8] >>> s = ks.Series(data) >>> s 0 1.0 1 2.0 2 3.0 3 4.0 4 NaN 5 6.0 6 7.0 7 8.0 dtype: float64 The `n` largest elements where ``n=5`` by default. >>> s.nlargest() 7 8.0 6 7.0 5 6.0 3 4.0 2 3.0 dtype: float64 >>> s.nlargest(n=3) 7 8.0 6 7.0 5 6.0 dtype: float64 """ return self.sort_values(ascending=False).head(n) def append( self, to_append: "Series", ignore_index: bool = False, verify_integrity: bool = False ) -> "Series": """ Concatenate two or more Series. Parameters ---------- to_append : Series or list/tuple of Series ignore_index : boolean, default False If True, do not use the index labels. verify_integrity : boolean, default False If True, raise Exception on creating index with duplicates Returns ------- appended : Series Examples -------- >>> s1 = ks.Series([1, 2, 3]) >>> s2 = ks.Series([4, 5, 6]) >>> s3 = ks.Series([4, 5, 6], index=[3,4,5]) >>> s1.append(s2) 0 1 1 2 2 3 0 4 1 5 2 6 dtype: int64 >>> s1.append(s3) 0 1 1 2 2 3 3 4 4 5 5 6 dtype: int64 With ignore_index set to True: >>> s1.append(s2, ignore_index=True) 0 1 1 2 2 3 3 4 4 5 5 6 dtype: int64 """ return first_series( self.to_frame().append(to_append.to_frame(), ignore_index, verify_integrity) ).rename(self.name) def sample( self, n: Optional[int] = None, frac: Optional[float] = None, replace: bool = False, random_state: Optional[int] = None, ) -> "Series": return first_series( self.to_frame().sample(n=n, frac=frac, replace=replace, random_state=random_state) ).rename(self.name) sample.__doc__ = DataFrame.sample.__doc__ def hist(self, bins=10, **kwds): return self.plot.hist(bins, **kwds) hist.__doc__ = KoalasPlotAccessor.hist.__doc__ def apply(self, func, args=(), **kwds) -> "Series": """ Invoke function on values of Series. Can be a Python function that only works on the Series. .. note:: this API executes the function once to infer the type which is potentially expensive, for instance, when the dataset is created after aggregations or sorting. To avoid this, specify return type in ``func``, for instance, as below: >>> def square(x) -> np.int32: ... return x ** 2 Koalas uses return type hint and does not try to infer the type. Parameters ---------- func : function Python function to apply. Note that type hint for return type is required. args : tuple Positional arguments passed to func after the series value. **kwds Additional keyword arguments passed to func. Returns ------- Series See Also -------- Series.aggregate : Only perform aggregating type operations. Series.transform : Only perform transforming type operations. DataFrame.apply : The equivalent function for DataFrame. Examples -------- Create a Series with typical summer temperatures for each city. >>> s = ks.Series([20, 21, 12], ... index=['London', 'New York', 'Helsinki']) >>> s London 20 New York 21 Helsinki 12 dtype: int64 Square the values by defining a function and passing it as an argument to ``apply()``. >>> def square(x) -> np.int64: ... return x ** 2 >>> s.apply(square) London 400 New York 441 Helsinki 144 dtype: int64 Define a custom function that needs additional positional arguments and pass these additional arguments using the ``args`` keyword >>> def subtract_custom_value(x, custom_value) -> np.int64: ... return x - custom_value >>> s.apply(subtract_custom_value, args=(5,)) London 15 New York 16 Helsinki 7 dtype: int64 Define a custom function that takes keyword arguments and pass these arguments to ``apply`` >>> def add_custom_values(x, **kwargs) -> np.int64: ... for month in kwargs: ... x += kwargs[month] ... return x >>> s.apply(add_custom_values, june=30, july=20, august=25) London 95 New York 96 Helsinki 87 dtype: int64 Use a function from the Numpy library >>> def numpy_log(col) -> np.float64: ... return np.log(col) >>> s.apply(numpy_log) London 2.995732 New York 3.044522 Helsinki 2.484907 dtype: float64 You can omit the type hint and let Koalas infer its type. >>> s.apply(np.log) London 2.995732 New York 3.044522 Helsinki 2.484907 dtype: float64 """ assert callable(func), "the first argument should be a callable function." try: spec = inspect.getfullargspec(func) return_sig = spec.annotations.get("return", None) should_infer_schema = return_sig is None except TypeError: # Falls back to schema inference if it fails to get signature. should_infer_schema = True apply_each = wraps(func)(lambda s: s.apply(func, args=args, **kwds)) if should_infer_schema: # TODO: In this case, it avoids the shortcut for now (but only infers schema) # because it returns a series from a different DataFrame and it has a different # anchor. We should fix this to allow the shortcut or only allow to infer # schema. limit = get_option("compute.shortcut_limit") pser = self.head(limit)._to_internal_pandas() transformed = pser.apply(func, *args, **kwds) kser = Series(transformed) # type: "Series" return self.koalas._transform_batch(apply_each, kser.spark.data_type) else: sig_return = infer_return_type(func) if not isinstance(sig_return, ScalarType): raise ValueError( "Expected the return type of this function to be of scalar type, " "but found type {}".format(sig_return) ) return_schema = sig_return.tpe return self.koalas._transform_batch(apply_each, return_schema) # TODO: not all arguments are implemented comparing to pandas' for now. def aggregate(self, func: Union[str, List[str]]) -> Union[Scalar, "Series"]: """Aggregate using one or more operations over the specified axis. Parameters ---------- func : str or a list of str function name(s) as string apply to series. Returns ------- scalar, Series The return can be: - scalar : when Series.agg is called with single function - Series : when Series.agg is called with several functions Notes ----- `agg` is an alias for `aggregate`. Use the alias. See Also -------- Series.apply : Invoke function on a Series. Series.transform : Only perform transforming type operations. Series.groupby : Perform operations over groups. DataFrame.aggregate : The equivalent function for DataFrame. Examples -------- >>> s = ks.Series([1, 2, 3, 4]) >>> s.agg('min') 1 >>> s.agg(['min', 'max']).sort_index() max 4 min 1 dtype: int64 """ if isinstance(func, list): return first_series(self.to_frame().aggregate(func)).rename(self.name) elif isinstance(func, str): return getattr(self, func)() else: raise ValueError("func must be a string or list of strings") agg = aggregate def transpose(self, *args, **kwargs) -> "Series": """ Return the transpose, which is by definition self. Examples -------- It returns the same object as the transpose of the given series object, which is by definition self. >>> s = ks.Series([1, 2, 3]) >>> s 0 1 1 2 2 3 dtype: int64 >>> s.transpose() 0 1 1 2 2 3 dtype: int64 """ return self.copy() T = property(transpose) def transform(self, func, axis=0, *args, **kwargs) -> Union["Series", DataFrame]: """ Call ``func`` producing the same type as `self` with transformed values and that has the same axis length as input. .. note:: this API executes the function once to infer the type which is potentially expensive, for instance, when the dataset is created after aggregations or sorting. To avoid this, specify return type in ``func``, for instance, as below: >>> def square(x) -> np.int32: ... return x ** 2 Koalas uses return type hint and does not try to infer the type. Parameters ---------- func : function or list A function or a list of functions to use for transforming the data. axis : int, default 0 or 'index' Can only be set to 0 at the moment. *args Positional arguments to pass to `func`. **kwargs Keyword arguments to pass to `func`. Returns ------- An instance of the same type with `self` that must have the same length as input. See Also -------- Series.aggregate : Only perform aggregating type operations. Series.apply : Invoke function on Series. DataFrame.transform : The equivalent function for DataFrame. Examples -------- >>> s = ks.Series(range(3)) >>> s 0 0 1 1 2 2 dtype: int64 >>> def sqrt(x) -> float: ... return np.sqrt(x) >>> s.transform(sqrt) 0 0.000000 1 1.000000 2 1.414214 dtype: float64 Even though the resulting instance must have the same length as the input, it is possible to provide several input functions: >>> def exp(x) -> float: ... return np.exp(x) >>> s.transform([sqrt, exp]) sqrt exp 0 0.000000 1.000000 1 1.000000 2.718282 2 1.414214 7.389056 You can omit the type hint and let Koalas infer its type. >>> s.transform([np.sqrt, np.exp]) sqrt exp 0 0.000000 1.000000 1 1.000000 2.718282 2 1.414214 7.389056 """ axis = validate_axis(axis) if axis != 0: raise NotImplementedError('axis should be either 0 or "index" currently.') if isinstance(func, list): applied = [] for f in func: applied.append(self.apply(f, args=args, **kwargs).rename(f.__name__)) internal = self._internal.with_new_columns(applied) return DataFrame(internal) else: return self.apply(func, args=args, **kwargs) def transform_batch(self, func, *args, **kwargs) -> "ks.Series": warnings.warn( "Series.transform_batch is deprecated as of Series.koalas.transform_batch. " "Please use the API instead.", FutureWarning, ) return self.koalas.transform_batch(func, *args, **kwargs) transform_batch.__doc__ = KoalasSeriesMethods.transform_batch.__doc__ def round(self, decimals=0) -> "Series": """ Round each value in a Series to the given number of decimals. Parameters ---------- decimals : int Number of decimal places to round to (default: 0). If decimals is negative, it specifies the number of positions to the left of the decimal point. Returns ------- Series object See Also -------- DataFrame.round Examples -------- >>> df = ks.Series([0.028208, 0.038683, 0.877076], name='x') >>> df 0 0.028208 1 0.038683 2 0.877076 Name: x, dtype: float64 >>> df.round(2) 0 0.03 1 0.04 2 0.88 Name: x, dtype: float64 """ if not isinstance(decimals, int): raise ValueError("decimals must be an integer") scol = F.round(self.spark.column, decimals) return self._with_new_scol(scol) # TODO: add 'interpolation' parameter. def quantile( self, q: Union[float, Iterable[float]] = 0.5, accuracy: int = 10000 ) -> Union[Scalar, "Series"]: """ Return value at the given quantile. .. note:: Unlike pandas', the quantile in Koalas is an approximated quantile based upon approximate percentile computation because computing quantile across a large dataset is extremely expensive. Parameters ---------- q : float or array-like, default 0.5 (50% quantile) 0 <= q <= 1, the quantile(s) to compute. accuracy : int, optional Default accuracy of approximation. Larger value means better accuracy. The relative error can be deduced by 1.0 / accuracy. Returns ------- float or Series If the current object is a Series and ``q`` is an array, a Series will be returned where the index is ``q`` and the values are the quantiles, otherwise a float will be returned. Examples -------- >>> s = ks.Series([1, 2, 3, 4, 5]) >>> s.quantile(.5) 3.0 >>> (s + 1).quantile(.5) 4.0 >>> s.quantile([.25, .5, .75]) 0.25 2.0 0.50 3.0 0.75 4.0 dtype: float64 >>> (s + 1).quantile([.25, .5, .75]) 0.25 3.0 0.50 4.0 0.75 5.0 dtype: float64 """ if isinstance(q, Iterable): return first_series( self.to_frame().quantile(q=q, axis=0, numeric_only=False, accuracy=accuracy) ).rename(self.name) else: if not isinstance(accuracy, int): raise ValueError( "accuracy must be an integer; however, got [%s]" % type(accuracy).__name__ ) if not isinstance(q, float): raise ValueError( "q must be a float or an array of floats; however, [%s] found." % type(q) ) if q < 0.0 or q > 1.0: raise ValueError("percentiles should all be in the interval [0, 1].") def quantile(spark_column, spark_type): if isinstance(spark_type, (BooleanType, NumericType)): return SF.percentile_approx(spark_column.cast(DoubleType()), q, accuracy) else: raise TypeError( "Could not convert {} ({}) to numeric".format( spark_type_to_pandas_dtype(spark_type), spark_type.simpleString() ) ) return self._reduce_for_stat_function(quantile, name="quantile") # TODO: add axis, numeric_only, pct, na_option parameter def rank(self, method="average", ascending=True) -> "Series": """ Compute numerical data ranks (1 through n) along axis. Equal values are assigned a rank that is the average of the ranks of those values. .. note:: the current implementation of rank uses Spark's Window without specifying partition specification. This leads to move all data into single partition in single machine and could cause serious performance degradation. Avoid this method against very large dataset. Parameters ---------- method : {'average', 'min', 'max', 'first', 'dense'} * average: average rank of group * min: lowest rank in group * max: highest rank in group * first: ranks assigned in order they appear in the array * dense: like 'min', but rank always increases by 1 between groups ascending : boolean, default True False for ranks by high (1) to low (N) Returns ------- ranks : same type as caller Examples -------- >>> s = ks.Series([1, 2, 2, 3], name='A') >>> s 0 1 1 2 2 2 3 3 Name: A, dtype: int64 >>> s.rank() 0 1.0 1 2.5 2 2.5 3 4.0 Name: A, dtype: float64 If method is set to 'min', it use lowest rank in group. >>> s.rank(method='min') 0 1.0 1 2.0 2 2.0 3 4.0 Name: A, dtype: float64 If method is set to 'max', it use highest rank in group. >>> s.rank(method='max') 0 1.0 1 3.0 2 3.0 3 4.0 Name: A, dtype: float64 If method is set to 'first', it is assigned rank in order without groups. >>> s.rank(method='first') 0 1.0 1 2.0 2 3.0 3 4.0 Name: A, dtype: float64 If method is set to 'dense', it leaves no gaps in group. >>> s.rank(method='dense') 0 1.0 1 2.0 2 2.0 3 3.0 Name: A, dtype: float64 """ return self._rank(method, ascending).spark.analyzed def _rank(self, method="average", ascending=True, *, part_cols=()): if method not in ["average", "min", "max", "first", "dense"]: msg = "method must be one of 'average', 'min', 'max', 'first', 'dense'" raise ValueError(msg) if self._internal.index_level > 1: raise ValueError("rank do not support index now") if ascending: asc_func = lambda scol: scol.asc() else: asc_func = lambda scol: scol.desc() if method == "first": window = ( Window.orderBy( asc_func(self.spark.column), asc_func(F.col(NATURAL_ORDER_COLUMN_NAME)), ) .partitionBy(*part_cols) .rowsBetween(Window.unboundedPreceding, Window.currentRow) ) scol = F.row_number().over(window) elif method == "dense": window = ( Window.orderBy(asc_func(self.spark.column)) .partitionBy(*part_cols) .rowsBetween(Window.unboundedPreceding, Window.currentRow) ) scol = F.dense_rank().over(window) else: if method == "average": stat_func = F.mean elif method == "min": stat_func = F.min elif method == "max": stat_func = F.max window1 = ( Window.orderBy(asc_func(self.spark.column)) .partitionBy(*part_cols) .rowsBetween(Window.unboundedPreceding, Window.currentRow) ) window2 = Window.partitionBy([self.spark.column] + list(part_cols)).rowsBetween( Window.unboundedPreceding, Window.unboundedFollowing ) scol = stat_func(F.row_number().over(window1)).over(window2) kser = self._with_new_scol(scol) return kser.astype(np.float64) def filter(self, items=None, like=None, regex=None, axis=None) -> "Series": axis = validate_axis(axis) if axis == 1: raise ValueError("Series does not support columns axis.") return first_series( self.to_frame().filter(items=items, like=like, regex=regex, axis=axis) ).rename(self.name) filter.__doc__ = DataFrame.filter.__doc__ def describe(self, percentiles: Optional[List[float]] = None) -> "Series": return first_series(self.to_frame().describe(percentiles)).rename(self.name) describe.__doc__ = DataFrame.describe.__doc__ def diff(self, periods=1) -> "Series": """ First discrete difference of element. Calculates the difference of a Series element compared with another element in the DataFrame (default is the element in the same column of the previous row). .. note:: the current implementation of diff uses Spark's Window without specifying partition specification. This leads to move all data into single partition in single machine and could cause serious performance degradation. Avoid this method against very large dataset. Parameters ---------- periods : int, default 1 Periods to shift for calculating difference, accepts negative values. Returns ------- diffed : Series Examples -------- >>> df = ks.DataFrame({'a': [1, 2, 3, 4, 5, 6], ... 'b': [1, 1, 2, 3, 5, 8], ... 'c': [1, 4, 9, 16, 25, 36]}, columns=['a', 'b', 'c']) >>> df a b c 0 1 1 1 1 2 1 4 2 3 2 9 3 4 3 16 4 5 5 25 5 6 8 36 >>> df.b.diff() 0 NaN 1 0.0 2 1.0 3 1.0 4 2.0 5 3.0 Name: b, dtype: float64 Difference with previous value >>> df.c.diff(periods=3) 0 NaN 1 NaN 2 NaN 3 15.0 4 21.0 5 27.0 Name: c, dtype: float64 Difference with following value >>> df.c.diff(periods=-1) 0 -3.0 1 -5.0 2 -7.0 3 -9.0 4 -11.0 5 NaN Name: c, dtype: float64 """ return self._diff(periods).spark.analyzed def _diff(self, periods, *, part_cols=()): if not isinstance(periods, int): raise ValueError("periods should be an int; however, got [%s]" % type(periods).__name__) window = ( Window.partitionBy(*part_cols) .orderBy(NATURAL_ORDER_COLUMN_NAME) .rowsBetween(-periods, -periods) ) scol = self.spark.column - F.lag(self.spark.column, periods).over(window) return self._with_new_scol(scol, dtype=self.dtype) def idxmax(self, skipna=True) -> Union[Tuple, Any]: """ Return the row label of the maximum value. If multiple values equal the maximum, the first row label with that value is returned. Parameters ---------- skipna : bool, default True Exclude NA/null values. If the entire Series is NA, the result will be NA. Returns ------- Index Label of the maximum value. Raises ------ ValueError If the Series is empty. See Also -------- Series.idxmin : Return index *label* of the first occurrence of minimum of values. Examples -------- >>> s = ks.Series(data=[1, None, 4, 3, 5], ... index=['A', 'B', 'C', 'D', 'E']) >>> s A 1.0 B NaN C 4.0 D 3.0 E 5.0 dtype: float64 >>> s.idxmax() 'E' If `skipna` is False and there is an NA value in the data, the function returns ``nan``. >>> s.idxmax(skipna=False) nan In case of multi-index, you get a tuple: >>> index = pd.MultiIndex.from_arrays([ ... ['a', 'a', 'b', 'b'], ['c', 'd', 'e', 'f']], names=('first', 'second')) >>> s = ks.Series(data=[1, None, 4, 5], index=index) >>> s first second a c 1.0 d NaN b e 4.0 f 5.0 dtype: float64 >>> s.idxmax() ('b', 'f') If multiple values equal the maximum, the first row label with that value is returned. >>> s = ks.Series([1, 100, 1, 100, 1, 100], index=[10, 3, 5, 2, 1, 8]) >>> s 10 1 3 100 5 1 2 100 1 1 8 100 dtype: int64 >>> s.idxmax() 3 """ sdf = self._internal.spark_frame scol = self.spark.column index_scols = self._internal.index_spark_columns # desc_nulls_(last|first) is used via Py4J directly because # it's not supported in Spark 2.3. if skipna: sdf = sdf.orderBy(Column(scol._jc.desc_nulls_last()), NATURAL_ORDER_COLUMN_NAME) else: sdf = sdf.orderBy(Column(scol._jc.desc_nulls_first()), NATURAL_ORDER_COLUMN_NAME) results = sdf.select([scol] + index_scols).take(1) if len(results) == 0: raise ValueError("attempt to get idxmin of an empty sequence") if results[0][0] is None: # This will only happens when skipna is False because we will # place nulls first. return np.nan values = list(results[0][1:]) if len(values) == 1: return values[0] else: return tuple(values) def idxmin(self, skipna=True) -> Union[Tuple, Any]: """ Return the row label of the minimum value. If multiple values equal the minimum, the first row label with that value is returned. Parameters ---------- skipna : bool, default True Exclude NA/null values. If the entire Series is NA, the result will be NA. Returns ------- Index Label of the minimum value. Raises ------ ValueError If the Series is empty. See Also -------- Series.idxmax : Return index *label* of the first occurrence of maximum of values. Notes ----- This method is the Series version of ``ndarray.argmin``. This method returns the label of the minimum, while ``ndarray.argmin`` returns the position. To get the position, use ``series.values.argmin()``. Examples -------- >>> s = ks.Series(data=[1, None, 4, 0], ... index=['A', 'B', 'C', 'D']) >>> s A 1.0 B NaN C 4.0 D 0.0 dtype: float64 >>> s.idxmin() 'D' If `skipna` is False and there is an NA value in the data, the function returns ``nan``. >>> s.idxmin(skipna=False) nan In case of multi-index, you get a tuple: >>> index = pd.MultiIndex.from_arrays([ ... ['a', 'a', 'b', 'b'], ['c', 'd', 'e', 'f']], names=('first', 'second')) >>> s = ks.Series(data=[1, None, 4, 0], index=index) >>> s first second a c 1.0 d NaN b e 4.0 f 0.0 dtype: float64 >>> s.idxmin() ('b', 'f') If multiple values equal the minimum, the first row label with that value is returned. >>> s = ks.Series([1, 100, 1, 100, 1, 100], index=[10, 3, 5, 2, 1, 8]) >>> s 10 1 3 100 5 1 2 100 1 1 8 100 dtype: int64 >>> s.idxmin() 10 """ sdf = self._internal.spark_frame scol = self.spark.column index_scols = self._internal.index_spark_columns # asc_nulls_(last|first)is used via Py4J directly because # it's not supported in Spark 2.3. if skipna: sdf = sdf.orderBy(Column(scol._jc.asc_nulls_last()), NATURAL_ORDER_COLUMN_NAME) else: sdf = sdf.orderBy(Column(scol._jc.asc_nulls_first()), NATURAL_ORDER_COLUMN_NAME) results = sdf.select([scol] + index_scols).take(1) if len(results) == 0: raise ValueError("attempt to get idxmin of an empty sequence") if results[0][0] is None: # This will only happens when skipna is False because we will # place nulls first. return np.nan values = list(results[0][1:]) if len(values) == 1: return values[0] else: return tuple(values) def pop(self, item) -> Union["Series", Scalar]: """ Return item and drop from series. Parameters ---------- item : str Label of index to be popped. Returns ------- Value that is popped from series. Examples -------- >>> s = ks.Series(data=np.arange(3), index=['A', 'B', 'C']) >>> s A 0 B 1 C 2 dtype: int64 >>> s.pop('A') 0 >>> s B 1 C 2 dtype: int64 >>> s = ks.Series(data=np.arange(3), index=['A', 'A', 'C']) >>> s A 0 A 1 C 2 dtype: int64 >>> s.pop('A') A 0 A 1 dtype: int64 >>> s C 2 dtype: int64 Also support for MultiIndex >>> midx = pd.MultiIndex([['lama', 'cow', 'falcon'], ... ['speed', 'weight', 'length']], ... [[0, 0, 0, 1, 1, 1, 2, 2, 2], ... [0, 1, 2, 0, 1, 2, 0, 1, 2]]) >>> s = ks.Series([45, 200, 1.2, 30, 250, 1.5, 320, 1, 0.3], ... index=midx) >>> s lama speed 45.0 weight 200.0 length 1.2 cow speed 30.0 weight 250.0 length 1.5 falcon speed 320.0 weight 1.0 length 0.3 dtype: float64 >>> s.pop('lama') speed 45.0 weight 200.0 length 1.2 dtype: float64 >>> s cow speed 30.0 weight 250.0 length 1.5 falcon speed 320.0 weight 1.0 length 0.3 dtype: float64 Also support for MultiIndex with several indexs. >>> midx = pd.MultiIndex([['a', 'b', 'c'], ... ['lama', 'cow', 'falcon'], ... ['speed', 'weight', 'length']], ... [[0, 0, 0, 0, 0, 0, 1, 1, 1], ... [0, 0, 0, 1, 1, 1, 2, 2, 2], ... [0, 1, 2, 0, 1, 2, 0, 0, 2]] ... ) >>> s = ks.Series([45, 200, 1.2, 30, 250, 1.5, 320, 1, 0.3], ... index=midx) >>> s a lama speed 45.0 weight 200.0 length 1.2 cow speed 30.0 weight 250.0 length 1.5 b falcon speed 320.0 speed 1.0 length 0.3 dtype: float64 >>> s.pop(('a', 'lama')) speed 45.0 weight 200.0 length 1.2 dtype: float64 >>> s a cow speed 30.0 weight 250.0 length 1.5 b falcon speed 320.0 speed 1.0 length 0.3 dtype: float64 >>> s.pop(('b', 'falcon', 'speed')) (b, falcon, speed) 320.0 (b, falcon, speed) 1.0 dtype: float64 """ if not is_name_like_value(item): raise ValueError("'key' should be string or tuple that contains strings") if not is_name_like_tuple(item): item = (item,) if self._internal.index_level < len(item): raise KeyError( "Key length ({}) exceeds index depth ({})".format( len(item), self._internal.index_level ) ) internal = self._internal scols = internal.index_spark_columns[len(item) :] + [self.spark.column] rows = [internal.spark_columns[level] == index for level, index in enumerate(item)] sdf = internal.spark_frame.filter(reduce(lambda x, y: x & y, rows)).select(scols) kdf = self._drop(item) self._update_anchor(kdf) if self._internal.index_level == len(item): # if spark_frame has one column and one data, return data only without frame pdf = sdf.limit(2).toPandas() length = len(pdf) if length == 1: return pdf[internal.data_spark_column_names[0]].iloc[0] item_string = name_like_string(item) sdf = sdf.withColumn(SPARK_DEFAULT_INDEX_NAME, F.lit(str(item_string))) internal = InternalFrame( spark_frame=sdf, index_spark_columns=[scol_for(sdf, SPARK_DEFAULT_INDEX_NAME)], column_labels=[self._column_label], data_dtypes=[self.dtype], ) return first_series(DataFrame(internal)) else: internal = internal.copy( spark_frame=sdf, index_spark_columns=[ scol_for(sdf, col) for col in internal.index_spark_column_names[len(item) :] ], index_dtypes=internal.index_dtypes[len(item) :], index_names=self._internal.index_names[len(item) :], data_spark_columns=[scol_for(sdf, internal.data_spark_column_names[0])], ) return first_series(DataFrame(internal)) def copy(self, deep=None) -> "Series": """ Make a copy of this object's indices and data. Parameters ---------- deep : None this parameter is not supported but just dummy parameter to match pandas. Returns ------- copy : Series Examples -------- >>> s = ks.Series([1, 2], index=["a", "b"]) >>> s a 1 b 2 dtype: int64 >>> s_copy = s.copy() >>> s_copy a 1 b 2 dtype: int64 """ return self._kdf.copy()._kser_for(self._column_label) def mode(self, dropna=True) -> "Series": """ Return the mode(s) of the dataset. Always returns Series even if only one value is returned. Parameters ---------- dropna : bool, default True Don't consider counts of NaN/NaT. Returns ------- Series Modes of the Series. Examples -------- >>> s = ks.Series([0, 0, 1, 1, 1, np.nan, np.nan, np.nan]) >>> s 0 0.0 1 0.0 2 1.0 3 1.0 4 1.0 5 NaN 6 NaN 7 NaN dtype: float64 >>> s.mode() 0 1.0 dtype: float64 If there are several same modes, all items are shown >>> s = ks.Series([0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, ... np.nan, np.nan, np.nan]) >>> s 0 0.0 1 0.0 2 1.0 3 1.0 4 1.0 5 2.0 6 2.0 7 2.0 8 3.0 9 3.0 10 3.0 11 NaN 12 NaN 13 NaN dtype: float64 >>> s.mode().sort_values() # doctest: +NORMALIZE_WHITESPACE, +ELLIPSIS <BLANKLINE> ... 1.0 ... 2.0 ... 3.0 dtype: float64 With 'dropna' set to 'False', we can also see NaN in the result >>> s.mode(False).sort_values() # doctest: +NORMALIZE_WHITESPACE, +ELLIPSIS <BLANKLINE> ... 1.0 ... 2.0 ... 3.0 ... NaN dtype: float64 """ ser_count = self.value_counts(dropna=dropna, sort=False) sdf_count = ser_count._internal.spark_frame most_value = ser_count.max() sdf_most_value = sdf_count.filter("count == {}".format(most_value)) sdf = sdf_most_value.select( F.col(SPARK_DEFAULT_INDEX_NAME).alias(SPARK_DEFAULT_SERIES_NAME) ) internal = InternalFrame(spark_frame=sdf, index_spark_columns=None, column_labels=[None]) return first_series(DataFrame(internal)) def keys(self) -> "ks.Index": """ Return alias for index. Returns ------- Index Index of the Series. Examples -------- >>> midx = pd.MultiIndex([['lama', 'cow', 'falcon'], ... ['speed', 'weight', 'length']], ... [[0, 0, 0, 1, 1, 1, 2, 2, 2], ... [0, 1, 2, 0, 1, 2, 0, 1, 2]]) >>> kser = ks.Series([45, 200, 1.2, 30, 250, 1.5, 320, 1, 0.3], index=midx) >>> kser.keys() # doctest: +SKIP MultiIndex([( 'lama', 'speed'), ( 'lama', 'weight'), ( 'lama', 'length'), ( 'cow', 'speed'), ( 'cow', 'weight'), ( 'cow', 'length'), ('falcon', 'speed'), ('falcon', 'weight'), ('falcon', 'length')], ) """ return self.index # TODO: 'regex', 'method' parameter def replace(self, to_replace=None, value=None, regex=False) -> "Series": """ Replace values given in to_replace with value. Values of the Series are replaced with other values dynamically. Parameters ---------- to_replace : str, list, dict, Series, int, float, or None How to find the values that will be replaced. * numeric, str: - numeric: numeric values equal to to_replace will be replaced with value - str: string exactly matching to_replace will be replaced with value * list of str or numeric: - if to_replace and value are both lists, they must be the same length. - str and numeric rules apply as above. * dict: - Dicts can be used to specify different replacement values for different existing values. For example, {'a': 'b', 'y': 'z'} replaces the value ‘a’ with ‘b’ and ‘y’ with ‘z’. To use a dict in this way the value parameter should be None. - For a DataFrame a dict can specify that different values should be replaced in different columns. For example, {'a': 1, 'b': 'z'} looks for the value 1 in column ‘a’ and the value ‘z’ in column ‘b’ and replaces these values with whatever is specified in value. The value parameter should not be None in this case. You can treat this as a special case of passing two lists except that you are specifying the column to search in. See the examples section for examples of each of these. value : scalar, dict, list, str default None Value to replace any values matching to_replace with. For a DataFrame a dict of values can be used to specify which value to use for each column (columns not in the dict will not be filled). Regular expressions, strings and lists or dicts of such objects are also allowed. Returns ------- Series Object after replacement. Examples -------- Scalar `to_replace` and `value` >>> s = ks.Series([0, 1, 2, 3, 4]) >>> s 0 0 1 1 2 2 3 3 4 4 dtype: int64 >>> s.replace(0, 5) 0 5 1 1 2 2 3 3 4 4 dtype: int64 List-like `to_replace` >>> s.replace([0, 4], 5000) 0 5000 1 1 2 2 3 3 4 5000 dtype: int64 >>> s.replace([1, 2, 3], [10, 20, 30]) 0 0 1 10 2 20 3 30 4 4 dtype: int64 Dict-like `to_replace` >>> s.replace({1: 1000, 2: 2000, 3: 3000, 4: 4000}) 0 0 1 1000 2 2000 3 3000 4 4000 dtype: int64 Also support for MultiIndex >>> midx = pd.MultiIndex([['lama', 'cow', 'falcon'], ... ['speed', 'weight', 'length']], ... [[0, 0, 0, 1, 1, 1, 2, 2, 2], ... [0, 1, 2, 0, 1, 2, 0, 1, 2]]) >>> s = ks.Series([45, 200, 1.2, 30, 250, 1.5, 320, 1, 0.3], ... index=midx) >>> s lama speed 45.0 weight 200.0 length 1.2 cow speed 30.0 weight 250.0 length 1.5 falcon speed 320.0 weight 1.0 length 0.3 dtype: float64 >>> s.replace(45, 450) lama speed 450.0 weight 200.0 length 1.2 cow speed 30.0 weight 250.0 length 1.5 falcon speed 320.0 weight 1.0 length 0.3 dtype: float64 >>> s.replace([45, 30, 320], 500) lama speed 500.0 weight 200.0 length 1.2 cow speed 500.0 weight 250.0 length 1.5 falcon speed 500.0 weight 1.0 length 0.3 dtype: float64 >>> s.replace({45: 450, 30: 300}) lama speed 450.0 weight 200.0 length 1.2 cow speed 300.0 weight 250.0 length 1.5 falcon speed 320.0 weight 1.0 length 0.3 dtype: float64 """ if to_replace is None: return self.fillna(method="ffill") if not isinstance(to_replace, (str, list, dict, int, float)): raise ValueError("'to_replace' should be one of str, list, dict, int, float") if regex: raise NotImplementedError("replace currently not support for regex") if isinstance(to_replace, list) and isinstance(value, list): if not len(to_replace) == len(value): raise ValueError( "Replacement lists must match in length. Expecting {} got {}".format( len(to_replace), len(value) ) ) to_replace = {k: v for k, v in zip(to_replace, value)} if isinstance(to_replace, dict): is_start = True if len(to_replace) == 0: current = self.spark.column else: for to_replace_, value in to_replace.items(): cond = ( (F.isnan(self.spark.column) | self.spark.column.isNull()) if pd.isna(to_replace_) else (self.spark.column == F.lit(to_replace_)) ) if is_start: current = F.when(cond, value) is_start = False else: current = current.when(cond, value) current = current.otherwise(self.spark.column) else: cond = self.spark.column.isin(to_replace) # to_replace may be a scalar if np.array(pd.isna(to_replace)).any(): cond = cond | F.isnan(self.spark.column) | self.spark.column.isNull() current = F.when(cond, value).otherwise(self.spark.column) return self._with_new_scol(current) # TODO: dtype? def update(self, other) -> None: """ Modify Series in place using non-NA values from passed Series. Aligns on index. Parameters ---------- other : Series Examples -------- >>> from databricks.koalas.config import set_option, reset_option >>> set_option("compute.ops_on_diff_frames", True) >>> s = ks.Series([1, 2, 3]) >>> s.update(ks.Series([4, 5, 6])) >>> s.sort_index() 0 4 1 5 2 6 dtype: int64 >>> s = ks.Series(['a', 'b', 'c']) >>> s.update(ks.Series(['d', 'e'], index=[0, 2])) >>> s.sort_index() 0 d 1 b 2 e dtype: object >>> s = ks.Series([1, 2, 3]) >>> s.update(ks.Series([4, 5, 6, 7, 8])) >>> s.sort_index() 0 4 1 5 2 6 dtype: int64 >>> s = ks.Series([1, 2, 3], index=[10, 11, 12]) >>> s 10 1 11 2 12 3 dtype: int64 >>> s.update(ks.Series([4, 5, 6])) >>> s.sort_index() 10 1 11 2 12 3 dtype: int64 >>> s.update(ks.Series([4, 5, 6], index=[11, 12, 13])) >>> s.sort_index() 10 1 11 4 12 5 dtype: int64 If ``other`` contains NaNs the corresponding values are not updated in the original Series. >>> s = ks.Series([1, 2, 3]) >>> s.update(ks.Series([4, np.nan, 6])) >>> s.sort_index() 0 4.0 1 2.0 2 6.0 dtype: float64 >>> reset_option("compute.ops_on_diff_frames") """ if not isinstance(other, Series): raise ValueError("'other' must be a Series") combined = combine_frames(self._kdf, other._kdf, how="leftouter") this_scol = combined["this"]._internal.spark_column_for(self._column_label) that_scol = combined["that"]._internal.spark_column_for(other._column_label) scol = ( F.when(that_scol.isNotNull(), that_scol) .otherwise(this_scol) .alias(self._kdf._internal.spark_column_name_for(self._column_label)) ) internal = combined["this"]._internal.with_new_spark_column( self._column_label, scol # TODO: dtype? ) self._kdf._update_internal_frame(internal.resolved_copy, requires_same_anchor=False) def where(self, cond, other=np.nan) -> "Series": """ Replace values where the condition is False. Parameters ---------- cond : boolean Series Where cond is True, keep the original value. Where False, replace with corresponding value from other. other : scalar, Series Entries where cond is False are replaced with corresponding value from other. Returns ------- Series Examples -------- >>> from databricks.koalas.config import set_option, reset_option >>> set_option("compute.ops_on_diff_frames", True) >>> s1 = ks.Series([0, 1, 2, 3, 4]) >>> s2 = ks.Series([100, 200, 300, 400, 500]) >>> s1.where(s1 > 0).sort_index() 0 NaN 1 1.0 2 2.0 3 3.0 4 4.0 dtype: float64 >>> s1.where(s1 > 1, 10).sort_index() 0 10 1 10 2 2 3 3 4 4 dtype: int64 >>> s1.where(s1 > 1, s1 + 100).sort_index() 0 100 1 101 2 2 3 3 4 4 dtype: int64 >>> s1.where(s1 > 1, s2).sort_index() 0 100 1 200 2 2 3 3 4 4 dtype: int64 >>> reset_option("compute.ops_on_diff_frames") """ assert isinstance(cond, Series) # We should check the DataFrame from both `cond` and `other`. should_try_ops_on_diff_frame = not same_anchor(cond, self) or ( isinstance(other, Series) and not same_anchor(other, self) ) if should_try_ops_on_diff_frame: # Try to perform it with 'compute.ops_on_diff_frame' option. kdf = self.to_frame() tmp_cond_col = verify_temp_column_name(kdf, "__tmp_cond_col__") tmp_other_col = verify_temp_column_name(kdf, "__tmp_other_col__") kdf[tmp_cond_col] = cond kdf[tmp_other_col] = other # above logic makes a Spark DataFrame looks like below: # +-----------------+---+----------------+-----------------+ # |__index_level_0__| 0|__tmp_cond_col__|__tmp_other_col__| # +-----------------+---+----------------+-----------------+ # | 0| 0| false| 100| # | 1| 1| false| 200| # | 3| 3| true| 400| # | 2| 2| true| 300| # | 4| 4| true| 500| # +-----------------+---+----------------+-----------------+ condition = ( F.when( kdf[tmp_cond_col].spark.column, kdf._kser_for(kdf._internal.column_labels[0]).spark.column, ) .otherwise(kdf[tmp_other_col].spark.column) .alias(kdf._internal.data_spark_column_names[0]) ) internal = kdf._internal.with_new_columns( [condition], column_labels=self._internal.column_labels ) return first_series(DataFrame(internal)) else: if isinstance(other, Series): other = other.spark.column condition = ( F.when(cond.spark.column, self.spark.column) .otherwise(other) .alias(self._internal.data_spark_column_names[0]) ) return self._with_new_scol(condition) def mask(self, cond, other=np.nan) -> "Series": """ Replace values where the condition is True. Parameters ---------- cond : boolean Series Where cond is False, keep the original value. Where True, replace with corresponding value from other. other : scalar, Series Entries where cond is True are replaced with corresponding value from other. Returns ------- Series Examples -------- >>> from databricks.koalas.config import set_option, reset_option >>> set_option("compute.ops_on_diff_frames", True) >>> s1 = ks.Series([0, 1, 2, 3, 4]) >>> s2 = ks.Series([100, 200, 300, 400, 500]) >>> s1.mask(s1 > 0).sort_index() 0 0.0 1 NaN 2 NaN 3 NaN 4 NaN dtype: float64 >>> s1.mask(s1 > 1, 10).sort_index() 0 0 1 1 2 10 3 10 4 10 dtype: int64 >>> s1.mask(s1 > 1, s1 + 100).sort_index() 0 0 1 1 2 102 3 103 4 104 dtype: int64 >>> s1.mask(s1 > 1, s2).sort_index() 0 0 1 1 2 300 3 400 4 500 dtype: int64 >>> reset_option("compute.ops_on_diff_frames") """ return self.where(~cond, other) def xs(self, key, level=None) -> "Series": """ Return cross-section from the Series. This method takes a `key` argument to select data at a particular level of a MultiIndex. Parameters ---------- key : label or tuple of label Label contained in the index, or partially in a MultiIndex. level : object, defaults to first n levels (n=1 or len(key)) In case of a key partially contained in a MultiIndex, indicate which levels are used. Levels can be referred by label or position. Returns ------- Series Cross-section from the original Series corresponding to the selected index levels. Examples -------- >>> midx = pd.MultiIndex([['a', 'b', 'c'], ... ['lama', 'cow', 'falcon'], ... ['speed', 'weight', 'length']], ... [[0, 0, 0, 1, 1, 1, 2, 2, 2], ... [0, 0, 0, 1, 1, 1, 2, 2, 2], ... [0, 1, 2, 0, 1, 2, 0, 1, 2]]) >>> s = ks.Series([45, 200, 1.2, 30, 250, 1.5, 320, 1, 0.3], ... index=midx) >>> s a lama speed 45.0 weight 200.0 length 1.2 b cow speed 30.0 weight 250.0 length 1.5 c falcon speed 320.0 weight 1.0 length 0.3 dtype: float64 Get values at specified index >>> s.xs('a') lama speed 45.0 weight 200.0 length 1.2 dtype: float64 Get values at several indexes >>> s.xs(('a', 'lama')) speed 45.0 weight 200.0 length 1.2 dtype: float64 Get values at specified index and level >>> s.xs('lama', level=1) a speed 45.0 weight 200.0 length 1.2 dtype: float64 """ if not isinstance(key, tuple): key = (key,) if level is None: level = 0 internal = self._internal scols = ( internal.index_spark_columns[:level] + internal.index_spark_columns[level + len(key) :] + [self.spark.column] ) rows = [internal.spark_columns[lvl] == index for lvl, index in enumerate(key, level)] sdf = internal.spark_frame.filter(reduce(lambda x, y: x & y, rows)).select(scols) if internal.index_level == len(key): # if spark_frame has one column and one data, return data only without frame pdf = sdf.limit(2).toPandas() length = len(pdf) if length == 1: return pdf[self._internal.data_spark_column_names[0]].iloc[0] index_spark_column_names = ( internal.index_spark_column_names[:level] + internal.index_spark_column_names[level + len(key) :] ) index_names = internal.index_names[:level] + internal.index_names[level + len(key) :] index_dtypes = internal.index_dtypes[:level] + internal.index_dtypes[level + len(key) :] internal = internal.copy( spark_frame=sdf, index_spark_columns=[scol_for(sdf, col) for col in index_spark_column_names], index_names=index_names, index_dtypes=index_dtypes, data_spark_columns=[scol_for(sdf, internal.data_spark_column_names[0])], ) return first_series(DataFrame(internal)) def pct_change(self, periods=1) -> "Series": """ Percentage change between the current and a prior element. .. note:: the current implementation of this API uses Spark's Window without specifying partition specification. This leads to move all data into single partition in single machine and could cause serious performance degradation. Avoid this method against very large dataset. Parameters ---------- periods : int, default 1 Periods to shift for forming percent change. Returns ------- Series Examples -------- >>> kser = ks.Series([90, 91, 85], index=[2, 4, 1]) >>> kser 2 90 4 91 1 85 dtype: int64 >>> kser.pct_change() 2 NaN 4 0.011111 1 -0.065934 dtype: float64 >>> kser.sort_index().pct_change() 1 NaN 2 0.058824 4 0.011111 dtype: float64 >>> kser.pct_change(periods=2) 2 NaN 4 NaN 1 -0.055556 dtype: float64 """ scol = self.spark.column window = Window.orderBy(NATURAL_ORDER_COLUMN_NAME).rowsBetween(-periods, -periods) prev_row = F.lag(scol, periods).over(window) return self._with_new_scol((scol - prev_row) / prev_row).spark.analyzed def combine_first(self, other) -> "Series": """ Combine Series values, choosing the calling Series's values first. Parameters ---------- other : Series The value(s) to be combined with the `Series`. Returns ------- Series The result of combining the Series with the other object. See Also -------- Series.combine : Perform elementwise operation on two Series using a given function. Notes ----- Result index will be the union of the two indexes. Examples -------- >>> s1 = ks.Series([1, np.nan]) >>> s2 = ks.Series([3, 4]) >>> with ks.option_context("compute.ops_on_diff_frames", True): ... s1.combine_first(s2) 0 1.0 1 4.0 dtype: float64 """ if not isinstance(other, ks.Series): raise ValueError("`combine_first` only allows `Series` for parameter `other`") if same_anchor(self, other): this = self.spark.column that = other.spark.column combined = self._kdf else: combined = combine_frames(self._kdf, other._kdf) this = combined["this"]._internal.spark_column_for(self._column_label) that = combined["that"]._internal.spark_column_for(other._column_label) # If `self` has missing value, use value of `other` cond = F.when(this.isNull(), that).otherwise(this) # If `self` and `other` come from same frame, the anchor should be kept if same_anchor(self, other): return self._with_new_scol(cond) # TODO: dtype? index_scols = combined._internal.index_spark_columns sdf = combined._internal.spark_frame.select( *index_scols, cond.alias(self._internal.data_spark_column_names[0]) ).distinct() internal = self._internal.with_new_sdf(sdf, data_dtypes=[None]) # TODO: dtype? return first_series(DataFrame(internal)) def dot(self, other: Union["Series", DataFrame]) -> Union[Scalar, "Series"]: """ Compute the dot product between the Series and the columns of other. This method computes the dot product between the Series and another one, or the Series and each columns of a DataFrame. It can also be called using `self @ other` in Python >= 3.5. .. note:: This API is slightly different from pandas when indexes from both Series are not aligned. To match with pandas', it requires to read the whole data for, for example, counting. pandas raises an exception; however, Koalas just proceeds and performs by ignoring mismatches with NaN permissively. >>> pdf1 = pd.Series([1, 2, 3], index=[0, 1, 2]) >>> pdf2 = pd.Series([1, 2, 3], index=[0, 1, 3]) >>> pdf1.dot(pdf2) # doctest: +SKIP ... ValueError: matrices are not aligned >>> kdf1 = ks.Series([1, 2, 3], index=[0, 1, 2]) >>> kdf2 = ks.Series([1, 2, 3], index=[0, 1, 3]) >>> kdf1.dot(kdf2) # doctest: +SKIP 5 Parameters ---------- other : Series, DataFrame. The other object to compute the dot product with its columns. Returns ------- scalar, Series Return the dot product of the Series and other if other is a Series, the Series of the dot product of Series and each rows of other if other is a DataFrame. Notes ----- The Series and other has to share the same index if other is a Series or a DataFrame. Examples -------- >>> s = ks.Series([0, 1, 2, 3]) >>> s.dot(s) 14 >>> s @ s 14 >>> kdf = ks.DataFrame({'x': [0, 1, 2, 3], 'y': [0, -1, -2, -3]}) >>> kdf x y 0 0 0 1 1 -1 2 2 -2 3 3 -3 >>> with ks.option_context("compute.ops_on_diff_frames", True): ... s.dot(kdf) ... x 14 y -14 dtype: int64 """ if isinstance(other, DataFrame): if not same_anchor(self, other): if not self.index.sort_values().equals(other.index.sort_values()): raise ValueError("matrices are not aligned") other = other.copy() column_labels = other._internal.column_labels self_column_label = verify_temp_column_name(other, "__self_column__") other[self_column_label] = self self_kser = other._kser_for(self_column_label) product_ksers = [other._kser_for(label) * self_kser for label in column_labels] dot_product_kser = DataFrame( other._internal.with_new_columns(product_ksers, column_labels=column_labels) ).sum() return cast(Series, dot_product_kser).rename(self.name) else: assert isinstance(other, Series) if not same_anchor(self, other): if len(self.index) != len(other.index): raise ValueError("matrices are not aligned") return (self * other).sum() def __matmul__(self, other): """ Matrix multiplication using binary `@` operator in Python>=3.5. """ return self.dot(other) def repeat(self, repeats: Union[int, "Series"]) -> "Series": """ Repeat elements of a Series. Returns a new Series where each element of the current Series is repeated consecutively a given number of times. Parameters ---------- repeats : int or Series The number of repetitions for each element. This should be a non-negative integer. Repeating 0 times will return an empty Series. Returns ------- Series Newly created Series with repeated elements. See Also -------- Index.repeat : Equivalent function for Index. Examples -------- >>> s = ks.Series(['a', 'b', 'c']) >>> s 0 a 1 b 2 c dtype: object >>> s.repeat(2) 0 a 1 b 2 c 0 a 1 b 2 c dtype: object >>> ks.Series([1, 2, 3]).repeat(0) Series([], dtype: int64) """ if not isinstance(repeats, (int, Series)): raise ValueError( "`repeats` argument must be integer or Series, but got {}".format(type(repeats)) ) if isinstance(repeats, Series): if LooseVersion(pyspark.__version__) < LooseVersion("2.4"): raise ValueError( "`repeats` argument must be integer with Spark<2.4, but got {}".format( type(repeats) ) ) if not same_anchor(self, repeats): kdf = self.to_frame() temp_repeats = verify_temp_column_name(kdf, "__temp_repeats__") kdf[temp_repeats] = repeats return ( kdf._kser_for(kdf._internal.column_labels[0]) .repeat(kdf[temp_repeats]) .rename(self.name) ) else: scol = F.explode( SF.array_repeat(self.spark.column, repeats.astype("int32").spark.column) ).alias(name_like_string(self.name)) sdf = self._internal.spark_frame.select(self._internal.index_spark_columns + [scol]) internal = self._internal.copy( spark_frame=sdf, index_spark_columns=[ scol_for(sdf, col) for col in self._internal.index_spark_column_names ], data_spark_columns=[scol_for(sdf, name_like_string(self.name))], ) return first_series(DataFrame(internal)) else: if repeats < 0: raise ValueError("negative dimensions are not allowed") kdf = self._kdf[[self.name]] if repeats == 0: return first_series(DataFrame(kdf._internal.with_filter(F.lit(False)))) else: return first_series(ks.concat([kdf] * repeats)) def asof(self, where) -> Union[Scalar, "Series"]: """ Return the last row(s) without any NaNs before `where`. The last row (for each element in `where`, if list) without any NaN is taken. If there is no good value, NaN is returned. .. note:: This API is dependent on :meth:`Index.is_monotonic_increasing` which can be expensive. Parameters ---------- where : index or array-like of indices Returns ------- scalar or Series The return can be: * scalar : when `self` is a Series and `where` is a scalar * Series: when `self` is a Series and `where` is an array-like Return scalar or Series Notes ----- Indices are assumed to be sorted. Raises if this is not the case. Examples -------- >>> s = ks.Series([1, 2, np.nan, 4], index=[10, 20, 30, 40]) >>> s 10 1.0 20 2.0 30 NaN 40 4.0 dtype: float64 A scalar `where`. >>> s.asof(20) 2.0 For a sequence `where`, a Series is returned. The first value is NaN, because the first element of `where` is before the first index value. >>> s.asof([5, 20]).sort_index() 5 NaN 20 2.0 dtype: float64 Missing values are not considered. The following is ``2.0``, not NaN, even though NaN is at the index location for ``30``. >>> s.asof(30) 2.0 """ should_return_series = True if isinstance(self.index, ks.MultiIndex): raise ValueError("asof is not supported for a MultiIndex") if isinstance(where, (ks.Index, ks.Series, DataFrame)): raise ValueError("where cannot be an Index, Series or a DataFrame") if not self.index.is_monotonic_increasing: raise ValueError("asof requires a sorted index") if not is_list_like(where): should_return_series = False where = [where] index_scol = self._internal.index_spark_columns[0] cond = [F.max(F.when(index_scol <= index, self.spark.column)) for index in where] sdf = self._internal.spark_frame.select(cond) if not should_return_series: result = sdf.head()[0] return result if result is not None else np.nan # The data is expected to be small so it's fine to transpose/use default index. with ks.option_context("compute.default_index_type", "distributed", "compute.max_rows", 1): kdf = ks.DataFrame(sdf) # type: DataFrame kdf.columns = pd.Index(where) return first_series(kdf.transpose()).rename(self.name) def mad(self) -> float: """ Return the mean absolute deviation of values. Examples -------- >>> s = ks.Series([1, 2, 3, 4]) >>> s 0 1 1 2 2 3 3 4 dtype: int64 >>> s.mad() 1.0 """ sdf = self._internal.spark_frame spark_column = self.spark.column avg = unpack_scalar(sdf.select(F.avg(spark_column))) mad = unpack_scalar(sdf.select(F.avg(F.abs(spark_column - avg)))) return mad def unstack(self, level=-1) -> DataFrame: """ Unstack, a.k.a. pivot, Series with MultiIndex to produce DataFrame. The level involved will automatically get sorted. Notes ----- Unlike pandas, Koalas doesn't check whether an index is duplicated or not because the checking of duplicated index requires scanning whole data which can be quite expensive. Parameters ---------- level : int, str, or list of these, default last level Level(s) to unstack, can pass level name. Returns ------- DataFrame Unstacked Series. Examples -------- >>> s = ks.Series([1, 2, 3, 4], ... index=pd.MultiIndex.from_product([['one', 'two'], ... ['a', 'b']])) >>> s one a 1 b 2 two a 3 b 4 dtype: int64 >>> s.unstack(level=-1).sort_index() a b one 1 2 two 3 4 >>> s.unstack(level=0).sort_index() one two a 1 3 b 2 4 """ if not isinstance(self.index, ks.MultiIndex): raise ValueError("Series.unstack only support for a MultiIndex") index_nlevels = self.index.nlevels if level > 0 and (level > index_nlevels - 1): raise IndexError( "Too many levels: Index has only {} levels, not {}".format(index_nlevels, level + 1) ) elif level < 0 and (level < -index_nlevels): raise IndexError( "Too many levels: Index has only {} levels, {} is not a valid level number".format( index_nlevels, level ) ) internal = self._internal.resolved_copy index_map = list(zip(internal.index_spark_column_names, internal.index_names)) pivot_col, column_label_names = index_map.pop(level) index_scol_names, index_names = zip(*index_map) col = internal.data_spark_column_names[0] sdf = internal.spark_frame sdf = sdf.groupby(list(index_scol_names)).pivot(pivot_col).agg(F.first(scol_for(sdf, col))) internal = InternalFrame( # TODO: dtypes? spark_frame=sdf, index_spark_columns=[scol_for(sdf, col) for col in index_scol_names], index_names=list(index_names), column_label_names=[column_label_names], ) return DataFrame(internal) def item(self) -> Scalar: """ Return the first element of the underlying data as a Python scalar. Returns ------- scalar The first element of Series. Raises ------ ValueError If the data is not length-1. Examples -------- >>> kser = ks.Series([10]) >>> kser.item() 10 """ return self.head(2)._to_internal_pandas().item() def iteritems(self) -> Iterable: """ Lazily iterate over (index, value) tuples. This method returns an iterable tuple (index, value). This is convenient if you want to create a lazy iterator. .. note:: Unlike pandas', the iteritems in Koalas returns generator rather zip object Returns ------- iterable Iterable of tuples containing the (index, value) pairs from a Series. See Also -------- DataFrame.items : Iterate over (column name, Series) pairs. DataFrame.iterrows : Iterate over DataFrame rows as (index, Series) pairs. Examples -------- >>> s = ks.Series(['A', 'B', 'C']) >>> for index, value in s.items(): ... print("Index : {}, Value : {}".format(index, value)) Index : 0, Value : A Index : 1, Value : B Index : 2, Value : C """ internal_index_columns = self._internal.index_spark_column_names internal_data_column = self._internal.data_spark_column_names[0] def extract_kv_from_spark_row(row): k = ( row[internal_index_columns[0]] if len(internal_index_columns) == 1 else tuple(row[c] for c in internal_index_columns) ) v = row[internal_data_column] return k, v for k, v in map( extract_kv_from_spark_row, self._internal.resolved_copy.spark_frame.toLocalIterator() ): yield k, v def items(self) -> Iterable: """This is an alias of ``iteritems``.""" return self.iteritems() def droplevel(self, level) -> "Series": """ Return Series with requested index level(s) removed. Parameters ---------- level : int, str, or list-like If a string is given, must be the name of a level If list-like, elements must be names or positional indexes of levels. Returns ------- Series Series with requested index level(s) removed. Examples -------- >>> kser = ks.Series( ... [1, 2, 3], ... index=pd.MultiIndex.from_tuples( ... [("x", "a"), ("x", "b"), ("y", "c")], names=["level_1", "level_2"] ... ), ... ) >>> kser level_1 level_2 x a 1 b 2 y c 3 dtype: int64 Removing specific index level by level >>> kser.droplevel(0) level_2 a 1 b 2 c 3 dtype: int64 Removing specific index level by name >>> kser.droplevel("level_2") level_1 x 1 x 2 y 3 dtype: int64 """ return first_series(self.to_frame().droplevel(level=level, axis=0)).rename(self.name) def tail(self, n=5) -> "Series": """ Return the last `n` rows. This function returns last `n` rows from the object based on position. It is useful for quickly verifying data, for example, after sorting or appending rows. For negative values of `n`, this function returns all rows except the first `n` rows, equivalent to ``df[n:]``. Parameters ---------- n : int, default 5 Number of rows to select. Returns ------- type of caller The last `n` rows of the caller object. See Also -------- DataFrame.head : The first `n` rows of the caller object. Examples -------- >>> kser = ks.Series([1, 2, 3, 4, 5]) >>> kser 0 1 1 2 2 3 3 4 4 5 dtype: int64 >>> kser.tail(3) # doctest: +SKIP 2 3 3 4 4 5 dtype: int64 """ return first_series(self.to_frame().tail(n=n)).rename(self.name) def explode(self) -> "Series": """ Transform each element of a list-like to a row. Returns ------- Series Exploded lists to rows; index will be duplicated for these rows. See Also -------- Series.str.split : Split string values on specified separator. Series.unstack : Unstack, a.k.a. pivot, Series with MultiIndex to produce DataFrame. DataFrame.melt : Unpivot a DataFrame from wide format to long format. DataFrame.explode : Explode a DataFrame from list-like columns to long format. Examples -------- >>> kser = ks.Series([[1, 2, 3], [], [3, 4]]) >>> kser 0 [1, 2, 3] 1 [] 2 [3, 4] dtype: object >>> kser.explode() # doctest: +SKIP 0 1.0 0 2.0 0 3.0 1 NaN 2 3.0 2 4.0 dtype: float64 """ if not isinstance(self.spark.data_type, ArrayType): return self.copy() scol = F.explode_outer(self.spark.column).alias(name_like_string(self._column_label)) internal = self._internal.with_new_columns([scol], keep_order=False) return first_series(DataFrame(internal)) def argsort(self) -> "Series": """ Return the integer indices that would sort the Series values. Unlike pandas, the index order is not preserved in the result. Returns ------- Series Positions of values within the sort order with -1 indicating nan values. Examples -------- >>> kser = ks.Series([3, 3, 4, 1, 6, 2, 3, 7, 8, 7, 10]) >>> kser 0 3 1 3 2 4 3 1 4 6 5 2 6 3 7 7 8 8 9 7 10 10 dtype: int64 >>> kser.argsort().sort_index() 0 3 1 5 2 0 3 1 4 6 5 2 6 4 7 7 8 9 9 8 10 10 dtype: int64 """ notnull = self.loc[self.notnull()] sdf_for_index = notnull._internal.spark_frame.select(notnull._internal.index_spark_columns) tmp_join_key = verify_temp_column_name(sdf_for_index, "__tmp_join_key__") sdf_for_index = InternalFrame.attach_distributed_sequence_column( sdf_for_index, tmp_join_key ) # sdf_for_index: # +----------------+-----------------+ # |__tmp_join_key__|__index_level_0__| # +----------------+-----------------+ # | 0| 0| # | 1| 1| # | 2| 2| # | 3| 3| # | 4| 4| # +----------------+-----------------+ sdf_for_data = notnull._internal.spark_frame.select( notnull.spark.column.alias("values"), NATURAL_ORDER_COLUMN_NAME ) sdf_for_data = InternalFrame.attach_distributed_sequence_column( sdf_for_data, SPARK_DEFAULT_SERIES_NAME ) # sdf_for_data: # +---+------+-----------------+ # | 0|values|__natural_order__| # +---+------+-----------------+ # | 0| 3| 25769803776| # | 1| 3| 51539607552| # | 2| 4| 77309411328| # | 3| 1| 103079215104| # | 4| 2| 128849018880| # +---+------+-----------------+ sdf_for_data = sdf_for_data.sort( scol_for(sdf_for_data, "values"), NATURAL_ORDER_COLUMN_NAME ).drop("values", NATURAL_ORDER_COLUMN_NAME) tmp_join_key = verify_temp_column_name(sdf_for_data, "__tmp_join_key__") sdf_for_data = InternalFrame.attach_distributed_sequence_column(sdf_for_data, tmp_join_key) # sdf_for_index: sdf_for_data: # +----------------+-----------------+ +----------------+---+ # |__tmp_join_key__|__index_level_0__| |__tmp_join_key__| 0| # +----------------+-----------------+ +----------------+---+ # | 0| 0| | 0| 3| # | 1| 1| | 1| 4| # | 2| 2| | 2| 0| # | 3| 3| | 3| 1| # | 4| 4| | 4| 2| # +----------------+-----------------+ +----------------+---+ sdf = sdf_for_index.join(sdf_for_data, on=tmp_join_key).drop(tmp_join_key) internal = self._internal.with_new_sdf( spark_frame=sdf, data_columns=[SPARK_DEFAULT_SERIES_NAME], data_dtypes=[None] ) kser = first_series(DataFrame(internal)) return cast( Series, ks.concat([kser, self.loc[self.isnull()].spark.transform(lambda _: F.lit(-1))]) ) def argmax(self) -> int: """ Return int position of the largest value in the Series. If the maximum is achieved in multiple locations, the first row position is returned. Returns ------- int Row position of the maximum value. Examples -------- Consider dataset containing cereal calories >>> s = ks.Series({'Corn Flakes': 100.0, 'Almond Delight': 110.0, ... 'Cinnamon Toast Crunch': 120.0, 'Cocoa Puff': 110.0}) >>> s # doctest: +SKIP Corn Flakes 100.0 Almond Delight 110.0 Cinnamon Toast Crunch 120.0 Cocoa Puff 110.0 dtype: float64 >>> s.argmax() # doctest: +SKIP 2 """ sdf = self._internal.spark_frame.select(self.spark.column, NATURAL_ORDER_COLUMN_NAME) max_value = sdf.select( F.max(scol_for(sdf, self._internal.data_spark_column_names[0])), F.first(NATURAL_ORDER_COLUMN_NAME), ).head() if max_value[1] is None: raise ValueError("attempt to get argmax of an empty sequence") elif max_value[0] is None: return -1 # We should remember the natural sequence started from 0 seq_col_name = verify_temp_column_name(sdf, "__distributed_sequence_column__") sdf = InternalFrame.attach_distributed_sequence_column( sdf.drop(NATURAL_ORDER_COLUMN_NAME), seq_col_name ) # If the maximum is achieved in multiple locations, the first row position is returned. return sdf.filter( scol_for(sdf, self._internal.data_spark_column_names[0]) == max_value[0] ).head()[0] def argmin(self) -> int: """ Return int position of the smallest value in the Series. If the minimum is achieved in multiple locations, the first row position is returned. Returns ------- int Row position of the minimum value. Examples -------- Consider dataset containing cereal calories >>> s = ks.Series({'Corn Flakes': 100.0, 'Almond Delight': 110.0, ... 'Cinnamon Toast Crunch': 120.0, 'Cocoa Puff': 110.0}) >>> s # doctest: +SKIP Corn Flakes 100.0 Almond Delight 110.0 Cinnamon Toast Crunch 120.0 Cocoa Puff 110.0 dtype: float64 >>> s.argmin() # doctest: +SKIP 0 """ sdf = self._internal.spark_frame.select(self.spark.column, NATURAL_ORDER_COLUMN_NAME) min_value = sdf.select( F.min(scol_for(sdf, self._internal.data_spark_column_names[0])), F.first(NATURAL_ORDER_COLUMN_NAME), ).head() if min_value[1] is None: raise ValueError("attempt to get argmin of an empty sequence") elif min_value[0] is None: return -1 # We should remember the natural sequence started from 0 seq_col_name = verify_temp_column_name(sdf, "__distributed_sequence_column__") sdf = InternalFrame.attach_distributed_sequence_column( sdf.drop(NATURAL_ORDER_COLUMN_NAME), seq_col_name ) # If the minimum is achieved in multiple locations, the first row position is returned. return sdf.filter( scol_for(sdf, self._internal.data_spark_column_names[0]) == min_value[0] ).head()[0] def compare( self, other: "Series", keep_shape: bool = False, keep_equal: bool = False ) -> DataFrame: """ Compare to another Series and show the differences. Parameters ---------- other : Series Object to compare with. keep_shape : bool, default False If true, all rows and columns are kept. Otherwise, only the ones with different values are kept. keep_equal : bool, default False If true, the result keeps values that are equal. Otherwise, equal values are shown as NaNs. Returns ------- DataFrame Notes ----- Matching NaNs will not appear as a difference. Examples -------- >>> from databricks.koalas.config import set_option, reset_option >>> set_option("compute.ops_on_diff_frames", True) >>> s1 = ks.Series(["a", "b", "c", "d", "e"]) >>> s2 = ks.Series(["a", "a", "c", "b", "e"]) Align the differences on columns >>> s1.compare(s2).sort_index() self other 1 b a 3 d b Keep all original rows >>> s1.compare(s2, keep_shape=True).sort_index() self other 0 None None 1 b a 2 None None 3 d b 4 None None Keep all original rows and also all original values >>> s1.compare(s2, keep_shape=True, keep_equal=True).sort_index() self other 0 a a 1 b a 2 c c 3 d b 4 e e >>> reset_option("compute.ops_on_diff_frames") """ if same_anchor(self, other): self_column_label = verify_temp_column_name(other.to_frame(), "__self_column__") other_column_label = verify_temp_column_name(self.to_frame(), "__other_column__") combined = DataFrame( self._internal.with_new_columns( [self.rename(self_column_label), other.rename(other_column_label)] ) ) # type: DataFrame else: if not self.index.equals(other.index): raise ValueError("Can only compare identically-labeled Series objects") combined = combine_frames(self.to_frame(), other.to_frame()) this_column_label = "self" that_column_label = "other" if keep_equal and keep_shape: combined.columns = pd.Index([this_column_label, that_column_label]) return combined this_data_scol = combined._internal.data_spark_columns[0] that_data_scol = combined._internal.data_spark_columns[1] index_scols = combined._internal.index_spark_columns sdf = combined._internal.spark_frame if keep_shape: this_scol = ( F.when(this_data_scol == that_data_scol, None) .otherwise(this_data_scol) .alias(this_column_label) ) that_scol = ( F.when(this_data_scol == that_data_scol, None) .otherwise(that_data_scol) .alias(that_column_label) ) else: sdf = sdf.filter(~this_data_scol.eqNullSafe(that_data_scol)) this_scol = this_data_scol.alias(this_column_label) that_scol = that_data_scol.alias(that_column_label) sdf = sdf.select(index_scols + [this_scol, that_scol, NATURAL_ORDER_COLUMN_NAME]) internal = InternalFrame( spark_frame=sdf, index_spark_columns=[ scol_for(sdf, col) for col in self._internal.index_spark_column_names ], index_names=self._internal.index_names, index_dtypes=self._internal.index_dtypes, column_labels=[(this_column_label,), (that_column_label,)], data_spark_columns=[scol_for(sdf, this_column_label), scol_for(sdf, that_column_label)], column_label_names=[None], ) return DataFrame(internal) def align( self, other: Union[DataFrame, "Series"], join: str = "outer", axis: Optional[Union[int, str]] = None, copy: bool = True, ) -> Tuple["Series", Union[DataFrame, "Series"]]: """ Align two objects on their axes with the specified join method. Join method is specified for each axis Index. Parameters ---------- other : DataFrame or Series join : {{'outer', 'inner', 'left', 'right'}}, default 'outer' axis : allowed axis of the other object, default None Align on index (0), columns (1), or both (None). copy : bool, default True Always returns new objects. If copy=False and no reindexing is required then original objects are returned. Returns ------- (left, right) : (Series, type of other) Aligned objects. Examples -------- >>> ks.set_option("compute.ops_on_diff_frames", True) >>> s1 = ks.Series([7, 8, 9], index=[10, 11, 12]) >>> s2 = ks.Series(["g", "h", "i"], index=[10, 20, 30]) >>> aligned_l, aligned_r = s1.align(s2) >>> aligned_l.sort_index() 10 7.0 11 8.0 12 9.0 20 NaN 30 NaN dtype: float64 >>> aligned_r.sort_index() 10 g 11 None 12 None 20 h 30 i dtype: object Align with the join type "inner": >>> aligned_l, aligned_r = s1.align(s2, join="inner") >>> aligned_l.sort_index() 10 7 dtype: int64 >>> aligned_r.sort_index() 10 g dtype: object Align with a DataFrame: >>> df = ks.DataFrame({"a": [1, 2, 3], "b": ["a", "b", "c"]}, index=[10, 20, 30]) >>> aligned_l, aligned_r = s1.align(df) >>> aligned_l.sort_index() 10 7.0 11 8.0 12 9.0 20 NaN 30 NaN dtype: float64 >>> aligned_r.sort_index() a b 10 1.0 a 11 NaN None 12 NaN None 20 2.0 b 30 3.0 c >>> ks.reset_option("compute.ops_on_diff_frames") """ axis = validate_axis(axis) if axis == 1: raise ValueError("Series does not support columns axis.") self_df = self.to_frame() left, right = self_df.align(other, join=join, axis=axis, copy=False) if left is self_df: left_ser = self else: left_ser = first_series(left).rename(self.name) return (left_ser.copy(), right.copy()) if copy else (left_ser, right) def _cum(self, func, skipna, part_cols=(), ascending=True): # This is used to cummin, cummax, cumsum, etc. if ascending: window = ( Window.orderBy(F.asc(NATURAL_ORDER_COLUMN_NAME)) .partitionBy(*part_cols) .rowsBetween(Window.unboundedPreceding, Window.currentRow) ) else: window = ( Window.orderBy(F.desc(NATURAL_ORDER_COLUMN_NAME)) .partitionBy(*part_cols) .rowsBetween(Window.unboundedPreceding, Window.currentRow) ) if skipna: # There is a behavior difference between pandas and PySpark. In case of cummax, # # Input: # A B # 0 2.0 1.0 # 1 5.0 NaN # 2 1.0 0.0 # 3 2.0 4.0 # 4 4.0 9.0 # # pandas: # A B # 0 2.0 1.0 # 1 5.0 NaN # 2 5.0 1.0 # 3 5.0 4.0 # 4 5.0 9.0 # # PySpark: # A B # 0 2.0 1.0 # 1 5.0 1.0 # 2 5.0 1.0 # 3 5.0 4.0 # 4 5.0 9.0 scol = F.when( # Manually sets nulls given the column defined above. self.spark.column.isNull(), F.lit(None), ).otherwise(func(self.spark.column).over(window)) else: # Here, we use two Windows. # One for real data. # The other one for setting nulls after the first null it meets. # # There is a behavior difference between pandas and PySpark. In case of cummax, # # Input: # A B # 0 2.0 1.0 # 1 5.0 NaN # 2 1.0 0.0 # 3 2.0 4.0 # 4 4.0 9.0 # # pandas: # A B # 0 2.0 1.0 # 1 5.0 NaN # 2 5.0 NaN # 3 5.0 NaN # 4 5.0 NaN # # PySpark: # A B # 0 2.0 1.0 # 1 5.0 1.0 # 2 5.0 1.0 # 3 5.0 4.0 # 4 5.0 9.0 scol = F.when( # By going through with max, it sets True after the first time it meets null. F.max(self.spark.column.isNull()).over(window), # Manually sets nulls given the column defined above. F.lit(None), ).otherwise(func(self.spark.column).over(window)) return self._with_new_scol(scol) def _cumsum(self, skipna, part_cols=()): kser = self if isinstance(kser.spark.data_type, BooleanType): kser = kser.spark.transform(lambda scol: scol.cast(LongType())) elif not isinstance(kser.spark.data_type, NumericType): raise TypeError( "Could not convert {} ({}) to numeric".format( spark_type_to_pandas_dtype(kser.spark.data_type), kser.spark.data_type.simpleString(), ) ) return kser._cum(F.sum, skipna, part_cols) def _cumprod(self, skipna, part_cols=()): if isinstance(self.spark.data_type, BooleanType): scol = self._cum( lambda scol: F.min(F.coalesce(scol, F.lit(True))), skipna, part_cols ).spark.column.cast(LongType()) elif isinstance(self.spark.data_type, NumericType): num_zeros = self._cum( lambda scol: F.sum(F.when(scol == 0, 1).otherwise(0)), skipna, part_cols ).spark.column num_negatives = self._cum( lambda scol: F.sum(F.when(scol < 0, 1).otherwise(0)), skipna, part_cols ).spark.column sign = F.when(num_negatives % 2 == 0, 1).otherwise(-1) abs_prod = F.exp( self._cum(lambda scol: F.sum(F.log(F.abs(scol))), skipna, part_cols).spark.column ) scol = F.when(num_zeros > 0, 0).otherwise(sign * abs_prod) if isinstance(self.spark.data_type, IntegralType): scol = F.round(scol).cast(LongType()) else: raise TypeError( "Could not convert {} ({}) to numeric".format( spark_type_to_pandas_dtype(self.spark.data_type), self.spark.data_type.simpleString(), ) ) return self._with_new_scol(scol) # ---------------------------------------------------------------------- # Accessor Methods # ---------------------------------------------------------------------- dt = CachedAccessor("dt", DatetimeMethods) str = CachedAccessor("str", StringMethods) plot = CachedAccessor("plot", KoalasPlotAccessor) # ---------------------------------------------------------------------- def _apply_series_op(self, op, should_resolve: bool = False): kser = op(self) if should_resolve: internal = kser._internal.resolved_copy return first_series(DataFrame(internal)) else: return kser def _reduce_for_stat_function(self, sfun, name, axis=None, numeric_only=None, **kwargs): """ Applies sfun to the column and returns a scalar Parameters ---------- sfun : the stats function to be used for aggregation name : original pandas API name. axis : used only for sanity check because series only support index axis. numeric_only : not used by this implementation, but passed down by stats functions """ from inspect import signature axis = validate_axis(axis) if axis == 1: raise ValueError("Series does not support columns axis.") num_args = len(signature(sfun).parameters) spark_column = self.spark.column spark_type = self.spark.data_type if num_args == 1: # Only pass in the column if sfun accepts only one arg scol = sfun(spark_column) else: # must be 2 assert num_args == 2 # Pass in both the column and its data type if sfun accepts two args scol = sfun(spark_column, spark_type) min_count = kwargs.get("min_count", 0) if min_count > 0: scol = F.when(Frame._count_expr(spark_column, spark_type) >= min_count, scol) result = unpack_scalar(self._internal.spark_frame.select(scol)) return result if result is not None else np.nan def __getitem__(self, key): try: if (isinstance(key, slice) and any(type(n) == int for n in [key.start, key.stop])) or ( type(key) == int and not isinstance(self.index.spark.data_type, (IntegerType, LongType)) ): # Seems like pandas Series always uses int as positional search when slicing # with ints, searches based on index values when the value is int. return self.iloc[key] return self.loc[key] except SparkPandasIndexingError: raise KeyError( "Key length ({}) exceeds index depth ({})".format( len(key), self._internal.index_level ) ) def __getattr__(self, item: str_type) -> Any: if item.startswith("__"): raise AttributeError(item) if hasattr(MissingPandasLikeSeries, item): property_or_func = getattr(MissingPandasLikeSeries, item) if isinstance(property_or_func, property): return property_or_func.fget(self) # type: ignore else: return partial(property_or_func, self) raise AttributeError("'Series' object has no attribute '{}'".format(item)) def _to_internal_pandas(self): """ Return a pandas Series directly from _internal to avoid overhead of copy. This method is for internal use only. """ return self._kdf._internal.to_pandas_frame[self.name] def __repr__(self): max_display_count = get_option("display.max_rows") if max_display_count is None: return self._to_internal_pandas().to_string(name=self.name, dtype=self.dtype) pser = self._kdf._get_or_create_repr_pandas_cache(max_display_count)[self.name] pser_length = len(pser) pser = pser.iloc[:max_display_count] if pser_length > max_display_count: repr_string = pser.to_string(length=True) rest, prev_footer = repr_string.rsplit("\n", 1) match = REPR_PATTERN.search(prev_footer) if match is not None: length = match.group("length") dtype_name = str(self.dtype.name) if self.name is None: footer = "\ndtype: {dtype}\nShowing only the first {length}".format( length=length, dtype=pprint_thing(dtype_name) ) else: footer = ( "\nName: {name}, dtype: {dtype}" "\nShowing only the first {length}".format( length=length, name=self.name, dtype=pprint_thing(dtype_name) ) ) return rest + footer return pser.to_string(name=self.name, dtype=self.dtype) def __dir__(self): if not isinstance(self.spark.data_type, StructType): fields = [] else: fields = [f for f in self.spark.data_type.fieldNames() if " " not in f] return super().__dir__() + fields def __iter__(self): return MissingPandasLikeSeries.__iter__(self) if sys.version_info >= (3, 7): # In order to support the type hints such as Series[...]. See DataFrame.__class_getitem__. def __class_getitem__(cls, tpe): return SeriesType[tpe] def unpack_scalar(sdf): """ Takes a dataframe that is supposed to contain a single row with a single scalar value, and returns this value. """ l = sdf.head(2) assert len(l) == 1, (sdf, l) row = l[0] l2 = list(row.asDict().values()) assert len(l2) == 1, (row, l2) return l2[0] def first_series(df) -> Union["Series", pd.Series]: """ Takes a DataFrame and returns the first column of the DataFrame as a Series """ assert isinstance(df, (DataFrame, pd.DataFrame)), type(df) if isinstance(df, DataFrame): return df._kser_for(df._internal.column_labels[0]) else: return df[df.columns[0]]
1
17,931
@itholic can you also update the parameters in the docs?
databricks-koalas
py
@@ -292,6 +292,11 @@ public final class IntMap<T> implements Traversable<T>, Serializable { public int characteristics() { return spliterator.characteristics(); } + + @Override + public Comparator<? super T> getComparator() { + return null; + } } return new SpliteratorProxy(original.spliterator()); }
1
/* / \____ _ _ ____ ______ / \ ____ __ _______ * / / \/ \ / \/ \ / /\__\/ // \/ \ // /\__\ JΛVΛSLΛNG * _/ / /\ \ \/ / /\ \\__\\ \ // /\ \ /\\/ \ /__\ \ Copyright 2014-2017 Javaslang, http://javaslang.io * /___/\_/ \_/\____/\_/ \_/\__\/__/\__\_/ \_// \__/\_____/ Licensed under the Apache License, Version 2.0 */ package javaslang.collection; import javaslang.Tuple; import javaslang.Tuple2; import javaslang.Tuple3; import javaslang.control.Option; import java.io.Serializable; import java.util.Comparator; import java.util.Objects; import java.util.Spliterator; import java.util.function.*; public final class IntMap<T> implements Traversable<T>, Serializable { private static final long serialVersionUID = 1L; private final Map<Integer, T> original; private static final IntMap<?> EMPTY = new IntMap<>(HashMap.empty()); @SuppressWarnings("unchecked") public static <T> IntMap<T> of(Map<Integer, T> original) { return original.isEmpty() ? (IntMap<T>) EMPTY : new IntMap<>(original); } // DEV-NOTE: needs to be used internally to ensure the isSameAs property of the original is reflected by this impl private IntMap<T> unit(Map<Integer, T> original) { return (this.original == original) ? this : of(original); } private IntMap(Map<Integer, T> original) { this.original = original; } @Override public boolean isDistinct() { return original.isDistinct(); } @Override public int hashCode() { return original.values().hashCode(); } @Override public boolean equals(Object o) { if (o instanceof IntMap) { final IntMap<?> that = (IntMap<?>) o; return original.equals(that.original) || original.values().equals(that.original.values()); } else if (o instanceof Iterable) { final Iterable<?> that = (Iterable<?>) o; return original.values().equals(that); } else { return false; } } @Override public String stringPrefix() { return "IntMap"; } @Override public String toString() { return mkString(stringPrefix() + "(", ", ", ")"); } @Override public IntMap<T> distinct() { return unit(original.distinct()); } @Override public IntMap<T> distinctBy(Comparator<? super T> comparator) { return unit(original.distinctBy((o1, o2) -> comparator.compare(o1._2, o2._2))); } @Override public <U> IntMap<T> distinctBy(Function<? super T, ? extends U> keyExtractor) { return unit(original.distinctBy(f -> keyExtractor.apply(f._2))); } @Override public IntMap<T> drop(int n) { final Map<Integer, T> dropped = original.drop(n); return dropped == original ? this : unit(dropped); } @Override public IntMap<T> dropRight(int n) { final Map<Integer, T> dropped = original.dropRight(n); return dropped == original ? this : unit(dropped); } @Override public IntMap<T> dropUntil(Predicate<? super T> predicate) { return unit(original.dropUntil(p -> predicate.test(p._2))); } @Override public IntMap<T> dropWhile(Predicate<? super T> predicate) { return unit(original.dropWhile(p -> predicate.test(p._2))); } @Override public IntMap<T> filter(Predicate<? super T> predicate) { return unit(original.filter(p -> predicate.test(p._2))); } @Override public <U> Seq<U> flatMap(Function<? super T, ? extends Iterable<? extends U>> mapper) { return original.flatMap(e -> mapper.apply(e._2)); } @Override public <U> U foldRight(U zero, BiFunction<? super T, ? super U, ? extends U> f) { Objects.requireNonNull(f, "f is null"); return original.foldRight(zero, (e, u) -> f.apply(e._2, u)); } @Override public <C> Map<C, ? extends IntMap<T>> groupBy(Function<? super T, ? extends C> classifier) { return original.groupBy(e -> classifier.apply(e._2)).map((k, v) -> Tuple.of(k, IntMap.of(v))); } @Override public Iterator<IntMap<T>> grouped(int size) { return original.grouped(size).map(IntMap::of); } @Override public boolean hasDefiniteSize() { return original.hasDefiniteSize(); } @Override public T head() { return original.head()._2; } @Override public Option<T> headOption() { return original.headOption().map(o -> o._2); } @Override public IntMap<T> init() { return IntMap.of(original.init()); } @Override public Option<? extends IntMap<T>> initOption() { return original.initOption().map(IntMap::of); } @Override public boolean isEmpty() { return original.isEmpty(); } @Override public boolean isTraversableAgain() { return original.isTraversableAgain(); } @Override public int length() { return original.length(); } @Override public <U> Seq<U> map(Function<? super T, ? extends U> mapper) { return original.map(e -> mapper.apply(e._2)); } @Override public IntMap<T> orElse(Iterable<? extends T> other) { return unit(original.orElse(List.ofAll(other).zipWithIndex().map(t -> Tuple.of(t._2, t._1)))); } @SuppressWarnings("unchecked") @Override public IntMap<T> orElse(Supplier<? extends Iterable<? extends T>> supplier) { return unit(original.orElse(() -> (Iterable<? extends Tuple2<Integer, T>>) List.ofAll(supplier.get()).zipWithIndex().map(t -> Tuple.of(t._2, t._1)))); } @Override public Tuple2<IntMap<T>, IntMap<T>> partition(Predicate<? super T> predicate) { Objects.requireNonNull(predicate, "predicate is null"); return original.partition(p -> predicate.test(p._2)).map(IntMap::of, IntMap::of); } @Override public IntMap<T> peek(Consumer<? super T> action) { original.peek(e -> action.accept(e._2)); return this; } @Override public IntMap<T> replace(T currentElement, T newElement) { final Option<Tuple2<Integer, T>> currentEntryOpt = original.find(e -> e._2.equals(currentElement)); if (currentEntryOpt.isDefined()) { final Tuple2<Integer, T> currentEntry = currentEntryOpt.get(); return unit(original.replace(currentEntry, Tuple.of(original.size() + 1, newElement))); } else { return this; } } @Override public IntMap<T> replaceAll(T currentElement, T newElement) { Map<Integer, T> result = original; for (Tuple2<Integer, T> entry : original.filter(e -> e._2.equals(currentElement))) { result = result.replaceAll(entry, Tuple.of(entry._1, newElement)); } return unit(result); } @Override public IntMap<T> retainAll(Iterable<? extends T> elements) { final Set<T> elementsSet = HashSet.ofAll(elements); return unit(original.retainAll(original.filter(e -> elementsSet.contains(e._2)))); } @Override public Traversable<T> scan(T zero, BiFunction<? super T, ? super T, ? extends T> operation) { final int[] index = new int[] { 0 }; return original.scan(Tuple.of(-1, zero), (i, t) -> Tuple.of(index[0]++, operation.apply(i._2, t._2))).values(); } @Override public <U> Traversable<U> scanLeft(U zero, BiFunction<? super U, ? super T, ? extends U> operation) { return original.scanLeft(zero, (i, t) -> operation.apply(i, t._2)); } @Override public <U> Traversable<U> scanRight(U zero, BiFunction<? super T, ? super U, ? extends U> operation) { return original.scanRight(zero, (t, i) -> operation.apply(t._2, i)); } @Override public Iterator<IntMap<T>> slideBy(Function<? super T, ?> classifier) { return original.slideBy(e -> classifier.apply(e._2)).map(IntMap::of); } @Override public Iterator<IntMap<T>> sliding(int size) { return original.sliding(size).map(IntMap::of); } @Override public Iterator<IntMap<T>> sliding(int size, int step) { return original.sliding(size, step).map(IntMap::of); } @Override public Tuple2<? extends IntMap<T>, ? extends IntMap<T>> span(Predicate<? super T> predicate) { return original.span(p -> predicate.test(p._2)).map(IntMap::of, IntMap::of); } public Spliterator<T> spliterator() { class SpliteratorProxy implements Spliterator<T> { private final Spliterator<Tuple2<Integer, T>> spliterator; private SpliteratorProxy(Spliterator<Tuple2<Integer, T>> spliterator) { this.spliterator = spliterator; } @Override public boolean tryAdvance(Consumer<? super T> action) { return spliterator.tryAdvance(a -> action.accept(a._2)); } @Override public Spliterator<T> trySplit() { return new SpliteratorProxy(spliterator.trySplit()); } @Override public long estimateSize() { return spliterator.estimateSize(); } @Override public int characteristics() { return spliterator.characteristics(); } } return new SpliteratorProxy(original.spliterator()); } @Override public IntMap<T> tail() { return IntMap.of(original.tail()); } @Override public Option<IntMap<T>> tailOption() { return original.tailOption().map(IntMap::of); } @Override public IntMap<T> take(int n) { return unit(original.take(n)); } @Override public IntMap<T> takeRight(int n) { return unit(original.takeRight(n)); } @Override public Traversable<T> takeUntil(Predicate<? super T> predicate) { return unit(original.takeUntil(p -> predicate.test(p._2))); } @Override public IntMap<T> takeWhile(Predicate<? super T> predicate) { return unit(original.takeWhile(p -> predicate.test(p._2))); } @Override public <T1, T2> Tuple2<Seq<T1>, Seq<T2>> unzip(Function<? super T, Tuple2<? extends T1, ? extends T2>> unzipper) { Objects.requireNonNull(unzipper, "unzipper is null"); return iterator().unzip(unzipper).map(Stream::ofAll, Stream::ofAll); } @Override public <T1, T2, T3> Tuple3<Seq<T1>, Seq<T2>, Seq<T3>> unzip3(Function<? super T, Tuple3<? extends T1, ? extends T2, ? extends T3>> unzipper) { Objects.requireNonNull(unzipper, "unzipper is null"); return iterator().unzip3(unzipper).map(Stream::ofAll, Stream::ofAll, Stream::ofAll); } @Override public <U> Seq<Tuple2<T, U>> zip(Iterable<? extends U> that) { return zipWith(that, Tuple::of); } @Override public <U, R> Seq<R> zipWith(Iterable<? extends U> that, BiFunction<? super T, ? super U, ? extends R> mapper) { Objects.requireNonNull(that, "that is null"); Objects.requireNonNull(mapper, "mapper is null"); return Stream.ofAll(iterator().zipWith(that, mapper)); } @Override public <U> Seq<Tuple2<T, U>> zipAll(Iterable<? extends U> that, T thisElem, U thatElem) { Objects.requireNonNull(that, "that is null"); return Stream.ofAll(iterator().zipAll(that, thisElem, thatElem)); } @Override public Seq<Tuple2<T, Integer>> zipWithIndex() { return zipWithIndex(Tuple::of); } @Override public <U> Seq<U> zipWithIndex(BiFunction<? super T, ? super Integer, ? extends U> mapper) { Objects.requireNonNull(mapper, "mapper is null"); return Stream.ofAll(iterator().zipWithIndex(mapper)); } }
1
12,074
The super impl Spliterator.getComparator() throws an IllegalStateException by default. Is it really necessary to return null? If null is used somewhere it will throw a NPE, which is roughly the same as throwing an IllegalStateException. I'm just curious - I'm sure there is a reason!
vavr-io-vavr
java
@@ -256,7 +256,7 @@ public class Avro { schema(table.schema()); withSpec(table.spec()); setAll(table.properties()); - metricsConfig(MetricsConfig.fromProperties(table.properties())); + metricsConfig(MetricsConfig.forTable(table)); return this; }
1
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.iceberg.avro; import java.io.IOException; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.function.BiFunction; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; import org.apache.avro.Conversions; import org.apache.avro.LogicalTypes; import org.apache.avro.Schema; import org.apache.avro.file.CodecFactory; import org.apache.avro.generic.GenericData; import org.apache.avro.io.DatumReader; import org.apache.avro.io.DatumWriter; import org.apache.avro.io.Encoder; import org.apache.avro.specific.SpecificData; import org.apache.iceberg.FieldMetrics; import org.apache.iceberg.FileFormat; import org.apache.iceberg.MetricsConfig; import org.apache.iceberg.PartitionSpec; import org.apache.iceberg.SchemaParser; import org.apache.iceberg.SortOrder; import org.apache.iceberg.StructLike; import org.apache.iceberg.Table; import org.apache.iceberg.deletes.EqualityDeleteWriter; import org.apache.iceberg.deletes.PositionDelete; import org.apache.iceberg.deletes.PositionDeleteWriter; import org.apache.iceberg.encryption.EncryptionKeyMetadata; import org.apache.iceberg.io.DataWriter; import org.apache.iceberg.io.DeleteSchemaUtil; import org.apache.iceberg.io.FileAppender; import org.apache.iceberg.io.InputFile; import org.apache.iceberg.io.OutputFile; import org.apache.iceberg.mapping.NameMapping; import org.apache.iceberg.relocated.com.google.common.base.Preconditions; import org.apache.iceberg.relocated.com.google.common.collect.Maps; import org.apache.iceberg.util.ArrayUtil; import static org.apache.iceberg.TableProperties.AVRO_COMPRESSION; import static org.apache.iceberg.TableProperties.AVRO_COMPRESSION_DEFAULT; import static org.apache.iceberg.TableProperties.DELETE_AVRO_COMPRESSION; public class Avro { private Avro() { } private enum CodecName { UNCOMPRESSED(CodecFactory.nullCodec()), SNAPPY(CodecFactory.snappyCodec()), GZIP(CodecFactory.deflateCodec(9)), LZ4(null), BROTLI(null), ZSTD(null); private final CodecFactory avroCodec; CodecName(CodecFactory avroCodec) { this.avroCodec = avroCodec; } public CodecFactory get() { Preconditions.checkArgument(avroCodec != null, "Missing implementation for codec %s", this); return avroCodec; } } private static final GenericData DEFAULT_MODEL = new SpecificData(); static { LogicalTypes.register(LogicalMap.NAME, schema -> LogicalMap.get()); DEFAULT_MODEL.addLogicalTypeConversion(new Conversions.DecimalConversion()); DEFAULT_MODEL.addLogicalTypeConversion(new UUIDConversion()); } public static WriteBuilder write(OutputFile file) { return new WriteBuilder(file); } public static class WriteBuilder { private final OutputFile file; private final Map<String, String> config = Maps.newHashMap(); private final Map<String, String> metadata = Maps.newLinkedHashMap(); private org.apache.iceberg.Schema schema = null; private String name = "table"; private Function<Schema, DatumWriter<?>> createWriterFunc = null; private boolean overwrite; private MetricsConfig metricsConfig; private Function<Map<String, String>, Context> createContextFunc = Context::dataContext; private WriteBuilder(OutputFile file) { this.file = file; } public WriteBuilder forTable(Table table) { schema(table.schema()); setAll(table.properties()); return this; } public WriteBuilder schema(org.apache.iceberg.Schema newSchema) { this.schema = newSchema; return this; } public WriteBuilder named(String newName) { this.name = newName; return this; } public WriteBuilder createWriterFunc(Function<Schema, DatumWriter<?>> writerFunction) { this.createWriterFunc = writerFunction; return this; } public WriteBuilder set(String property, String value) { config.put(property, value); return this; } public WriteBuilder setAll(Map<String, String> properties) { config.putAll(properties); return this; } public WriteBuilder meta(String property, String value) { metadata.put(property, value); return this; } public WriteBuilder meta(Map<String, String> properties) { metadata.putAll(properties); return this; } public WriteBuilder metricsConfig(MetricsConfig newMetricsConfig) { this.metricsConfig = newMetricsConfig; return this; } public WriteBuilder overwrite() { return overwrite(true); } public WriteBuilder overwrite(boolean enabled) { this.overwrite = enabled; return this; } // supposed to always be a private method used strictly by data and delete write builders private WriteBuilder createContextFunc(Function<Map<String, String>, Context> newCreateContextFunc) { this.createContextFunc = newCreateContextFunc; return this; } public <D> FileAppender<D> build() throws IOException { Preconditions.checkNotNull(schema, "Schema is required"); Preconditions.checkNotNull(name, "Table name is required and cannot be null"); Function<Schema, DatumWriter<?>> writerFunc; if (createWriterFunc != null) { writerFunc = createWriterFunc; } else { writerFunc = GenericAvroWriter::new; } // add the Iceberg schema to keyValueMetadata meta("iceberg.schema", SchemaParser.toJson(schema)); Context context = createContextFunc.apply(config); CodecFactory codec = context.codec(); return new AvroFileAppender<>( schema, AvroSchemaUtil.convert(schema, name), file, writerFunc, codec, metadata, metricsConfig, overwrite); } private static class Context { private final CodecFactory codec; private Context(CodecFactory codec) { this.codec = codec; } static Context dataContext(Map<String, String> config) { String codecAsString = config.getOrDefault(AVRO_COMPRESSION, AVRO_COMPRESSION_DEFAULT); CodecFactory codec = toCodec(codecAsString); return new Context(codec); } static Context deleteContext(Map<String, String> config) { // default delete config using data config Context dataContext = dataContext(config); String codecAsString = config.get(DELETE_AVRO_COMPRESSION); CodecFactory codec = codecAsString != null ? toCodec(codecAsString) : dataContext.codec(); return new Context(codec); } private static CodecFactory toCodec(String codecAsString) { try { return CodecName.valueOf(codecAsString.toUpperCase(Locale.ENGLISH)).get(); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("Unsupported compression codec: " + codecAsString); } } CodecFactory codec() { return codec; } } } public static DataWriteBuilder writeData(OutputFile file) { return new DataWriteBuilder(file); } public static class DataWriteBuilder { private final WriteBuilder appenderBuilder; private final String location; private PartitionSpec spec = null; private StructLike partition = null; private EncryptionKeyMetadata keyMetadata = null; private SortOrder sortOrder = null; private DataWriteBuilder(OutputFile file) { this.appenderBuilder = write(file); this.location = file.location(); } public DataWriteBuilder forTable(Table table) { schema(table.schema()); withSpec(table.spec()); setAll(table.properties()); metricsConfig(MetricsConfig.fromProperties(table.properties())); return this; } public DataWriteBuilder schema(org.apache.iceberg.Schema newSchema) { appenderBuilder.schema(newSchema); return this; } public DataWriteBuilder set(String property, String value) { appenderBuilder.set(property, value); return this; } public DataWriteBuilder setAll(Map<String, String> properties) { appenderBuilder.setAll(properties); return this; } public DataWriteBuilder meta(String property, String value) { appenderBuilder.meta(property, value); return this; } public DataWriteBuilder overwrite() { return overwrite(true); } public DataWriteBuilder overwrite(boolean enabled) { appenderBuilder.overwrite(enabled); return this; } public DataWriteBuilder metricsConfig(MetricsConfig newMetricsConfig) { appenderBuilder.metricsConfig(newMetricsConfig); return this; } public DataWriteBuilder createWriterFunc(Function<Schema, DatumWriter<?>> newCreateWriterFunc) { appenderBuilder.createWriterFunc(newCreateWriterFunc); return this; } public DataWriteBuilder withSpec(PartitionSpec newSpec) { this.spec = newSpec; return this; } public DataWriteBuilder withPartition(StructLike newPartition) { this.partition = newPartition; return this; } public DataWriteBuilder withKeyMetadata(EncryptionKeyMetadata metadata) { this.keyMetadata = metadata; return this; } public DataWriteBuilder withSortOrder(SortOrder newSortOrder) { this.sortOrder = newSortOrder; return this; } public <T> DataWriter<T> build() throws IOException { Preconditions.checkArgument(spec != null, "Cannot create data writer without spec"); Preconditions.checkArgument(spec.isUnpartitioned() || partition != null, "Partition must not be null when creating data writer for partitioned spec"); FileAppender<T> fileAppender = appenderBuilder.build(); return new DataWriter<>(fileAppender, FileFormat.AVRO, location, spec, partition, keyMetadata, sortOrder); } } public static DeleteWriteBuilder writeDeletes(OutputFile file) { return new DeleteWriteBuilder(file); } public static class DeleteWriteBuilder { private final WriteBuilder appenderBuilder; private final String location; private Function<Schema, DatumWriter<?>> createWriterFunc = null; private org.apache.iceberg.Schema rowSchema; private PartitionSpec spec; private StructLike partition; private EncryptionKeyMetadata keyMetadata = null; private int[] equalityFieldIds = null; private SortOrder sortOrder; private DeleteWriteBuilder(OutputFile file) { this.appenderBuilder = write(file); this.location = file.location(); } public DeleteWriteBuilder forTable(Table table) { rowSchema(table.schema()); withSpec(table.spec()); setAll(table.properties()); return this; } public DeleteWriteBuilder set(String property, String value) { appenderBuilder.set(property, value); return this; } public DeleteWriteBuilder setAll(Map<String, String> properties) { appenderBuilder.setAll(properties); return this; } public DeleteWriteBuilder meta(String property, String value) { appenderBuilder.meta(property, value); return this; } public DeleteWriteBuilder meta(Map<String, String> properties) { appenderBuilder.meta(properties); return this; } public DeleteWriteBuilder overwrite() { return overwrite(true); } public DeleteWriteBuilder overwrite(boolean enabled) { appenderBuilder.overwrite(enabled); return this; } public DeleteWriteBuilder createWriterFunc(Function<Schema, DatumWriter<?>> writerFunction) { this.createWriterFunc = writerFunction; return this; } public DeleteWriteBuilder rowSchema(org.apache.iceberg.Schema newRowSchema) { this.rowSchema = newRowSchema; return this; } public DeleteWriteBuilder withSpec(PartitionSpec newSpec) { this.spec = newSpec; return this; } public DeleteWriteBuilder withPartition(StructLike key) { this.partition = key; return this; } public DeleteWriteBuilder withKeyMetadata(EncryptionKeyMetadata metadata) { this.keyMetadata = metadata; return this; } public DeleteWriteBuilder equalityFieldIds(List<Integer> fieldIds) { this.equalityFieldIds = ArrayUtil.toIntArray(fieldIds); return this; } public DeleteWriteBuilder equalityFieldIds(int... fieldIds) { this.equalityFieldIds = fieldIds; return this; } public DeleteWriteBuilder withSortOrder(SortOrder newSortOrder) { this.sortOrder = newSortOrder; return this; } public <T> EqualityDeleteWriter<T> buildEqualityWriter() throws IOException { Preconditions.checkState(rowSchema != null, "Cannot create equality delete file without a schema`"); Preconditions.checkState(equalityFieldIds != null, "Cannot create equality delete file without delete field ids"); Preconditions.checkState(createWriterFunc != null, "Cannot create equality delete file unless createWriterFunc is set"); Preconditions.checkArgument(spec != null, "Spec must not be null when creating equality delete writer"); Preconditions.checkArgument(spec.isUnpartitioned() || partition != null, "Partition must not be null for partitioned writes"); meta("delete-type", "equality"); meta("delete-field-ids", IntStream.of(equalityFieldIds) .mapToObj(Objects::toString) .collect(Collectors.joining(", "))); // the appender uses the row schema without extra columns appenderBuilder.schema(rowSchema); appenderBuilder.createWriterFunc(createWriterFunc); appenderBuilder.createContextFunc(WriteBuilder.Context::deleteContext); return new EqualityDeleteWriter<>( appenderBuilder.build(), FileFormat.AVRO, location, spec, partition, keyMetadata, sortOrder, equalityFieldIds); } public <T> PositionDeleteWriter<T> buildPositionWriter() throws IOException { Preconditions.checkState(equalityFieldIds == null, "Cannot create position delete file using delete field ids"); Preconditions.checkArgument(spec != null, "Spec must not be null when creating position delete writer"); Preconditions.checkArgument(spec.isUnpartitioned() || partition != null, "Partition must not be null for partitioned writes"); meta("delete-type", "position"); if (rowSchema != null && createWriterFunc != null) { // the appender uses the row schema wrapped with position fields appenderBuilder.schema(DeleteSchemaUtil.posDeleteSchema(rowSchema)); appenderBuilder.createWriterFunc( avroSchema -> new PositionAndRowDatumWriter<>(createWriterFunc.apply(avroSchema))); } else { appenderBuilder.schema(DeleteSchemaUtil.pathPosSchema()); appenderBuilder.createWriterFunc(ignored -> new PositionDatumWriter()); } appenderBuilder.createContextFunc(WriteBuilder.Context::deleteContext); return new PositionDeleteWriter<>( appenderBuilder.build(), FileFormat.AVRO, location, spec, partition, keyMetadata); } } /** * A {@link DatumWriter} implementation that wraps another to produce position deletes. */ private static class PositionDatumWriter implements MetricsAwareDatumWriter<PositionDelete<?>> { private static final ValueWriter<Object> PATH_WRITER = ValueWriters.strings(); private static final ValueWriter<Long> POS_WRITER = ValueWriters.longs(); @Override public void setSchema(Schema schema) { } @Override public void write(PositionDelete<?> delete, Encoder out) throws IOException { PATH_WRITER.write(delete.path(), out); POS_WRITER.write(delete.pos(), out); } @Override public Stream<FieldMetrics> metrics() { return Stream.concat(PATH_WRITER.metrics(), POS_WRITER.metrics()); } } /** * A {@link DatumWriter} implementation that wraps another to produce position deletes with row data. * * @param <D> the type of datum written as a deleted row */ private static class PositionAndRowDatumWriter<D> implements MetricsAwareDatumWriter<PositionDelete<D>> { private static final ValueWriter<Object> PATH_WRITER = ValueWriters.strings(); private static final ValueWriter<Long> POS_WRITER = ValueWriters.longs(); private final DatumWriter<D> rowWriter; private PositionAndRowDatumWriter(DatumWriter<D> rowWriter) { this.rowWriter = rowWriter; } @Override public void setSchema(Schema schema) { Schema.Field rowField = schema.getField("row"); if (rowField != null) { rowWriter.setSchema(rowField.schema()); } } @Override public void write(PositionDelete<D> delete, Encoder out) throws IOException { PATH_WRITER.write(delete.path(), out); POS_WRITER.write(delete.pos(), out); rowWriter.write(delete.row(), out); } @Override public Stream<FieldMetrics> metrics() { return Stream.concat(PATH_WRITER.metrics(), POS_WRITER.metrics()); } } public static ReadBuilder read(InputFile file) { return new ReadBuilder(file); } public static class ReadBuilder { private final InputFile file; private final Map<String, String> renames = Maps.newLinkedHashMap(); private ClassLoader loader = Thread.currentThread().getContextClassLoader(); private NameMapping nameMapping; private boolean reuseContainers = false; private org.apache.iceberg.Schema schema = null; private Function<Schema, DatumReader<?>> createReaderFunc = null; private BiFunction<org.apache.iceberg.Schema, Schema, DatumReader<?>> createReaderBiFunc = null; private final Function<Schema, DatumReader<?>> defaultCreateReaderFunc = readSchema -> { GenericAvroReader<?> reader = new GenericAvroReader<>(readSchema); reader.setClassLoader(loader); return reader; }; private Long start = null; private Long length = null; private ReadBuilder(InputFile file) { Preconditions.checkNotNull(file, "Input file cannot be null"); this.file = file; } public ReadBuilder createReaderFunc(Function<Schema, DatumReader<?>> readerFunction) { Preconditions.checkState(createReaderBiFunc == null, "Cannot set multiple createReaderFunc"); this.createReaderFunc = readerFunction; return this; } public ReadBuilder createReaderFunc(BiFunction<org.apache.iceberg.Schema, Schema, DatumReader<?>> readerFunction) { Preconditions.checkState(createReaderFunc == null, "Cannot set multiple createReaderFunc"); this.createReaderBiFunc = readerFunction; return this; } /** * Restricts the read to the given range: [start, end = start + length). * * @param newStart the start position for this read * @param newLength the length of the range this read should scan * @return this builder for method chaining */ public ReadBuilder split(long newStart, long newLength) { this.start = newStart; this.length = newLength; return this; } public ReadBuilder project(org.apache.iceberg.Schema projectedSchema) { this.schema = projectedSchema; return this; } public ReadBuilder reuseContainers() { this.reuseContainers = true; return this; } public ReadBuilder reuseContainers(boolean shouldReuse) { this.reuseContainers = shouldReuse; return this; } public ReadBuilder rename(String fullName, String newName) { renames.put(fullName, newName); return this; } public ReadBuilder withNameMapping(NameMapping newNameMapping) { this.nameMapping = newNameMapping; return this; } public ReadBuilder classLoader(ClassLoader classLoader) { this.loader = classLoader; return this; } public <D> AvroIterable<D> build() { Preconditions.checkNotNull(schema, "Schema is required"); Function<Schema, DatumReader<?>> readerFunc; if (createReaderBiFunc != null) { readerFunc = avroSchema -> createReaderBiFunc.apply(schema, avroSchema); } else if (createReaderFunc != null) { readerFunc = createReaderFunc; } else { readerFunc = defaultCreateReaderFunc; } return new AvroIterable<>(file, new ProjectionDatumReader<>(readerFunc, schema, renames, nameMapping), start, length, reuseContainers); } } }
1
33,751
Do we need to do the same in Avro `WriteBuilder` too? I don't think we use that method right now but should make sense for consistency. We already handle that for Parquet.
apache-iceberg
java
@@ -319,6 +319,8 @@ int FlatCompiler::Compile(int argc, const char **argv) { opts.force_defaults = true; } else if (arg == "--force-empty") { opts.set_empty_to_null = false; + } else if (arg == "--java_primitive_has_method") { + opts.java_primitive_has_method = true; } else { for (size_t i = 0; i < params_.num_generators; ++i) { if (arg == params_.generators[i].generator_opt_long ||
1
/* * Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "flatbuffers/flatc.h" #include <list> namespace flatbuffers { const char *FLATC_VERSION() { return FLATBUFFERS_VERSION(); } void FlatCompiler::ParseFile( flatbuffers::Parser &parser, const std::string &filename, const std::string &contents, std::vector<const char *> &include_directories) const { auto local_include_directory = flatbuffers::StripFileName(filename); include_directories.push_back(local_include_directory.c_str()); include_directories.push_back(nullptr); if (!parser.Parse(contents.c_str(), &include_directories[0], filename.c_str())) { Error(parser.error_, false, false); } if (!parser.error_.empty()) { Warn(parser.error_, false); } include_directories.pop_back(); include_directories.pop_back(); } void FlatCompiler::LoadBinarySchema(flatbuffers::Parser &parser, const std::string &filename, const std::string &contents) { if (!parser.Deserialize(reinterpret_cast<const uint8_t *>(contents.c_str()), contents.size())) { Error("failed to load binary schema: " + filename, false, false); } } void FlatCompiler::Warn(const std::string &warn, bool show_exe_name) const { params_.warn_fn(this, warn, show_exe_name); } void FlatCompiler::Error(const std::string &err, bool usage, bool show_exe_name) const { params_.error_fn(this, err, usage, show_exe_name); } std::string FlatCompiler::GetUsageString(const char *program_name) const { std::stringstream ss; ss << "Usage: " << program_name << " [OPTION]... FILE... [-- FILE...]\n"; for (size_t i = 0; i < params_.num_generators; ++i) { const Generator &g = params_.generators[i]; std::stringstream full_name; full_name << std::setw(12) << std::left << g.generator_opt_long; const char *name = g.generator_opt_short ? g.generator_opt_short : " "; const char *help = g.generator_help; ss << " " << full_name.str() << " " << name << " " << help << ".\n"; } // clang-format off ss << " -o PATH Prefix PATH to all generated files.\n" " -I PATH Search for includes in the specified path.\n" " -M Print make rules for generated files.\n" " --version Print the version number of flatc and exit.\n" " --strict-json Strict JSON: field names must be / will be quoted,\n" " no trailing commas in tables/vectors.\n" " --allow-non-utf8 Pass non-UTF-8 input through parser and emit nonstandard\n" " \\x escapes in JSON. (Default is to raise parse error on\n" " non-UTF-8 input.)\n" " --natural-utf8 Output strings with UTF-8 as human-readable strings.\n" " By default, UTF-8 characters are printed as \\uXXXX escapes.\n" " --defaults-json Output fields whose value is the default when\n" " writing JSON\n" " --unknown-json Allow fields in JSON that are not defined in the\n" " schema. These fields will be discared when generating\n" " binaries.\n" " --no-prefix Don\'t prefix enum values with the enum type in C++.\n" " --scoped-enums Use C++11 style scoped and strongly typed enums.\n" " also implies --no-prefix.\n" " --gen-includes (deprecated), this is the default behavior.\n" " If the original behavior is required (no include\n" " statements) use --no-includes.\n" " --no-includes Don\'t generate include statements for included\n" " schemas the generated file depends on (C++).\n" " --gen-mutable Generate accessors that can mutate buffers in-place.\n" " --gen-onefile Generate single output file for C# and Go.\n" " --gen-name-strings Generate type name functions for C++.\n" " --gen-object-api Generate an additional object-based API.\n" " --gen-compare Generate operator== for object-based API types.\n" " --gen-nullable Add Clang _Nullable for C++ pointer. or @Nullable for Java\n" " --gen-generated Add @Generated annotation for Java\n" " --gen-all Generate not just code for the current schema files,\n" " but for all files it includes as well.\n" " If the language uses a single file for output (by default\n" " the case for C++ and JS), all code will end up in this one\n" " file.\n" " --cpp-include Adds an #include in generated file.\n" " --cpp-ptr-type T Set object API pointer type (default std::unique_ptr).\n" " --cpp-str-type T Set object API string type (default std::string).\n" " T::c_str(), T::length() and T::empty() must be supported.\n" " The custom type also needs to be constructible from std::string\n" " (see the --cpp-str-flex-ctor option to change this behavior).\n" " --cpp-str-flex-ctor Don't construct custom string types by passing std::string\n" " from Flatbuffers, but (char* + length).\n" " --object-prefix Customise class prefix for C++ object-based API.\n" " --object-suffix Customise class suffix for C++ object-based API.\n" " Default value is \"T\".\n" " --no-js-exports Removes Node.js style export lines in JS.\n" " --goog-js-export Uses goog.exports* for closure compiler exporting in JS.\n" " --es6-js-export Uses ECMAScript 6 export style lines in JS.\n" " --go-namespace Generate the overrided namespace in Golang.\n" " --go-import Generate the overrided import for flatbuffers in Golang\n" " (default is \"github.com/google/flatbuffers/go\").\n" " --raw-binary Allow binaries without file_indentifier to be read.\n" " This may crash flatc given a mismatched schema.\n" " --size-prefixed Input binaries are size prefixed buffers.\n" " --proto Input is a .proto, translate to .fbs.\n" " --oneof-union Translate .proto oneofs to flatbuffer unions.\n" " --grpc Generate GRPC interfaces for the specified languages.\n" " --schema Serialize schemas instead of JSON (use with -b).\n" " --bfbs-comments Add doc comments to the binary schema files.\n" " --bfbs-builtins Add builtin attributes to the binary schema files.\n" " --conform FILE Specify a schema the following schemas should be\n" " an evolution of. Gives errors if not.\n" " --conform-includes Include path for the schema given with --conform PATH\n" " --include-prefix Prefix this path to any generated include statements.\n" " PATH\n" " --keep-prefix Keep original prefix of schema include statement.\n" " --no-fb-import Don't include flatbuffers import statement for TypeScript.\n" " --no-ts-reexport Don't re-export imported dependencies for TypeScript.\n" " --short-names Use short function names for JS and TypeScript.\n" " --reflect-types Add minimal type reflection to code generation.\n" " --reflect-names Add minimal type/name reflection.\n" " --root-type T Select or override the default root_type\n" " --force-defaults Emit default values in binary output from JSON\n" " --force-empty When serializing from object API representation,\n" " force strings and vectors to empty rather than null.\n" "FILEs may be schemas (must end in .fbs), binary schemas (must end in .bfbs),\n" "or JSON files (conforming to preceding schema). FILEs after the -- must be\n" "binary flatbuffer format files.\n" "Output files are named using the base file name of the input,\n" "and written to the current directory or the path given by -o.\n" "example: " << program_name << " -c -b schema1.fbs schema2.fbs data.json\n"; // clang-format on return ss.str(); } int FlatCompiler::Compile(int argc, const char **argv) { if (params_.generators == nullptr || params_.num_generators == 0) { return 0; } flatbuffers::IDLOptions opts; std::string output_path; bool any_generator = false; bool print_make_rules = false; bool raw_binary = false; bool schema_binary = false; bool grpc_enabled = false; std::vector<std::string> filenames; std::list<std::string> include_directories_storage; std::vector<const char *> include_directories; std::vector<const char *> conform_include_directories; std::vector<bool> generator_enabled(params_.num_generators, false); size_t binary_files_from = std::numeric_limits<size_t>::max(); std::string conform_to_schema; for (int argi = 0; argi < argc; argi++) { std::string arg = argv[argi]; if (arg[0] == '-') { if (filenames.size() && arg[1] != '-') Error("invalid option location: " + arg, true); if (arg == "-o") { if (++argi >= argc) Error("missing path following: " + arg, true); output_path = flatbuffers::ConCatPathFileName( flatbuffers::PosixPath(argv[argi]), ""); } else if (arg == "-I") { if (++argi >= argc) Error("missing path following" + arg, true); include_directories_storage.push_back( flatbuffers::PosixPath(argv[argi])); include_directories.push_back( include_directories_storage.back().c_str()); } else if (arg == "--conform") { if (++argi >= argc) Error("missing path following" + arg, true); conform_to_schema = flatbuffers::PosixPath(argv[argi]); } else if (arg == "--conform-includes") { if (++argi >= argc) Error("missing path following" + arg, true); include_directories_storage.push_back( flatbuffers::PosixPath(argv[argi])); conform_include_directories.push_back( include_directories_storage.back().c_str()); } else if (arg == "--include-prefix") { if (++argi >= argc) Error("missing path following" + arg, true); opts.include_prefix = flatbuffers::ConCatPathFileName( flatbuffers::PosixPath(argv[argi]), ""); } else if (arg == "--keep-prefix") { opts.keep_include_path = true; } else if (arg == "--strict-json") { opts.strict_json = true; } else if (arg == "--allow-non-utf8") { opts.allow_non_utf8 = true; } else if (arg == "--natural-utf8") { opts.natural_utf8 = true; } else if (arg == "--no-js-exports") { opts.skip_js_exports = true; } else if (arg == "--goog-js-export") { opts.use_goog_js_export_format = true; opts.use_ES6_js_export_format = false; } else if (arg == "--es6-js-export") { opts.use_goog_js_export_format = false; opts.use_ES6_js_export_format = true; } else if (arg == "--go-namespace") { if (++argi >= argc) Error("missing golang namespace" + arg, true); opts.go_namespace = argv[argi]; } else if (arg == "--go-import") { if (++argi >= argc) Error("missing golang import" + arg, true); opts.go_import = argv[argi]; } else if (arg == "--defaults-json") { opts.output_default_scalars_in_json = true; } else if (arg == "--unknown-json") { opts.skip_unexpected_fields_in_json = true; } else if (arg == "--no-prefix") { opts.prefixed_enums = false; } else if (arg == "--scoped-enums") { opts.prefixed_enums = false; opts.scoped_enums = true; } else if (arg == "--no-union-value-namespacing") { opts.union_value_namespacing = false; } else if (arg == "--gen-mutable") { opts.mutable_buffer = true; } else if (arg == "--gen-name-strings") { opts.generate_name_strings = true; } else if (arg == "--gen-object-api") { opts.generate_object_based_api = true; } else if (arg == "--gen-compare") { opts.gen_compare = true; } else if (arg == "--cpp-include") { if (++argi >= argc) Error("missing include following" + arg, true); opts.cpp_includes.push_back(argv[argi]); } else if (arg == "--cpp-ptr-type") { if (++argi >= argc) Error("missing type following" + arg, true); opts.cpp_object_api_pointer_type = argv[argi]; } else if (arg == "--cpp-str-type") { if (++argi >= argc) Error("missing type following" + arg, true); opts.cpp_object_api_string_type = argv[argi]; } else if (arg == "--cpp-str-flex-ctor") { opts.cpp_object_api_string_flexible_constructor = true; } else if (arg == "--gen-nullable") { opts.gen_nullable = true; } else if (arg == "--gen-generated") { opts.gen_generated = true; } else if (arg == "--object-prefix") { if (++argi >= argc) Error("missing prefix following" + arg, true); opts.object_prefix = argv[argi]; } else if (arg == "--object-suffix") { if (++argi >= argc) Error("missing suffix following" + arg, true); opts.object_suffix = argv[argi]; } else if (arg == "--gen-all") { opts.generate_all = true; opts.include_dependence_headers = false; } else if (arg == "--gen-includes") { // Deprecated, remove this option some time in the future. printf("warning: --gen-includes is deprecated (it is now default)\n"); } else if (arg == "--no-includes") { opts.include_dependence_headers = false; } else if (arg == "--gen-onefile") { opts.one_file = true; } else if (arg == "--raw-binary") { raw_binary = true; } else if (arg == "--size-prefixed") { opts.size_prefixed = true; } else if (arg == "--") { // Separator between text and binary inputs. binary_files_from = filenames.size(); } else if (arg == "--proto") { opts.proto_mode = true; } else if (arg == "--oneof-union") { opts.proto_oneof_union = true; } else if (arg == "--schema") { schema_binary = true; } else if (arg == "-M") { print_make_rules = true; } else if (arg == "--version") { printf("flatc version %s\n", FLATC_VERSION()); exit(0); } else if (arg == "--grpc") { grpc_enabled = true; } else if (arg == "--bfbs-comments") { opts.binary_schema_comments = true; } else if (arg == "--bfbs-builtins") { opts.binary_schema_builtins = true; } else if (arg == "--no-fb-import") { opts.skip_flatbuffers_import = true; } else if (arg == "--no-ts-reexport") { opts.reexport_ts_modules = false; } else if (arg == "--short-names") { opts.js_ts_short_names = true; } else if (arg == "--reflect-types") { opts.mini_reflect = IDLOptions::kTypes; } else if (arg == "--reflect-names") { opts.mini_reflect = IDLOptions::kTypesAndNames; } else if (arg == "--root-type") { if (++argi >= argc) Error("missing type following" + arg, true); opts.root_type = argv[argi]; } else if (arg == "--force-defaults") { opts.force_defaults = true; } else if (arg == "--force-empty") { opts.set_empty_to_null = false; } else { for (size_t i = 0; i < params_.num_generators; ++i) { if (arg == params_.generators[i].generator_opt_long || (params_.generators[i].generator_opt_short && arg == params_.generators[i].generator_opt_short)) { generator_enabled[i] = true; any_generator = true; opts.lang_to_generate |= params_.generators[i].lang; goto found; } } Error("unknown commandline argument: " + arg, true); found:; } } else { filenames.push_back(flatbuffers::PosixPath(argv[argi])); } } if (!filenames.size()) Error("missing input files", false, true); if (opts.proto_mode) { if (any_generator) Error("cannot generate code directly from .proto files", true); } else if (!any_generator && conform_to_schema.empty()) { Error("no options: specify at least one generator.", true); } flatbuffers::Parser conform_parser; if (!conform_to_schema.empty()) { std::string contents; if (!flatbuffers::LoadFile(conform_to_schema.c_str(), true, &contents)) Error("unable to load schema: " + conform_to_schema); if (flatbuffers::GetExtension(conform_to_schema) == reflection::SchemaExtension()) { LoadBinarySchema(conform_parser, conform_to_schema, contents); } else { ParseFile(conform_parser, conform_to_schema, contents, conform_include_directories); } } std::unique_ptr<flatbuffers::Parser> parser(new flatbuffers::Parser(opts)); for (auto file_it = filenames.begin(); file_it != filenames.end(); ++file_it) { auto &filename = *file_it; std::string contents; if (!flatbuffers::LoadFile(filename.c_str(), true, &contents)) Error("unable to load file: " + filename); bool is_binary = static_cast<size_t>(file_it - filenames.begin()) >= binary_files_from; auto ext = flatbuffers::GetExtension(filename); auto is_schema = ext == "fbs" || ext == "proto"; auto is_binary_schema = ext == reflection::SchemaExtension(); if (is_binary) { parser->builder_.Clear(); parser->builder_.PushFlatBuffer( reinterpret_cast<const uint8_t *>(contents.c_str()), contents.length()); if (!raw_binary) { // Generally reading binaries that do not correspond to the schema // will crash, and sadly there's no way around that when the binary // does not contain a file identifier. // We'd expect that typically any binary used as a file would have // such an identifier, so by default we require them to match. if (!parser->file_identifier_.length()) { Error("current schema has no file_identifier: cannot test if \"" + filename + "\" matches the schema, use --raw-binary to read this file" " anyway."); } else if (!flatbuffers::BufferHasIdentifier( contents.c_str(), parser->file_identifier_.c_str(), opts.size_prefixed)) { Error("binary \"" + filename + "\" does not have expected file_identifier \"" + parser->file_identifier_ + "\", use --raw-binary to read this file anyway."); } } } else { // Check if file contains 0 bytes. if (!is_binary_schema && contents.length() != strlen(contents.c_str())) { Error("input file appears to be binary: " + filename, true); } if (is_schema) { // If we're processing multiple schemas, make sure to start each // one from scratch. If it depends on previous schemas it must do // so explicitly using an include. parser.reset(new flatbuffers::Parser(opts)); } if (is_binary_schema) { LoadBinarySchema(*parser.get(), filename, contents); } else { ParseFile(*parser.get(), filename, contents, include_directories); if (!is_schema && !parser->builder_.GetSize()) { // If a file doesn't end in .fbs, it must be json/binary. Ensure we // didn't just parse a schema with a different extension. Error("input file is neither json nor a .fbs (schema) file: " + filename, true); } } if ((is_schema || is_binary_schema) && !conform_to_schema.empty()) { auto err = parser->ConformTo(conform_parser); if (!err.empty()) Error("schemas don\'t conform: " + err); } if (schema_binary) { parser->Serialize(); parser->file_extension_ = reflection::SchemaExtension(); } } std::string filebase = flatbuffers::StripPath(flatbuffers::StripExtension(filename)); for (size_t i = 0; i < params_.num_generators; ++i) { parser->opts.lang = params_.generators[i].lang; if (generator_enabled[i]) { if (!print_make_rules) { flatbuffers::EnsureDirExists(output_path); if ((!params_.generators[i].schema_only || (is_schema || is_binary_schema)) && !params_.generators[i].generate(*parser.get(), output_path, filebase)) { Error(std::string("Unable to generate ") + params_.generators[i].lang_name + " for " + filebase); } } else { std::string make_rule = params_.generators[i].make_rule( *parser.get(), output_path, filename); if (!make_rule.empty()) printf("%s\n", flatbuffers::WordWrap(make_rule, 80, " ", " \\").c_str()); } if (grpc_enabled) { if (params_.generators[i].generateGRPC != nullptr) { if (!params_.generators[i].generateGRPC(*parser.get(), output_path, filebase)) { Error(std::string("Unable to generate GRPC interface for") + params_.generators[i].lang_name); } } else { Warn(std::string("GRPC interface generator not implemented for ") + params_.generators[i].lang_name); } } } } if (!opts.root_type.empty()) { if (!parser->SetRootType(opts.root_type.c_str())) Error("unknown root type: " + opts.root_type); else if (parser->root_struct_def_->fixed) Error("root type must be a table"); } if (opts.proto_mode) GenerateFBS(*parser.get(), output_path, filebase); // We do not want to generate code for the definitions in this file // in any files coming up next. parser->MarkGenerated(); } return 0; } } // namespace flatbuffers
1
16,325
can you make all the `_` into `-` to be consistent with the other options?
google-flatbuffers
java
@@ -0,0 +1,15 @@ +// Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package archer + +import "github.com/aws/aws-sdk-go/service/cloudformation" + +// StackConfiguration represents an entity that can be serialized +// into a Cloudformation template +type StackConfiguration interface { + StackName() string + Template() (string, error) + Parameters() []*cloudformation.Parameter + Tags() []*cloudformation.Tag +}
1
1
10,705
What do you think of renaming this file to `stack.go` or `cfn_stack.go`? `common.go`/`util.go` don't provide us anything descriptive about the contents of the file.
aws-copilot-cli
go
@@ -19,12 +19,14 @@ using System.Runtime.CompilerServices; #if SIGNED [assembly: InternalsVisibleTo("OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests, PublicKey=002400000480000094000000060200000024000052534131000400000100010051c1562a090fb0c9f391012a32198b5e5d9a60e9b80fa2d7b434c9e5ccb7259bd606e66f9660676afc6692b8cdc6793d190904551d2103b7b22fa636dcbb8208839785ba402ea08fc00c8f1500ccef28bbf599aa64ffb1e1d5dc1bf3420a3777badfe697856e9d52070a50c3ea5821c80bef17ca3acffa28f89dd413f096f898")] [assembly: InternalsVisibleTo("Benchmarks, PublicKey=002400000480000094000000060200000024000052534131000400000100010051c1562a090fb0c9f391012a32198b5e5d9a60e9b80fa2d7b434c9e5ccb7259bd606e66f9660676afc6692b8cdc6793d190904551d2103b7b22fa636dcbb8208839785ba402ea08fc00c8f1500ccef28bbf599aa64ffb1e1d5dc1bf3420a3777badfe697856e9d52070a50c3ea5821c80bef17ca3acffa28f89dd413f096f898")] +[assembly: InternalsVisibleTo("Examples.Console, PublicKey=002400000480000094000000060200000024000052534131000400000100010051c1562a090fb0c9f391012a32198b5e5d9a60e9b80fa2d7b434c9e5ccb7259bd606e66f9660676afc6692b8cdc6793d190904551d2103b7b22fa636dcbb8208839785ba402ea08fc00c8f1500ccef28bbf599aa64ffb1e1d5dc1bf3420a3777badfe697856e9d52070a50c3ea5821c80bef17ca3acffa28f89dd413f096f898")] // Used by Moq. [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")] #else [assembly: InternalsVisibleTo("OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests")] [assembly: InternalsVisibleTo("Benchmarks")] +[assembly: InternalsVisibleTo("Examples.Console")] // Used by Moq. [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
1
// <copyright file="AssemblyInfo.cs" company="OpenTelemetry Authors"> // Copyright The OpenTelemetry Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> using System.Runtime.CompilerServices; #if SIGNED [assembly: InternalsVisibleTo("OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests, PublicKey=002400000480000094000000060200000024000052534131000400000100010051c1562a090fb0c9f391012a32198b5e5d9a60e9b80fa2d7b434c9e5ccb7259bd606e66f9660676afc6692b8cdc6793d190904551d2103b7b22fa636dcbb8208839785ba402ea08fc00c8f1500ccef28bbf599aa64ffb1e1d5dc1bf3420a3777badfe697856e9d52070a50c3ea5821c80bef17ca3acffa28f89dd413f096f898")] [assembly: InternalsVisibleTo("Benchmarks, PublicKey=002400000480000094000000060200000024000052534131000400000100010051c1562a090fb0c9f391012a32198b5e5d9a60e9b80fa2d7b434c9e5ccb7259bd606e66f9660676afc6692b8cdc6793d190904551d2103b7b22fa636dcbb8208839785ba402ea08fc00c8f1500ccef28bbf599aa64ffb1e1d5dc1bf3420a3777badfe697856e9d52070a50c3ea5821c80bef17ca3acffa28f89dd413f096f898")] // Used by Moq. [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")] #else [assembly: InternalsVisibleTo("OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests")] [assembly: InternalsVisibleTo("Benchmarks")] // Used by Moq. [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] #endif
1
21,202
It isn't a very effective example if it requires access to the internals I can't tell just looking at the diff why this is needed, can you provide a little context?
open-telemetry-opentelemetry-dotnet
.cs
@@ -3,13 +3,16 @@ require 'spec_helper' require 'bolt/transport/local' require 'bolt/target' +require 'bolt/inventory' +require 'bolt_spec/transport' require_relative 'shared_examples' describe Bolt::Transport::Local, bash: true do - let(:runner) { Bolt::Transport::Local.new } + include BoltSpec::Transport + + let(:transport) { :local } let(:os_context) { posix_context } - let(:transport_conf) { {} } let(:target) { Bolt::Target.new('local://localhost', transport_conf) } it 'is always connected' do
1
# frozen_string_literal: true require 'spec_helper' require 'bolt/transport/local' require 'bolt/target' require_relative 'shared_examples' describe Bolt::Transport::Local, bash: true do let(:runner) { Bolt::Transport::Local.new } let(:os_context) { posix_context } let(:transport_conf) { {} } let(:target) { Bolt::Target.new('local://localhost', transport_conf) } it 'is always connected' do expect(runner.connected?(target)).to eq(true) end include_examples 'transport api' context 'file errors' do before(:each) do allow(FileUtils).to receive(:cp_r).and_raise('no write') allow(Dir).to receive(:mktmpdir).with(no_args).and_raise('no tmpdir') end include_examples 'transport failures' end end
1
10,101
Why does this include `bolt/inventory`?
puppetlabs-bolt
rb
@@ -427,7 +427,7 @@ public final class LinkedHashMap<K, V> implements Kind2<LinkedHashMap<?, ?>, K, Queue<Tuple2<K, V>> newList = list; HashMap<K, V> newMap = map; if (containsKey(key)) { - newList = newList.filter(t -> !t._1.equals(key)); + newList = newList.filter(t -> !Objects.equals(t._1, key)); newMap = newMap.remove(key); } newList = newList.append(Tuple.of(key, value));
1
/* / \____ _ _ ____ ______ / \ ____ __ _______ * / / \/ \ / \/ \ / /\__\/ // \/ \ // /\__\ JΛVΛSLΛNG * _/ / /\ \ \/ / /\ \\__\\ \ // /\ \ /\\/ \ /__\ \ Copyright 2014-2016 Javaslang, http://javaslang.io * /___/\_/ \_/\____/\_/ \_/\__\/__/\__\_/ \_// \__/\_____/ Licensed under the Apache License, Version 2.0 */ package javaslang.collection; import javaslang.Kind2; import javaslang.Tuple; import javaslang.Tuple2; import javaslang.control.Option; import java.io.Serializable; import java.util.ArrayList; import java.util.Comparator; import java.util.Objects; import java.util.function.*; import java.util.stream.Collector; /** * An immutable {@code LinkedHashMap} implementation. * * @author Ruslan Sennov * @since 2.0.0 */ public final class LinkedHashMap<K, V> implements Kind2<LinkedHashMap<?, ?>, K, V>, Map<K, V>, Serializable { private static final long serialVersionUID = 1L; private static final LinkedHashMap<?, ?> EMPTY = new LinkedHashMap<>(Queue.empty(), HashMap.empty()); private final Queue<Tuple2<K, V>> list; private final HashMap<K, V> map; private LinkedHashMap(Queue<Tuple2<K, V>> list, HashMap<K, V> map) { this.list = list; this.map = map; } /** * Returns a {@link java.util.stream.Collector} which may be used in conjunction with * {@link java.util.stream.Stream#collect(java.util.stream.Collector)} to obtain a {@link javaslang.collection.LinkedHashMap}. * * @param <K> The key type * @param <V> The value type * @return A {@link javaslang.collection.LinkedHashMap} Collector. */ public static <K, V> Collector<Tuple2<K, V>, ArrayList<Tuple2<K, V>>, LinkedHashMap<K, V>> collector() { final Supplier<ArrayList<Tuple2<K, V>>> supplier = ArrayList::new; final BiConsumer<ArrayList<Tuple2<K, V>>, Tuple2<K, V>> accumulator = ArrayList::add; final BinaryOperator<ArrayList<Tuple2<K, V>>> combiner = (left, right) -> { left.addAll(right); return left; }; final Function<ArrayList<Tuple2<K, V>>, LinkedHashMap<K, V>> finisher = LinkedHashMap::ofEntries; return Collector.of(supplier, accumulator, combiner, finisher); } @SuppressWarnings("unchecked") public static <K, V> LinkedHashMap<K, V> empty() { return (LinkedHashMap<K, V>) EMPTY; } /** * Narrows a widened {@code LinkedHashMap<? extends K, ? extends V>} to {@code LinkedHashMap<K, V>} * by performing a type-safe cast. This is eligible because immutable/read-only * collections are covariant. * * @param linkedHashMap A {@code LinkedHashMap}. * @param <K> Key type * @param <V> Value type * @return the given {@code linkedHashMap} instance as narrowed type {@code LinkedHashMap<K, V>}. */ @SuppressWarnings("unchecked") public static <K, V> LinkedHashMap<K, V> narrow(LinkedHashMap<? extends K, ? extends V> linkedHashMap) { return (LinkedHashMap<K, V>) linkedHashMap; } /** * Returns a singleton {@code LinkedHashMap}, i.e. a {@code LinkedHashMap} of one element. * * @param entry A map entry. * @param <K> The key type * @param <V> The value type * @return A new Map containing the given entry */ @SuppressWarnings("unchecked") public static <K, V> LinkedHashMap<K, V> of(Tuple2<? extends K, ? extends V> entry) { final HashMap<K, V> map = HashMap.of(entry); final Queue<Tuple2<K, V>> list = Queue.of((Tuple2<K, V>) entry); return new LinkedHashMap<>(list, map); } /** * Creates a LinkedHashMap of the given list of key-value pairs. * * @param pairs A list of key-value pairs * @param <K> The key type * @param <V> The value type * @return A new Map containing the given entries */ @SuppressWarnings("unchecked") public static <K, V> LinkedHashMap<K, V> of(Object... pairs) { Objects.requireNonNull(pairs, "pairs is null"); if ((pairs.length & 1) != 0) { throw new IllegalArgumentException("Odd length of key-value pairs list"); } HashMap<K, V> map = HashMap.empty(); Queue<Tuple2<K, V>> list = Queue.empty(); for (int i = 0; i < pairs.length; i += 2) { final K k = (K) pairs[i]; final V v = (V) pairs[i + 1]; map = map.put(k, v); list = list.append(Tuple.of(k, v)); } return wrap(list, map); } /** * Returns a {@code LinkedHashMap}, from a source java.util.Map. * * @param map A map entry. * @param <K> The key type * @param <V> The value type * @return A new Map containing the given map */ public static <K, V> LinkedHashMap<K, V> ofAll(java.util.Map<? extends K, ? extends V> map) { Objects.requireNonNull(map, "map is null"); LinkedHashMap<K, V> result = LinkedHashMap.empty(); for (java.util.Map.Entry<? extends K, ? extends V> entry : map.entrySet()) { result = result.put(entry.getKey(), entry.getValue()); } return result; } /** * Returns a singleton {@code LinkedHashMap}, i.e. a {@code LinkedHashMap} of one element. * * @param key A singleton map key. * @param value A singleton map value. * @param <K> The key type * @param <V> The value type * @return A new Map containing the given entry */ public static <K, V> LinkedHashMap<K, V> of(K key, V value) { final HashMap<K, V> map = HashMap.of(key, value); final Queue<Tuple2<K, V>> list = Queue.of(Tuple.of(key, value)); return new LinkedHashMap<>(list, map); } /** * Returns a LinkedHashMap containing {@code n} values of a given Function {@code f} * over a range of integer values from 0 to {@code n - 1}. * * @param <K> The key type * @param <V> The value type * @param n The number of elements in the LinkedHashMap * @param f The Function computing element values * @return A LinkedHashMap consisting of elements {@code f(0),f(1), ..., f(n - 1)} * @throws NullPointerException if {@code f} is null */ @SuppressWarnings("unchecked") public static <K, V> LinkedHashMap<K, V> tabulate(int n, Function<? super Integer, ? extends Tuple2<? extends K, ? extends V>> f) { Objects.requireNonNull(f, "f is null"); return ofEntries(Collections.tabulate(n, (Function<? super Integer, ? extends Tuple2<K, V>>) f)); } /** * Returns a LinkedHashMap containing {@code n} values supplied by a given Supplier {@code s}. * * @param <K> The key type * @param <V> The value type * @param n The number of elements in the LinkedHashMap * @param s The Supplier computing element values * @return A LinkedHashMap of size {@code n}, where each element contains the result supplied by {@code s}. * @throws NullPointerException if {@code s} is null */ @SuppressWarnings("unchecked") public static <K, V> LinkedHashMap<K, V> fill(int n, Supplier<? extends Tuple2<? extends K, ? extends V>> s) { Objects.requireNonNull(s, "s is null"); return ofEntries(Collections.fill(n, (Supplier<? extends Tuple2<K, V>>) s)); } /** * Creates a LinkedHashMap of the given entries. * * @param entries Map entries * @param <K> The key type * @param <V> The value type * @return A new Map containing the given entries */ @SuppressWarnings("unchecked") public static <K, V> LinkedHashMap<K, V> ofEntries(java.util.Map.Entry<? extends K, ? extends V>... entries) { HashMap<K, V> map = HashMap.empty(); Queue<Tuple2<K, V>> list = Queue.empty(); for (java.util.Map.Entry<? extends K, ? extends V> entry : entries) { final Tuple2<K, V> tuple = Tuple.of(entry.getKey(), entry.getValue()); map = map.put(tuple); list = list.append(tuple); } return wrap(list, map); } /** * Creates a LinkedHashMap of the given entries. * * @param entries Map entries * @param <K> The key type * @param <V> The value type * @return A new Map containing the given entries */ @SuppressWarnings("unchecked") public static <K, V> LinkedHashMap<K, V> ofEntries(Tuple2<? extends K, ? extends V>... entries) { final HashMap<K, V> map = HashMap.ofEntries(entries); final Queue<Tuple2<K, V>> list = Queue.of((Tuple2<K, V>[]) entries); return wrap(list, map); } /** * Creates a LinkedHashMap of the given entries. * * @param entries Map entries * @param <K> The key type * @param <V> The value type * @return A new Map containing the given entries */ @SuppressWarnings("unchecked") public static <K, V> LinkedHashMap<K, V> ofEntries(Iterable<? extends Tuple2<? extends K, ? extends V>> entries) { Objects.requireNonNull(entries, "entries is null"); if (entries instanceof LinkedHashMap) { return (LinkedHashMap<K, V>) entries; } else { HashMap<K, V> map = HashMap.empty(); Queue<Tuple2<K, V>> list = Queue.empty(); for (Tuple2<? extends K, ? extends V> entry : entries) { map = map.put(entry); list = list.append((Tuple2<K, V>) entry); } return wrap(list, map); } } @Override public <K2, V2> LinkedHashMap<K2, V2> bimap(Function<? super K, ? extends K2> keyMapper, Function<? super V, ? extends V2> valueMapper) { Objects.requireNonNull(keyMapper, "keyMapper is null"); Objects.requireNonNull(valueMapper, "valueMapper is null"); final Iterator<Tuple2<K2, V2>> entries = iterator().map(entry -> Tuple.of(keyMapper.apply(entry._1), valueMapper.apply(entry._2))); return LinkedHashMap.ofEntries(entries); } @Override public boolean containsKey(K key) { return map.containsKey(key); } @Override public LinkedHashMap<K, V> distinct() { return Maps.distinct(this); } @Override public LinkedHashMap<K, V> distinctBy(Comparator<? super Tuple2<K, V>> comparator) { return Maps.distinctBy(this, this::createFromEntries, comparator); } @Override public <U> LinkedHashMap<K, V> distinctBy(Function<? super Tuple2<K, V>, ? extends U> keyExtractor) { return Maps.distinctBy(this, this::createFromEntries, keyExtractor); } @Override public LinkedHashMap<K, V> drop(int n) { return Maps.drop(this, this::createFromEntries, LinkedHashMap::empty, n); } @Override public LinkedHashMap<K, V> dropRight(int n) { return Maps.dropRight(this, this::createFromEntries, LinkedHashMap::empty, n); } @Override public LinkedHashMap<K, V> dropUntil(Predicate<? super Tuple2<K, V>> predicate) { return Maps.dropUntil(this, this::createFromEntries, predicate); } @Override public LinkedHashMap<K, V> dropWhile(Predicate<? super Tuple2<K, V>> predicate) { return Maps.dropWhile(this, this::createFromEntries, predicate); } @Override public LinkedHashMap<K, V> filter(BiPredicate<? super K, ? super V> predicate) { return Maps.filter(this, this::createFromEntries, predicate); } @Override public LinkedHashMap<K, V> filter(Predicate<? super Tuple2<K, V>> predicate) { return Maps.filter(this, this::createFromEntries, predicate); } @Override public LinkedHashMap<K, V> filterKeys(Predicate<? super K> predicate) { return Maps.filterKeys(this, this::createFromEntries, predicate); } @Override public LinkedHashMap<K, V> filterValues(Predicate<? super V> predicate) { return Maps.filterValues(this, this::createFromEntries, predicate); } @Override public <K2, V2> LinkedHashMap<K2, V2> flatMap(BiFunction<? super K, ? super V, ? extends Iterable<Tuple2<K2, V2>>> mapper) { Objects.requireNonNull(mapper, "mapper is null"); return foldLeft(LinkedHashMap.<K2, V2> empty(), (acc, entry) -> { for (Tuple2<? extends K2, ? extends V2> mappedEntry : mapper.apply(entry._1, entry._2)) { acc = acc.put(mappedEntry); } return acc; }); } @Override public Option<V> get(K key) { return map.get(key); } @Override public V getOrElse(K key, V defaultValue) { return map.getOrElse(key, defaultValue); } @Override public <C> Map<C, LinkedHashMap<K, V>> groupBy(Function<? super Tuple2<K, V>, ? extends C> classifier) { return Maps.groupBy(this, this::createFromEntries, classifier); } @Override public Iterator<LinkedHashMap<K, V>> grouped(int size) { return Maps.grouped(this, this::createFromEntries, size); } @Override public Tuple2<K, V> head() { return list.head(); } @Override public LinkedHashMap<K, V> init() { if (isEmpty()) { throw new UnsupportedOperationException("init of empty LinkedHashMap"); } else { return LinkedHashMap.ofEntries(list.init()); } } @Override public Option<LinkedHashMap<K, V>> initOption() { return Maps.initOption(this); } @Override public boolean isEmpty() { return map.isEmpty(); } @Override public Iterator<Tuple2<K, V>> iterator() { return list.iterator(); } @Override public Set<K> keySet() { return map.keySet(); } @Override public <K2, V2> LinkedHashMap<K2, V2> map(BiFunction<? super K, ? super V, Tuple2<K2, V2>> mapper) { Objects.requireNonNull(mapper, "mapper is null"); return foldLeft(LinkedHashMap.empty(), (acc, entry) -> acc.put(entry.map(mapper))); } @Override public <K2> LinkedHashMap<K2, V> mapKeys(Function<? super K, ? extends K2> keyMapper) { Objects.requireNonNull(keyMapper, "keyMapper is null"); return map((k, v) -> Tuple.of(keyMapper.apply(k), v)); } @Override public <K2> LinkedHashMap<K2, V> mapKeys(Function<? super K, ? extends K2> keyMapper, BiFunction<? super V, ? super V, ? extends V> valueMerge) { return Collections.mapKeys(this, LinkedHashMap.empty(), keyMapper, valueMerge); } @Override public <W> LinkedHashMap<K, W> mapValues(Function<? super V, ? extends W> mapper) { Objects.requireNonNull(mapper, "mapper is null"); return map((k, v) -> Tuple.of(k, mapper.apply(v))); } @Override public LinkedHashMap<K, V> merge(Map<? extends K, ? extends V> that) { return Maps.merge(this, this::createFromEntries, that); } @Override public <U extends V> LinkedHashMap<K, V> merge(Map<? extends K, U> that, BiFunction<? super V, ? super U, ? extends V> collisionResolution) { return Maps.merge(this, this::createFromEntries, that, collisionResolution); } @Override public Tuple2<LinkedHashMap<K, V>, LinkedHashMap<K, V>> partition(Predicate<? super Tuple2<K, V>> predicate) { return Maps.partition(this, this::createFromEntries, predicate); } @Override public LinkedHashMap<K, V> peek(Consumer<? super Tuple2<K, V>> action) { return Maps.peek(this, action); } @Override public <U extends V> LinkedHashMap<K, V> put(K key, U value, BiFunction<? super V, ? super U, ? extends V> merge) { return Maps.put(this, key, value, merge); } @Override public LinkedHashMap<K, V> put(K key, V value) { Queue<Tuple2<K, V>> newList = list; HashMap<K, V> newMap = map; if (containsKey(key)) { newList = newList.filter(t -> !t._1.equals(key)); newMap = newMap.remove(key); } newList = newList.append(Tuple.of(key, value)); newMap = newMap.put(key, value); return new LinkedHashMap<>(newList, newMap); } @Override public LinkedHashMap<K, V> put(Tuple2<? extends K, ? extends V> entry) { return Maps.put(this, entry); } @Override public <U extends V> LinkedHashMap<K, V> put(Tuple2<? extends K, U> entry, BiFunction<? super V, ? super U, ? extends V> merge) { return Maps.put(this, entry, merge); } @Override public LinkedHashMap<K, V> remove(K key) { if (containsKey(key)) { final Queue<Tuple2<K, V>> newList = list.removeFirst(t -> t._1.equals(key)); final HashMap<K, V> newMap = map.remove(key); return wrap(newList, newMap); } else { return this; } } @Override public LinkedHashMap<K, V> removeAll(BiPredicate<? super K, ? super V> predicate) { return Maps.removeAll(this, this::createFromEntries, predicate); } @Override public LinkedHashMap<K, V> removeAll(Iterable<? extends K> keys) { Objects.requireNonNull(keys, "keys is null"); final HashSet<K> toRemove = HashSet.ofAll(keys); final Queue<Tuple2<K, V>> newList = list.filter(t -> !toRemove.contains(t._1)); final HashMap<K, V> newMap = map.filter(t -> !toRemove.contains(t._1)); return newList.size() == size() ? this : wrap(newList, newMap); } @Override public LinkedHashMap<K, V> removeKeys(Predicate<? super K> predicate) { return Maps.removeKeys(this, this::createFromEntries, predicate); } @Override public LinkedHashMap<K, V> removeValues(Predicate<? super V> predicate) { return Maps.removeValues(this, this::createFromEntries, predicate); } @Override public LinkedHashMap<K, V> replace(Tuple2<K, V> currentElement, Tuple2<K, V> newElement) { return Maps.replace(this, currentElement, newElement); } @Override public LinkedHashMap<K, V> replaceAll(Tuple2<K, V> currentElement, Tuple2<K, V> newElement) { return Maps.replaceAll(this, currentElement, newElement); } @Override public LinkedHashMap<K, V> retainAll(Iterable<? extends Tuple2<K, V>> elements) { Objects.requireNonNull(elements, "elements is null"); LinkedHashMap<K, V> result = empty(); for (Tuple2<K, V> entry : elements) { if (contains(entry)) { result = result.put(entry._1, entry._2); } } return result; } @Override public LinkedHashMap<K, V> scan( Tuple2<K, V> zero, BiFunction<? super Tuple2<K, V>, ? super Tuple2<K, V>, ? extends Tuple2<K, V>> operation) { return Maps.scan(this, LinkedHashMap::empty, zero, operation); } @Override public int size() { return map.size(); } @Override public Iterator<LinkedHashMap<K, V>> sliding(int size) { return Maps.sliding(this, this::createFromEntries, size); } @Override public Iterator<LinkedHashMap<K, V>> sliding(int size, int step) { return Maps.sliding(this, this::createFromEntries, size, step); } @Override public Tuple2<LinkedHashMap<K, V>, LinkedHashMap<K, V>> span(Predicate<? super Tuple2<K, V>> predicate) { return Maps.span(this, this::createFromEntries, predicate); } @Override public LinkedHashMap<K, V> tail() { if (isEmpty()) { throw new UnsupportedOperationException("tail of empty LinkedHashMap"); } else { return LinkedHashMap.ofEntries(list.tail()); } } @Override public Option<LinkedHashMap<K, V>> tailOption() { return Maps.tailOption(this); } @Override public LinkedHashMap<K, V> take(int n) { return Maps.take(this, this::createFromEntries, n); } @Override public LinkedHashMap<K, V> takeRight(int n) { return Maps.takeRight(this, this::createFromEntries, n); } @Override public LinkedHashMap<K, V> takeUntil(Predicate<? super Tuple2<K, V>> predicate) { return Maps.takeUntil(this, this::createFromEntries, predicate); } @Override public LinkedHashMap<K, V> takeWhile(Predicate<? super Tuple2<K, V>> predicate) { return Maps.takeWhile(this, this::createFromEntries, predicate); } @Override public java.util.LinkedHashMap<K, V> toJavaMap() { return toJavaMap(java.util.LinkedHashMap::new, t -> t); } @Override public Seq<V> values() { return map.values(); } @Override public boolean equals(Object o) { if (o == this) { return true; } else if (o instanceof LinkedHashMap) { final LinkedHashMap<?, ?> that = (LinkedHashMap<?, ?>) o; return this.list.equals(that.list); } else { return false; } } @Override public int hashCode() { return list.hashCode(); } private Object readResolve() { return isEmpty() ? EMPTY : this; } @Override public String stringPrefix() { return "LinkedHashMap"; } @Override public String toString() { return mkString(stringPrefix() + "(", ", ", ")"); } private static <K, V> LinkedHashMap<K, V> wrap(Queue<Tuple2<K, V>> list, HashMap<K, V> map) { return list.isEmpty() ? empty() : new LinkedHashMap<>(list, map); } // We need this method to narrow the argument of `ofEntries`. // If this method is static with type args <K, V>, the jdk fails to infer types at the call site. private LinkedHashMap<K, V> createFromEntries(Iterable<Tuple2<K, V>> tuples) { return LinkedHashMap.ofEntries(tuples); } }
1
10,351
We called `t._1.equals(...)` where `t._1` potentially could be `null`.
vavr-io-vavr
java
@@ -0,0 +1,14 @@ +/* global forms */ +const rangeRoles = ['progressbar', 'scrollbar', 'slider', 'spinbutton']; + +/** + * Determines if an element is an aria range element + * @method isAriaRange + * @memberof axe.commons.forms + * @param {Element} node Node to determine if aria range + * @returns {Bool} + */ +forms.isAriaRange = function(node) { + const role = axe.commons.aria.getRole(node, { noImplicit: true }); + return rangeRoles.includes(role) && node.hasAttribute('aria-valuenow'); +};
1
1
14,525
I don't think we should include the `hasAttribute` test here. Even without aria-valuenow, it's still an aria range element. This check is going to make reuse of this function problematic. Better to move the attribute check part outside this function IMO.
dequelabs-axe-core
js
@@ -35,6 +35,7 @@ class ErgonodeFixtureCommand extends Command $this->setName('ergonode:fixture:load'); $this->setDescription('Fill database with data'); $this->addOption('group', 'g', InputOption::VALUE_REQUIRED, 'Group'); + $this->addOption('file', 'f', InputOption::VALUE_REQUIRED, 'File'); } /**
1
<?php /** * Copyright © Ergonode Sp. z o.o. All rights reserved. * See LICENSE.txt for license details. */ declare(strict_types=1); namespace Ergonode\Fixture\Application\Command; use Doctrine\Migrations\Tools\BytesFormatter; use Ergonode\Fixture\Infrastructure\Process\FixtureProcess; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Stopwatch\Stopwatch; use Symfony\Component\Stopwatch\StopwatchEvent; use Ergonode\Fixture\Exception\FixtureException; class ErgonodeFixtureCommand extends Command { private FixtureProcess $process; public function __construct(FixtureProcess $process) { $this->process = $process; parent::__construct(); } public function configure(): void { $this->setName('ergonode:fixture:load'); $this->setDescription('Fill database with data'); $this->addOption('group', 'g', InputOption::VALUE_REQUIRED, 'Group'); } /** * @throws FixtureException */ public function execute(InputInterface $input, OutputInterface $output): int { $stopwatch = new Stopwatch(); $stopwatch->start('ergonode-fixture-load'); $this->process->process($input->getOption('group')); $event = $stopwatch->stop('ergonode-fixture-load'); $this->endFixtureLoad($event, $output); return 0; } private function endFixtureLoad(StopwatchEvent $stopwatchEvent, OutputInterface $output): void { $output->write("\n <comment>------------------------</comment>\n"); $output->write(sprintf( " <info>++</info> finished in %sms\n", $stopwatchEvent->getDuration() )); $output->write(sprintf( " <info>++</info> used %s memory\n", BytesFormatter::formatBytes($stopwatchEvent->getMemory()) )); } }
1
9,527
Shouldn't it be optional?
ergonode-backend
php
@@ -55,6 +55,7 @@ func newClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegio cfg, metadata.ClientInfo{ ServiceName: ServiceName, + ServiceID: "API Gateway", SigningName: signingName, SigningRegion: signingRegion, Endpoint: endpoint,
1
// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package apigateway import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/client" "github.com/aws/aws-sdk-go/aws/client/metadata" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/aws/signer/v4" "github.com/aws/aws-sdk-go/private/protocol/restjson" ) // APIGateway provides the API operation methods for making requests to // Amazon API Gateway. See this package's package overview docs // for details on the service. // // APIGateway methods are safe to use concurrently. It is not safe to // modify mutate any of the struct's properties though. type APIGateway struct { *client.Client } // Used for custom client initialization logic var initClient func(*client.Client) // Used for custom request initialization logic var initRequest func(*request.Request) // Service information constants const ( ServiceName = "apigateway" // Service endpoint prefix API calls made to. EndpointsID = ServiceName // Service ID for Regions and Endpoints metadata. ) // New creates a new instance of the APIGateway client with a session. // If additional configuration is needed for the client instance use the optional // aws.Config parameter to add your extra config. // // Example: // // Create a APIGateway client from just a session. // svc := apigateway.New(mySession) // // // Create a APIGateway client with additional configuration // svc := apigateway.New(mySession, aws.NewConfig().WithRegion("us-west-2")) func New(p client.ConfigProvider, cfgs ...*aws.Config) *APIGateway { c := p.ClientConfig(EndpointsID, cfgs...) return newClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) } // newClient creates, initializes and returns a new service client instance. func newClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *APIGateway { svc := &APIGateway{ Client: client.New( cfg, metadata.ClientInfo{ ServiceName: ServiceName, SigningName: signingName, SigningRegion: signingRegion, Endpoint: endpoint, APIVersion: "2015-07-09", }, handlers, ), } // Handlers svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) svc.Handlers.Build.PushBackNamed(restjson.BuildHandler) svc.Handlers.Unmarshal.PushBackNamed(restjson.UnmarshalHandler) svc.Handlers.UnmarshalMeta.PushBackNamed(restjson.UnmarshalMetaHandler) svc.Handlers.UnmarshalError.PushBackNamed(restjson.UnmarshalErrorHandler) // Run custom client initialization if present if initClient != nil { initClient(svc.Client) } return svc } // newRequest creates a new request for a APIGateway operation and runs any // custom request initialization. func (c *APIGateway) newRequest(op *request.Operation, params, data interface{}) *request.Request { req := c.NewRequest(op, params, data) // Run custom request initialization if present if initRequest != nil { initRequest(req) } return req }
1
9,205
would be helpful to make these a package level constant so they are accessible to the user. similar to Service Name. Not directly related note, v2 SDK ServiceName should be renamed to ServiceEndpointPrefix.
aws-aws-sdk-go
go
@@ -18,7 +18,7 @@ class Storage public function load(string $path) { - return include $this->realpath($path); + return file_exists($this->realpath($path)) ? include $this->realpath($path) : null; } public function store(string $path, string $content): void
1
<?php class Storage { public function directories(string $path): DirectoryIterator { return new DirectoryIterator( $this->realpath($path) ); } public function getDecodedJson(string $filename) { return file_exists($filename) ? json_decode(file_get_contents($filename), true) : null; } public function load(string $path) { return include $this->realpath($path); } public function store(string $path, string $content): void { $path = $this->realpath($path); file_put_contents($path, $content); } public function realpath(string $path): string { return realpath($path); } } class Output { protected $items = []; protected $eol = PHP_EOL; protected $line = PHP_EOL . PHP_EOL; protected $columns = 10; public function add(string $language, string $value = null): void { if (! array_key_exists($language, $this->items)) { $this->items[$language] = []; } if ($value) { array_push($this->items[$language], $value); } } public function get(): string { $result = $this->header(); $result .= $this->table(); foreach ($this->items as $language => $values) { $result .= $this->summary($language); $result .= $this->content($values); } return $result; } protected function header(): string { return '# Todo list' . $this->eol; } protected function summary(string $language): string { return "{$this->line}## {$language}{$this->line}"; } protected function content(array $values): string { if ($this->isEmpty($values)) { return $this->eol . 'All lines are translated 😊' . $this->eol; } $content = implode($this->eol, $values); return <<<HTML <details> <summary>show</summary> {$content} [ [to top](#todo-list) ] </details> HTML; } protected function table(): string { $result = ''; $captions = implode('|', array_fill(0, $this->columns, ' ')); $divider = implode('|', array_fill(0, $this->columns, ':---:')); $result .= "|{$captions}|{$this->eol}"; $result .= "|{$divider}|{$this->eol}"; $keys = array_keys($this->items); $rows = array_chunk($keys, $this->columns); array_map(function ($row) use (&$result) { $row = $this->tableHeaderValue($row); $result .= $row . $this->eol; }, $rows); return $result . $this->eol . $this->eol; } protected function tableHeaderValue(array $languages): string { $languages = array_map(function ($language) { $icon = $this->icon($this->items[$language]); return "[{$language} {$icon}](#$language)"; }, $languages); return implode('|', $languages); } protected function icon($values): string { $is_empty = is_array($values) ? $this->isEmpty($values) : (bool) $values; return $is_empty ? '✔' : '❗'; } protected function isEmpty(array $values): bool { return empty($values); } } class TodoGenerator { /** @var Storage */ protected $storage; /** @var Output */ protected $output; protected $basePath; public function __construct(string $basePath, Storage $storage, Output $output) { $this->storage = $storage; $this->output = $output; $this->basePath = $basePath; $this->load(); } /** * Returns object. * * @param string $basePath base path * * @return TodoGenerator */ public static function make(string $basePath): self { $storage = new Storage(); $output = new Output(); return new self($basePath, $storage, $output); } /** * Save todo list. * * @param string $path */ public function save(string $path): void { $this->storage->store($path, $this->output->get()); } /** * Compare translations and generate file. */ private function load(): void { // Get English version $english = $this->getTranslations('en'); $languages = $this->getLanguages(); $this->compareTranslations($languages, $english); } /** * Returns array of translations by language. * * @param string $language language code * @param string $directory directory * * @return array */ private function getTranslations(string $language, string $directory = __DIR__): array { return [ 'json' => $this->getJsonContent($language, $directory), 'auth' => $this->getContent($language, $directory, 'auth.php'), 'pagination' => $this->getContent($language, $directory, 'pagination.php'), 'passwords' => $this->getContent($language, $directory, 'passwords.php'), 'validation' => $this->getContent($language, $directory, 'validation.php'), 'validation-inline' => $this->getContent($language, $directory, 'validation-inline.php'), ]; } private function getJsonPath(string $language, string $directory): string { $directoryJson = ('en' === $language) ? '/en/' : '/../json/'; return $directory . $directoryJson . $language . '.json'; } private function getJsonContent(string $language, string $directory): ?array { $path = $this->getJsonPath($language, $directory); return $this->storage->getDecodedJson($path); } private function getContent(string $language, string $directory, string $filename) { return $this->storage->load( implode(DIRECTORY_SEPARATOR, [$directory, $language, $filename]) ); } /** * Returns list of languages. * * @return array */ private function getLanguages(): array { $directories = $this->storage->directories($this->basePath); $result = []; foreach ($directories as $directory) { if (! $directory->isDot()) { array_push($result, $directory->getFilename()); } } sort($result); return array_filter($result); } /** * Compare translations. * * @param array $default language by default * @param array $languages others languages */ private function compareTranslations(array $languages, array $default) { array_map(function ($language) use ($default) { $this->output->add($language); $current = $this->getTranslations($language, $this->basePath); foreach ($default as $key => $values) { array_map(function ($key2) use ($key, $current, $language, $default) { if (in_array($key2, ['custom', 'attributes'], true)) { return; } if (! isset($current[$key][$key2])) { $this->output->add( $language, " * {$key} : {$key2} : not present" ); } elseif ($current[$key][$key2] === $default[$key][$key2]) { $this->output->add( $language, " * {$key} : {$key2}" ); } }, array_keys($values)); } }, $languages); } } TodoGenerator::make(__DIR__ . '/../src') ->save(__DIR__ . '/../todo.md');
1
7,895
Duplicate call to the method. Better to put in a variable.
Laravel-Lang-lang
php
@@ -1023,8 +1023,9 @@ type Prefetcher interface { // PrefetchAfterBlockRetrieved allows the prefetcher to trigger prefetches // after a block has been retrieved. Whichever component is responsible for // retrieving blocks will call this method once it's done retrieving a - // block. - PrefetchAfterBlockRetrieved(b Block, kmd KeyMetadata, priority int, + // block. It caches if it has triggered a prefetch and returns that. + PrefetchAfterBlockRetrieved(b Block, blockPtr BlockPointer, + kmd KeyMetadata, priority int, lifetime BlockCacheLifetime, hasPrefetched bool) // Shutdown shuts down the prefetcher idempotently. Future calls to // the various Prefetch* methods will return io.EOF. The returned channel
1
// Copyright 2016 Keybase Inc. All rights reserved. // Use of this source code is governed by a BSD // license that can be found in the LICENSE file. package libkbfs import ( "time" "github.com/keybase/client/go/libkb" "github.com/keybase/client/go/logger" "github.com/keybase/client/go/protocol/keybase1" "github.com/keybase/kbfs/kbfsblock" "github.com/keybase/kbfs/kbfscodec" "github.com/keybase/kbfs/kbfscrypto" "github.com/keybase/kbfs/tlf" metrics "github.com/rcrowley/go-metrics" "golang.org/x/net/context" ) type dataVersioner interface { // DataVersion returns the data version for this block DataVersion() DataVer } type logMaker interface { MakeLogger(module string) logger.Logger } type blockCacher interface { BlockCache() BlockCache } // Block just needs to be (de)serialized using msgpack type Block interface { dataVersioner // GetEncodedSize returns the encoded size of this block, but only // if it has been previously set; otherwise it returns 0. GetEncodedSize() uint32 // SetEncodedSize sets the encoded size of this block, locally // caching it. The encoded size is not serialized. SetEncodedSize(size uint32) // NewEmpty returns a new block of the same type as this block NewEmpty() Block // Set sets this block to the same value as the passed-in block Set(other Block, codec kbfscodec.Codec) } // NodeID is a unique but transient ID for a Node. That is, two Node // objects in memory at the same time represent the same file or // directory if and only if their NodeIDs are equal (by pointer). type NodeID interface { // ParentID returns the NodeID of the directory containing the // pointed-to file or directory, or nil if none exists. ParentID() NodeID } // Node represents a direct pointer to a file or directory in KBFS. // It is somewhat like an inode in a regular file system. Users of // KBFS can use Node as a handle when accessing files or directories // they have previously looked up. type Node interface { // GetID returns the ID of this Node. This should be used as a // map key instead of the Node itself. GetID() NodeID // GetFolderBranch returns the folder ID and branch for this Node. GetFolderBranch() FolderBranch // GetBasename returns the current basename of the node, or "" // if the node has been unlinked. GetBasename() string } // KBFSOps handles all file system operations. Expands all indirect // pointers. Operations that modify the server data change all the // block IDs along the path, and so must return a path with the new // BlockIds so the caller can update their references. // // KBFSOps implementations must guarantee goroutine-safety of calls on // a per-top-level-folder basis. // // There are two types of operations that could block: // * remote-sync operations, that need to synchronously update the // MD for the corresponding top-level folder. When these // operations return successfully, they will have guaranteed to // have successfully written the modification to the KBFS servers. // * remote-access operations, that don't sync any modifications to KBFS // servers, but may block on reading data from the servers. // // KBFSOps implementations are supposed to give git-like consistency // semantics for modification operations; they will be visible to // other clients immediately after the remote-sync operations succeed, // if and only if there was no other intervening modification to the // same folder. If not, the change will be sync'd to the server in a // special per-device "unmerged" area before the operation succeeds. // In this case, the modification will not be visible to other clients // until the KBFS code on this device performs automatic conflict // resolution in the background. // // All methods take a Context (see https://blog.golang.org/context), // and if that context is cancelled during the operation, KBFSOps will // abort any blocking calls and return ctx.Err(). Any notifications // resulting from an operation will also include this ctx (or a // Context derived from it), allowing the caller to determine whether // the notification is a result of their own action or an external // action. type KBFSOps interface { // GetFavorites returns the logged-in user's list of favorite // top-level folders. This is a remote-access operation. GetFavorites(ctx context.Context) ([]Favorite, error) // RefreshCachedFavorites tells the instances to forget any cached // favorites list and fetch a new list from the server. The // effects are asychronous; if there's an error refreshing the // favorites, the cached favorites will become empty. RefreshCachedFavorites(ctx context.Context) // AddFavorite adds the favorite to both the server and // the local cache. AddFavorite(ctx context.Context, fav Favorite) error // DeleteFavorite deletes the favorite from both the server and // the local cache. Idempotent, so it succeeds even if the folder // isn't favorited. DeleteFavorite(ctx context.Context, fav Favorite) error // GetTLFCryptKeys gets crypt key of all generations as well as // TLF ID for tlfHandle. The returned keys (the keys slice) are ordered by // generation, starting with the key for FirstValidKeyGen. GetTLFCryptKeys(ctx context.Context, tlfHandle *TlfHandle) ( keys []kbfscrypto.TLFCryptKey, id tlf.ID, err error) // GetTLFID gets the TLF ID for tlfHandle. GetTLFID(ctx context.Context, tlfHandle *TlfHandle) (tlf.ID, error) // GetOrCreateRootNode returns the root node and root entry // info associated with the given TLF handle and branch, if // the logged-in user has read permissions to the top-level // folder. It creates the folder if one doesn't exist yet (and // branch == MasterBranch), and the logged-in user has write // permissions to the top-level folder. This is a // remote-access operation. GetOrCreateRootNode( ctx context.Context, h *TlfHandle, branch BranchName) ( node Node, ei EntryInfo, err error) // GetRootNode is like GetOrCreateRootNode but if the root node // does not exist it will return a nil Node and not create it. GetRootNode( ctx context.Context, h *TlfHandle, branch BranchName) ( node Node, ei EntryInfo, err error) // GetDirChildren returns a map of children in the directory, // mapped to their EntryInfo, if the logged-in user has read // permission for the top-level folder. This is a remote-access // operation. GetDirChildren(ctx context.Context, dir Node) (map[string]EntryInfo, error) // Lookup returns the Node and entry info associated with a // given name in a directory, if the logged-in user has read // permissions to the top-level folder. The returned Node is nil // if the name is a symlink. This is a remote-access operation. Lookup(ctx context.Context, dir Node, name string) (Node, EntryInfo, error) // Stat returns the entry info associated with a // given Node, if the logged-in user has read permissions to the // top-level folder. This is a remote-access operation. Stat(ctx context.Context, node Node) (EntryInfo, error) // CreateDir creates a new subdirectory under the given node, if // the logged-in user has write permission to the top-level // folder. Returns the new Node for the created subdirectory, and // its new entry info. This is a remote-sync operation. CreateDir(ctx context.Context, dir Node, name string) ( Node, EntryInfo, error) // CreateFile creates a new file under the given node, if the // logged-in user has write permission to the top-level folder. // Returns the new Node for the created file, and its new // entry info. excl (when implemented) specifies whether this is an exclusive // create. Semantically setting excl to WithExcl is like O_CREAT|O_EXCL in a // Unix open() call. // // This is a remote-sync operation. CreateFile(ctx context.Context, dir Node, name string, isExec bool, excl Excl) ( Node, EntryInfo, error) // CreateLink creates a new symlink under the given node, if the // logged-in user has write permission to the top-level folder. // Returns the new entry info for the created symlink. This // is a remote-sync operation. CreateLink(ctx context.Context, dir Node, fromName string, toPath string) ( EntryInfo, error) // RemoveDir removes the subdirectory represented by the given // node, if the logged-in user has write permission to the // top-level folder. Will return an error if the subdirectory is // not empty. This is a remote-sync operation. RemoveDir(ctx context.Context, dir Node, dirName string) error // RemoveEntry removes the directory entry represented by the // given node, if the logged-in user has write permission to the // top-level folder. This is a remote-sync operation. RemoveEntry(ctx context.Context, dir Node, name string) error // Rename performs an atomic rename operation with a given // top-level folder if the logged-in user has write permission to // that folder, and will return an error if nodes from different // folders are passed in. Also returns an error if the new name // already has an entry corresponding to an existing directory // (only non-dir types may be renamed over). This is a // remote-sync operation. Rename(ctx context.Context, oldParent Node, oldName string, newParent Node, newName string) error // Read fills in the given buffer with data from the file at the // given node starting at the given offset, if the logged-in user // has read permission to the top-level folder. The read data // reflects any outstanding writes and truncates to that file that // have been written through this KBFSOps object, even if those // writes have not yet been sync'd. There is no guarantee that // Read returns all of the requested data; it will return the // number of bytes that it wrote to the dest buffer. Reads on an // unlinked file may or may not succeed, depending on whether or // not the data has been cached locally. If (0, nil) is returned, // that means EOF has been reached. This is a remote-access // operation. Read(ctx context.Context, file Node, dest []byte, off int64) (int64, error) // Write modifies the file at the given node, by writing the given // buffer at the given offset within the file, if the logged-in // user has write permission to the top-level folder. It // overwrites any data already there, and extends the file size as // necessary to accomodate the new data. It guarantees to write // the entire buffer in one operation. Writes on an unlinked file // may or may not succeed as no-ops, depending on whether or not // the necessary blocks have been locally cached. This is a // remote-access operation. Write(ctx context.Context, file Node, data []byte, off int64) error // Truncate modifies the file at the given node, by either // shrinking or extending its size to match the given size, if the // logged-in user has write permission to the top-level folder. // If extending the file, it pads the new data with 0s. Truncates // on an unlinked file may or may not succeed as no-ops, depending // on whether or not the necessary blocks have been locally // cached. This is a remote-access operation. Truncate(ctx context.Context, file Node, size uint64) error // SetEx turns on or off the executable bit on the file // represented by a given node, if the logged-in user has write // permissions to the top-level folder. This is a remote-sync // operation. SetEx(ctx context.Context, file Node, ex bool) error // SetMtime sets the modification time on the file represented by // a given node, if the logged-in user has write permissions to // the top-level folder. If mtime is nil, it is a noop. This is // a remote-sync operation. SetMtime(ctx context.Context, file Node, mtime *time.Time) error // Sync flushes all outstanding writes and truncates for the given // file to the KBFS servers, if the logged-in user has write // permissions to the top-level folder. If done through a file // system interface, this may include modifications done via // multiple file handles. This is a remote-sync operation. Sync(ctx context.Context, file Node) error // FolderStatus returns the status of a particular folder/branch, along // with a channel that will be closed when the status has been // updated (to eliminate the need for polling this method). FolderStatus(ctx context.Context, folderBranch FolderBranch) ( FolderBranchStatus, <-chan StatusUpdate, error) // Status returns the status of KBFS, along with a channel that will be // closed when the status has been updated (to eliminate the need for // polling this method). KBFSStatus can be non-empty even if there is an // error. Status(ctx context.Context) ( KBFSStatus, <-chan StatusUpdate, error) // UnstageForTesting clears out this device's staged state, if // any, and fast-forwards to the current head of this // folder-branch. UnstageForTesting(ctx context.Context, folderBranch FolderBranch) error // Rekey rekeys this folder. Rekey(ctx context.Context, id tlf.ID) error // SyncFromServerForTesting blocks until the local client has // contacted the server and guaranteed that all known updates // for the given top-level folder have been applied locally // (and notifications sent out to any observers). It returns // an error if this folder-branch is currently unmerged or // dirty locally. SyncFromServerForTesting(ctx context.Context, folderBranch FolderBranch) error // GetUpdateHistory returns a complete history of all the merged // updates of the given folder, in a data structure that's // suitable for encoding directly into JSON. This is an expensive // operation, and should only be used for ocassional debugging. // Note that the history does not include any unmerged changes or // outstanding writes from the local device. GetUpdateHistory(ctx context.Context, folderBranch FolderBranch) ( history TLFUpdateHistory, err error) // GetEditHistory returns a clustered list of the most recent file // edits by each of the valid writers of the given folder. users // looking to get updates to this list can register as an observer // for the folder. GetEditHistory(ctx context.Context, folderBranch FolderBranch) ( edits TlfWriterEdits, err error) // GetNodeMetadata gets metadata associated with a Node. GetNodeMetadata(ctx context.Context, node Node) (NodeMetadata, error) // Shutdown is called to clean up any resources associated with // this KBFSOps instance. Shutdown(ctx context.Context) error // PushConnectionStatusChange updates the status of a service for // human readable connection status tracking. PushConnectionStatusChange(service string, newStatus error) // PushStatusChange causes Status listeners to be notified via closing // the status channel. PushStatusChange() } // KeybaseService is an interface for communicating with the keybase // service. type KeybaseService interface { // Resolve, given an assertion, resolves it to a username/UID // pair. The username <-> UID mapping is trusted and // immutable, so it can be cached. If the assertion is just // the username or a UID assertion, then the resolution can // also be trusted. If the returned pair is equal to that of // the current session, then it can also be // trusted. Otherwise, Identify() needs to be called on the // assertion before the assertion -> (username, UID) mapping // can be trusted. Resolve(ctx context.Context, assertion string) ( libkb.NormalizedUsername, keybase1.UID, error) // Identify, given an assertion, returns a UserInfo struct // with the user that matches that assertion, or an error // otherwise. The reason string is displayed on any tracker // popups spawned. Identify(ctx context.Context, assertion, reason string) (UserInfo, error) // LoadUserPlusKeys returns a UserInfo struct for a // user with the specified UID. // If you have the UID for a user and don't require Identify to // validate an assertion or the identity of a user, use this to // get UserInfo structs as it is much cheaper than Identify. LoadUserPlusKeys(ctx context.Context, uid keybase1.UID) (UserInfo, error) // LoadUnverifiedKeys returns a list of unverified public keys. They are the union // of all known public keys associated with the account and the currently verified // keys currently part of the user's sigchain. LoadUnverifiedKeys(ctx context.Context, uid keybase1.UID) ( []keybase1.PublicKey, error) // CurrentSession returns a SessionInfo struct with all the // information for the current session, or an error otherwise. CurrentSession(ctx context.Context, sessionID int) (SessionInfo, error) // FavoriteAdd adds the given folder to the list of favorites. FavoriteAdd(ctx context.Context, folder keybase1.Folder) error // FavoriteAdd removes the given folder from the list of // favorites. FavoriteDelete(ctx context.Context, folder keybase1.Folder) error // FavoriteList returns the current list of favorites. FavoriteList(ctx context.Context, sessionID int) ([]keybase1.Folder, error) // Notify sends a filesystem notification. Notify(ctx context.Context, notification *keybase1.FSNotification) error // NotifySyncStatus sends a sync status notification. NotifySyncStatus(ctx context.Context, status *keybase1.FSPathSyncStatus) error // FlushUserFromLocalCache instructs this layer to clear any // KBFS-side, locally-cached information about the given user. // This does NOT involve communication with the daemon, this is // just to force future calls loading this user to fall through to // the daemon itself, rather than being served from the cache. FlushUserFromLocalCache(ctx context.Context, uid keybase1.UID) // FlushUserUnverifiedKeysFromLocalCache instructs this layer to clear any // KBFS-side, locally-cached unverified keys for the given user. FlushUserUnverifiedKeysFromLocalCache(ctx context.Context, uid keybase1.UID) // TODO: Add CryptoClient methods, too. // EstablishMountDir asks the service for the current mount path // and sets it if not established. EstablishMountDir(ctx context.Context) (string, error) // Shutdown frees any resources associated with this // instance. No other methods may be called after this is // called. Shutdown() } // KeybaseServiceCn defines methods needed to construct KeybaseService // and Crypto implementations. type KeybaseServiceCn interface { NewKeybaseService(config Config, params InitParams, ctx Context, log logger.Logger) (KeybaseService, error) NewCrypto(config Config, params InitParams, ctx Context, log logger.Logger) (Crypto, error) } type resolver interface { // Resolve, given an assertion, resolves it to a username/UID // pair. The username <-> UID mapping is trusted and // immutable, so it can be cached. If the assertion is just // the username or a UID assertion, then the resolution can // also be trusted. If the returned pair is equal to that of // the current session, then it can also be // trusted. Otherwise, Identify() needs to be called on the // assertion before the assertion -> (username, UID) mapping // can be trusted. Resolve(ctx context.Context, assertion string) ( libkb.NormalizedUsername, keybase1.UID, error) } type identifier interface { // Identify resolves an assertion (which could also be a // username) to a UserInfo struct, spawning tracker popups if // necessary. The reason string is displayed on any tracker // popups spawned. Identify(ctx context.Context, assertion, reason string) (UserInfo, error) } type normalizedUsernameGetter interface { // GetNormalizedUsername returns the normalized username // corresponding to the given UID. GetNormalizedUsername(ctx context.Context, uid keybase1.UID) (libkb.NormalizedUsername, error) } type currentInfoGetter interface { // GetCurrentToken gets the current keybase session token. GetCurrentToken(ctx context.Context) (string, error) // GetCurrentUserInfo gets the name and UID of the current // logged-in user. GetCurrentUserInfo(ctx context.Context) ( libkb.NormalizedUsername, keybase1.UID, error) // GetCurrentCryptPublicKey gets the crypt public key for the // currently-active device. GetCurrentCryptPublicKey(ctx context.Context) ( kbfscrypto.CryptPublicKey, error) // GetCurrentVerifyingKey gets the public key used for signing for the // currently-active device. GetCurrentVerifyingKey(ctx context.Context) ( kbfscrypto.VerifyingKey, error) } // KBPKI interacts with the Keybase daemon to fetch user info. type KBPKI interface { currentInfoGetter resolver identifier normalizedUsernameGetter // HasVerifyingKey returns nil if the given user has the given // VerifyingKey, and an error otherwise. HasVerifyingKey(ctx context.Context, uid keybase1.UID, verifyingKey kbfscrypto.VerifyingKey, atServerTime time.Time) error // HasUnverifiedVerifyingKey returns nil if the given user has the given // unverified VerifyingKey, and an error otherwise. Note that any match // is with a key not verified to be currently connected to the user via // their sigchain. This is currently only used to verify finalized or // reset TLFs. Further note that unverified keys is a super set of // verified keys. HasUnverifiedVerifyingKey(ctx context.Context, uid keybase1.UID, verifyingKey kbfscrypto.VerifyingKey) error // GetCryptPublicKeys gets all of a user's crypt public keys (including // paper keys). GetCryptPublicKeys(ctx context.Context, uid keybase1.UID) ( []kbfscrypto.CryptPublicKey, error) // TODO: Split the methods below off into a separate // FavoriteOps interface. // FavoriteAdd adds folder to the list of the logged in user's // favorite folders. It is idempotent. FavoriteAdd(ctx context.Context, folder keybase1.Folder) error // FavoriteDelete deletes folder from the list of the logged in user's // favorite folders. It is idempotent. FavoriteDelete(ctx context.Context, folder keybase1.Folder) error // FavoriteList returns the list of all favorite folders for // the logged in user. FavoriteList(ctx context.Context) ([]keybase1.Folder, error) // Notify sends a filesystem notification. Notify(ctx context.Context, notification *keybase1.FSNotification) error } // KeyMetadata is an interface for something that holds key // information. This is usually implemented by RootMetadata. type KeyMetadata interface { // TlfID returns the ID of the TLF for which this object holds // key info. TlfID() tlf.ID // LatestKeyGeneration returns the most recent key generation // with key data in this object, or PublicKeyGen if this TLF // is public. LatestKeyGeneration() KeyGen // GetTlfHandle returns the handle for the TLF. It must not // return nil. // // TODO: Remove the need for this function in this interface, // so that BareRootMetadata can implement this interface // fully. GetTlfHandle() *TlfHandle // HasKeyForUser returns whether or not the given user has // keys for at least one device. Returns an error if the TLF // is public. HasKeyForUser(user keybase1.UID) (bool, error) // GetTLFCryptKeyParams returns all the necessary info to // construct the TLF crypt key for the given key generation, // user, and device (identified by its crypt public key), or // false if not found. This returns an error if the TLF is // public. GetTLFCryptKeyParams( keyGen KeyGen, user keybase1.UID, key kbfscrypto.CryptPublicKey) ( kbfscrypto.TLFEphemeralPublicKey, EncryptedTLFCryptKeyClientHalf, TLFCryptKeyServerHalfID, bool, error) // StoresHistoricTLFCryptKeys returns whether or not history keys are // symmetrically encrypted; if not, they're encrypted per-device. StoresHistoricTLFCryptKeys() bool // GetHistoricTLFCryptKey attempts to symmetrically decrypt the key at the given // generation using the current generation's TLFCryptKey. GetHistoricTLFCryptKey(c cryptoPure, keyGen KeyGen, currentKey kbfscrypto.TLFCryptKey) ( kbfscrypto.TLFCryptKey, error) } type encryptionKeyGetter interface { // GetTLFCryptKeyForEncryption gets the crypt key to use for // encryption (i.e., with the latest key generation) for the // TLF with the given metadata. GetTLFCryptKeyForEncryption(ctx context.Context, kmd KeyMetadata) ( kbfscrypto.TLFCryptKey, error) } type mdDecryptionKeyGetter interface { // GetTLFCryptKeyForMDDecryption gets the crypt key to use for the // TLF with the given metadata to decrypt the private portion of // the metadata. It finds the appropriate key from mdWithKeys // (which in most cases is the same as mdToDecrypt) if it's not // already cached. GetTLFCryptKeyForMDDecryption(ctx context.Context, kmdToDecrypt, kmdWithKeys KeyMetadata) ( kbfscrypto.TLFCryptKey, error) } type blockDecryptionKeyGetter interface { // GetTLFCryptKeyForBlockDecryption gets the crypt key to use // for the TLF with the given metadata to decrypt the block // pointed to by the given pointer. GetTLFCryptKeyForBlockDecryption(ctx context.Context, kmd KeyMetadata, blockPtr BlockPointer) (kbfscrypto.TLFCryptKey, error) } type blockKeyGetter interface { encryptionKeyGetter blockDecryptionKeyGetter } // KeyManager fetches and constructs the keys needed for KBFS file // operations. type KeyManager interface { blockKeyGetter mdDecryptionKeyGetter // GetTLFCryptKeyOfAllGenerations gets the crypt keys of all generations // for current devices. keys contains crypt keys from all generations, in // order, starting from FirstValidKeyGen. GetTLFCryptKeyOfAllGenerations(ctx context.Context, kmd KeyMetadata) ( keys []kbfscrypto.TLFCryptKey, err error) // Rekey checks the given MD object, if it is a private TLF, // against the current set of device keys for all valid // readers and writers. If there are any new devices, it // updates all existing key generations to include the new // devices. If there are devices that have been removed, it // creates a new epoch of keys for the TLF. If there was an // error, or the RootMetadata wasn't changed, it returns false. // Otherwise, it returns true. If a new key generation is // added the second return value points to this new key. This // is to allow for caching of the TLF crypt key only after a // successful merged write of the metadata. Otherwise we could // prematurely pollute the key cache. // // If the given MD object is a public TLF, it simply updates // the TLF's handle with any newly-resolved writers. // // If promptPaper is set, prompts for any unlocked paper keys. // promptPaper shouldn't be set if md is for a public TLF. Rekey(ctx context.Context, md *RootMetadata, promptPaper bool) ( bool, *kbfscrypto.TLFCryptKey, error) } // Reporter exports events (asynchronously) to any number of sinks type Reporter interface { // ReportErr records that a given error happened. ReportErr(ctx context.Context, tlfName CanonicalTlfName, public bool, mode ErrorModeType, err error) // AllKnownErrors returns all errors known to this Reporter. AllKnownErrors() []ReportedError // Notify sends the given notification to any sink. Notify(ctx context.Context, notification *keybase1.FSNotification) // NotifySyncStatus sends the given path sync status to any sink. NotifySyncStatus(ctx context.Context, status *keybase1.FSPathSyncStatus) // Shutdown frees any resources allocated by a Reporter. Shutdown() } // MDCache gets and puts plaintext top-level metadata into the cache. type MDCache interface { // Get gets the metadata object associated with the given TLF ID, // revision number, and branch ID (NullBranchID for merged MD). Get(tlf tlf.ID, rev MetadataRevision, bid BranchID) (ImmutableRootMetadata, error) // Put stores the metadata object. Put(md ImmutableRootMetadata) error // Delete removes the given metadata object from the cache if it exists. Delete(tlf tlf.ID, rev MetadataRevision, bid BranchID) // Replace replaces the entry matching the md under the old branch // ID with the new one. If the old entry doesn't exist, this is // equivalent to a Put. Replace(newRmd ImmutableRootMetadata, oldBID BranchID) error } // KeyCache handles caching for both TLFCryptKeys and BlockCryptKeys. type KeyCache interface { // GetTLFCryptKey gets the crypt key for the given TLF. GetTLFCryptKey(tlf.ID, KeyGen) (kbfscrypto.TLFCryptKey, error) // PutTLFCryptKey stores the crypt key for the given TLF. PutTLFCryptKey(tlf.ID, KeyGen, kbfscrypto.TLFCryptKey) error } // BlockCacheLifetime denotes the lifetime of an entry in BlockCache. type BlockCacheLifetime int const ( // NoCacheEntry means that the entry will not be cached. NoCacheEntry BlockCacheLifetime = iota // TransientEntry means that the cache entry may be evicted at // any time. TransientEntry // PermanentEntry means that the cache entry must remain until // explicitly removed from the cache. PermanentEntry ) // BlockCacheSimple gets and puts plaintext dir blocks and file blocks into // a cache. These blocks are immutable and identified by their // content hash. type BlockCacheSimple interface { // Get gets the block associated with the given block ID. Get(ptr BlockPointer) (Block, error) // Put stores the final (content-addressable) block associated // with the given block ID. If lifetime is TransientEntry, // then it is assumed that the block exists on the server and // the entry may be evicted from the cache at any time. If // lifetime is PermanentEntry, then it is assumed that the // block doesn't exist on the server and must remain in the // cache until explicitly removed. As an intermediary state, // as when a block is being sent to the server, the block may // be put into the cache both with TransientEntry and // PermanentEntry -- these are two separate entries. This is // fine, since the block should be the same. Put(ptr BlockPointer, tlf tlf.ID, block Block, lifetime BlockCacheLifetime) error } // BlockCache specifies the interface of BlockCacheSimple, and also more // advanced and internal methods. type BlockCache interface { BlockCacheSimple // CheckForKnownPtr sees whether this cache has a transient // entry for the given file block, which must be a direct file // block containing data). Returns the full BlockPointer // associated with that ID, including key and data versions. // If no ID is known, return an uninitialized BlockPointer and // a nil error. CheckForKnownPtr(tlf tlf.ID, block *FileBlock) (BlockPointer, error) // DeleteTransient removes the transient entry for the given // pointer from the cache, as well as any cached IDs so the block // won't be reused. DeleteTransient(ptr BlockPointer, tlf tlf.ID) error // Delete removes the permanent entry for the non-dirty block // associated with the given block ID from the cache. No // error is returned if no block exists for the given ID. DeletePermanent(id kbfsblock.ID) error // DeleteKnownPtr removes the cached ID for the given file // block. It does not remove the block itself. DeleteKnownPtr(tlf tlf.ID, block *FileBlock) error // GetWithPrefetch retrieves a block from the cache, along with whether or // not it has triggered a prefetch. GetWithPrefetch(ptr BlockPointer) ( block Block, hasPrefetched bool, err error) // PutWithPrefetch puts a block into the cache, along with whether or not // it has triggered a prefetch. PutWithPrefetch(ptr BlockPointer, tlf tlf.ID, block Block, lifetime BlockCacheLifetime, hasPrefetched bool) error // SetCleanBytesCapacity atomically sets clean bytes capacity for block // cache. SetCleanBytesCapacity(capacity uint64) // GetCleanBytesCapacity atomically gets clean bytes capacity for block // cache. GetCleanBytesCapacity() (capacity uint64) } // DirtyPermChan is a channel that gets closed when the holder has // permission to write. We are forced to define it as a type due to a // bug in mockgen that can't handle return values with a chan // struct{}. type DirtyPermChan <-chan struct{} // DirtyBlockCache gets and puts plaintext dir blocks and file blocks // into a cache, which have been modified by the application and not // yet committed on the KBFS servers. They are identified by a // (potentially random) ID that may not have any relationship with // their context, along with a Branch in case the same TLF is being // modified via multiple branches. Dirty blocks are never evicted, // they must be deleted explicitly. type DirtyBlockCache interface { // Get gets the block associated with the given block ID. Returns // the dirty block for the given ID, if one exists. Get(tlfID tlf.ID, ptr BlockPointer, branch BranchName) (Block, error) // Put stores a dirty block currently identified by the // given block pointer and branch name. Put(tlfID tlf.ID, ptr BlockPointer, branch BranchName, block Block) error // Delete removes the dirty block associated with the given block // pointer and branch from the cache. No error is returned if no // block exists for the given ID. Delete(tlfID tlf.ID, ptr BlockPointer, branch BranchName) error // IsDirty states whether or not the block associated with the // given block pointer and branch name is dirty in this cache. IsDirty(tlfID tlf.ID, ptr BlockPointer, branch BranchName) bool // IsAnyDirty returns whether there are any dirty blocks in the // cache. tlfID may be ignored. IsAnyDirty(tlfID tlf.ID) bool // RequestPermissionToDirty is called whenever a user wants to // write data to a file. The caller provides an estimated number // of bytes that will become dirty -- this is difficult to know // exactly without pre-fetching all the blocks involved, but in // practice we can just use the number of bytes sent in via the // Write. It returns a channel that blocks until the cache is // ready to receive more dirty data, at which point the channel is // closed. The user must call // `UpdateUnsyncedBytes(-estimatedDirtyBytes)` once it has // completed its write and called `UpdateUnsyncedBytes` for all // the exact dirty block sizes. RequestPermissionToDirty(ctx context.Context, tlfID tlf.ID, estimatedDirtyBytes int64) (DirtyPermChan, error) // UpdateUnsyncedBytes is called by a user, who has already been // granted permission to write, with the delta in block sizes that // were dirtied as part of the write. So for example, if a // newly-dirtied block of 20 bytes was extended by 5 bytes, they // should send 25. If on the next write (before any syncs), bytes // 10-15 of that same block were overwritten, they should send 0 // over the channel because there were no new bytes. If an // already-dirtied block is truncated, or if previously requested // bytes have now been updated more accurately in previous // requests, newUnsyncedBytes may be negative. wasSyncing should // be true if `BlockSyncStarted` has already been called for this // block. UpdateUnsyncedBytes(tlfID tlf.ID, newUnsyncedBytes int64, wasSyncing bool) // UpdateSyncingBytes is called when a particular block has // started syncing, or with a negative number when a block is no // longer syncing due to an error (and BlockSyncFinished will // never be called). UpdateSyncingBytes(tlfID tlf.ID, size int64) // BlockSyncFinished is called when a particular block has // finished syncing, though the overall sync might not yet be // complete. This lets the cache know it might be able to grant // more permission to writers. BlockSyncFinished(tlfID tlf.ID, size int64) // SyncFinished is called when a complete sync has completed and // its dirty blocks have been removed from the cache. This lets // the cache know it might be able to grant more permission to // writers. SyncFinished(tlfID tlf.ID, size int64) // ShouldForceSync returns true if the sync buffer is full enough // to force all callers to sync their data immediately. ShouldForceSync(tlfID tlf.ID) bool // Shutdown frees any resources associated with this instance. It // returns an error if there are any unsynced blocks. Shutdown() error } // cryptoPure contains all methods of Crypto that don't depend on // implicit state, i.e. they're pure functions of the input. type cryptoPure interface { // MakeRandomTlfID generates a dir ID using a CSPRNG. MakeRandomTlfID(isPublic bool) (tlf.ID, error) // MakeRandomBranchID generates a per-device branch ID using a // CSPRNG. It will not return LocalSquashBranchID or // NullBranchID. MakeRandomBranchID() (BranchID, error) // MakeMdID computes the MD ID of a RootMetadata object. // TODO: This should move to BareRootMetadata. Note though, that some mock tests // rely on it being part of the config and crypto_measured.go uses it to keep // statistics on time spent hashing. MakeMdID(md BareRootMetadata) (MdID, error) // MakeMerkleHash computes the hash of a RootMetadataSigned object // for inclusion into the KBFS Merkle tree. MakeMerkleHash(md *RootMetadataSigned) (MerkleHash, error) // MakeTemporaryBlockID generates a temporary block ID using a // CSPRNG. This is used for indirect blocks before they're // committed to the server. MakeTemporaryBlockID() (kbfsblock.ID, error) // MakeRefNonce generates a block reference nonce using a // CSPRNG. This is used for distinguishing different references to // the same BlockID. MakeBlockRefNonce() (kbfsblock.RefNonce, error) // MakeRandomTLFEphemeralKeys generates ephemeral keys using a // CSPRNG for a TLF. These keys can then be used to key/rekey // the TLF. MakeRandomTLFEphemeralKeys() (kbfscrypto.TLFEphemeralPublicKey, kbfscrypto.TLFEphemeralPrivateKey, error) // MakeRandomTLFKeys generates keys using a CSPRNG for a // single key generation of a TLF. MakeRandomTLFKeys() (kbfscrypto.TLFPublicKey, kbfscrypto.TLFPrivateKey, kbfscrypto.TLFCryptKey, error) // MakeRandomTLFCryptKeyServerHalf generates the server-side of a // top-level folder crypt key. MakeRandomTLFCryptKeyServerHalf() ( kbfscrypto.TLFCryptKeyServerHalf, error) // MakeRandomBlockCryptKeyServerHalf generates the server-side of // a block crypt key. MakeRandomBlockCryptKeyServerHalf() ( kbfscrypto.BlockCryptKeyServerHalf, error) // EncryptTLFCryptKeyClientHalf encrypts a TLFCryptKeyClientHalf // using both a TLF's ephemeral private key and a device pubkey. EncryptTLFCryptKeyClientHalf( privateKey kbfscrypto.TLFEphemeralPrivateKey, publicKey kbfscrypto.CryptPublicKey, clientHalf kbfscrypto.TLFCryptKeyClientHalf) ( EncryptedTLFCryptKeyClientHalf, error) // EncryptPrivateMetadata encrypts a PrivateMetadata object. EncryptPrivateMetadata( pmd PrivateMetadata, key kbfscrypto.TLFCryptKey) ( EncryptedPrivateMetadata, error) // DecryptPrivateMetadata decrypts a PrivateMetadata object. DecryptPrivateMetadata( encryptedPMD EncryptedPrivateMetadata, key kbfscrypto.TLFCryptKey) (PrivateMetadata, error) // EncryptBlocks encrypts a block. plainSize is the size of the encoded // block; EncryptBlock() must guarantee that plainSize <= // len(encryptedBlock). EncryptBlock(block Block, key kbfscrypto.BlockCryptKey) ( plainSize int, encryptedBlock EncryptedBlock, err error) // DecryptBlock decrypts a block. Similar to EncryptBlock(), // DecryptBlock() must guarantee that (size of the decrypted // block) <= len(encryptedBlock). DecryptBlock(encryptedBlock EncryptedBlock, key kbfscrypto.BlockCryptKey, block Block) error // GetTLFCryptKeyServerHalfID creates a unique ID for this particular // kbfscrypto.TLFCryptKeyServerHalf. GetTLFCryptKeyServerHalfID( user keybase1.UID, devicePubKey kbfscrypto.CryptPublicKey, serverHalf kbfscrypto.TLFCryptKeyServerHalf) ( TLFCryptKeyServerHalfID, error) // VerifyTLFCryptKeyServerHalfID verifies the ID is the proper HMAC result. VerifyTLFCryptKeyServerHalfID(serverHalfID TLFCryptKeyServerHalfID, user keybase1.UID, deviceKID keybase1.KID, serverHalf kbfscrypto.TLFCryptKeyServerHalf) error // EncryptMerkleLeaf encrypts a Merkle leaf node with the TLFPublicKey. EncryptMerkleLeaf(leaf MerkleLeaf, pubKey kbfscrypto.TLFPublicKey, nonce *[24]byte, ePrivKey kbfscrypto.TLFEphemeralPrivateKey) ( EncryptedMerkleLeaf, error) // DecryptMerkleLeaf decrypts a Merkle leaf node with the TLFPrivateKey. DecryptMerkleLeaf(encryptedLeaf EncryptedMerkleLeaf, privKey kbfscrypto.TLFPrivateKey, nonce *[24]byte, ePubKey kbfscrypto.TLFEphemeralPublicKey) (*MerkleLeaf, error) // MakeTLFWriterKeyBundleID hashes a TLFWriterKeyBundleV3 to create an ID. MakeTLFWriterKeyBundleID(wkb TLFWriterKeyBundleV3) (TLFWriterKeyBundleID, error) // MakeTLFReaderKeyBundleID hashes a TLFReaderKeyBundleV3 to create an ID. MakeTLFReaderKeyBundleID(rkb TLFReaderKeyBundleV3) (TLFReaderKeyBundleID, error) // EncryptTLFCryptKeys encrypts an array of historic TLFCryptKeys. EncryptTLFCryptKeys(oldKeys []kbfscrypto.TLFCryptKey, key kbfscrypto.TLFCryptKey) (EncryptedTLFCryptKeys, error) // DecryptTLFCryptKeys decrypts an array of historic TLFCryptKeys. DecryptTLFCryptKeys( encKeys EncryptedTLFCryptKeys, key kbfscrypto.TLFCryptKey) ( []kbfscrypto.TLFCryptKey, error) } // Crypto signs, verifies, encrypts, and decrypts stuff. type Crypto interface { cryptoPure // Duplicate kbfscrypto.Signer here to work around gomock's // limitations. Sign(context.Context, []byte) (kbfscrypto.SignatureInfo, error) SignForKBFS(context.Context, []byte) (kbfscrypto.SignatureInfo, error) SignToString(context.Context, []byte) (string, error) // DecryptTLFCryptKeyClientHalf decrypts a // kbfscrypto.TLFCryptKeyClientHalf using the current device's // private key and the TLF's ephemeral public key. DecryptTLFCryptKeyClientHalf(ctx context.Context, publicKey kbfscrypto.TLFEphemeralPublicKey, encryptedClientHalf EncryptedTLFCryptKeyClientHalf) ( kbfscrypto.TLFCryptKeyClientHalf, error) // DecryptTLFCryptKeyClientHalfAny decrypts one of the // kbfscrypto.TLFCryptKeyClientHalf using the available // private keys and the ephemeral public key. If promptPaper // is true, the service will prompt the user for any unlocked // paper keys. DecryptTLFCryptKeyClientHalfAny(ctx context.Context, keys []EncryptedTLFCryptKeyClientAndEphemeral, promptPaper bool) ( kbfscrypto.TLFCryptKeyClientHalf, int, error) // Shutdown frees any resources associated with this instance. Shutdown() } // MDOps gets and puts root metadata to an MDServer. On a get, it // verifies the metadata is signed by the metadata's signing key. type MDOps interface { // GetForHandle returns the current metadata object // corresponding to the given top-level folder's handle and // merge status, if the logged-in user has read permission on // the folder. It creates the folder if one doesn't exist // yet, and the logged-in user has permission to do so. // // If there is no returned error, then the returned ID must // always be non-null. An empty ImmutableRootMetadata may be // returned, but if it is non-empty, then its ID must match // the returned ID. GetForHandle( ctx context.Context, handle *TlfHandle, mStatus MergeStatus) ( tlf.ID, ImmutableRootMetadata, error) // GetForTLF returns the current metadata object // corresponding to the given top-level folder, if the logged-in // user has read permission on the folder. GetForTLF(ctx context.Context, id tlf.ID) (ImmutableRootMetadata, error) // GetUnmergedForTLF is the same as the above but for unmerged // metadata. GetUnmergedForTLF(ctx context.Context, id tlf.ID, bid BranchID) ( ImmutableRootMetadata, error) // GetRange returns a range of metadata objects corresponding to // the passed revision numbers (inclusive). GetRange(ctx context.Context, id tlf.ID, start, stop MetadataRevision) ( []ImmutableRootMetadata, error) // GetUnmergedRange is the same as the above but for unmerged // metadata history (inclusive). GetUnmergedRange(ctx context.Context, id tlf.ID, bid BranchID, start, stop MetadataRevision) ([]ImmutableRootMetadata, error) // Put stores the metadata object for the given // top-level folder. Put(ctx context.Context, rmd *RootMetadata) (MdID, error) // PutUnmerged is the same as the above but for unmerged // metadata history. PutUnmerged(ctx context.Context, rmd *RootMetadata) (MdID, error) // PruneBranch prunes all unmerged history for the given TLF // branch. PruneBranch(ctx context.Context, id tlf.ID, bid BranchID) error // ResolveBranch prunes all unmerged history for the given TLF // branch, and also deletes any blocks in `blocksToDelete` that // are still in the local journal. It also appends the given MD // to the journal. ResolveBranch(ctx context.Context, id tlf.ID, bid BranchID, blocksToDelete []kbfsblock.ID, rmd *RootMetadata) (MdID, error) // GetLatestHandleForTLF returns the server's idea of the latest handle for the TLF, // which may not yet be reflected in the MD if the TLF hasn't been rekeyed since it // entered into a conflicting state. GetLatestHandleForTLF(ctx context.Context, id tlf.ID) ( tlf.Handle, error) } // KeyOps fetches server-side key halves from the key server. type KeyOps interface { // GetTLFCryptKeyServerHalf gets a server-side key half for a // device given the key half ID. GetTLFCryptKeyServerHalf(ctx context.Context, serverHalfID TLFCryptKeyServerHalfID, cryptPublicKey kbfscrypto.CryptPublicKey) ( kbfscrypto.TLFCryptKeyServerHalf, error) // PutTLFCryptKeyServerHalves stores a server-side key halves for a // set of users and devices. PutTLFCryptKeyServerHalves(ctx context.Context, keyServerHalves UserDeviceKeyServerHalves) error // DeleteTLFCryptKeyServerHalf deletes a server-side key half for a // device given the key half ID. DeleteTLFCryptKeyServerHalf(ctx context.Context, uid keybase1.UID, kid keybase1.KID, serverHalfID TLFCryptKeyServerHalfID) error } // Prefetcher is an interface to a block prefetcher. type Prefetcher interface { // PrefetchBlock directs the prefetcher to prefetch a block. PrefetchBlock(block Block, blockPtr BlockPointer, kmd KeyMetadata, priority int) error // PrefetchAfterBlockRetrieved allows the prefetcher to trigger prefetches // after a block has been retrieved. Whichever component is responsible for // retrieving blocks will call this method once it's done retrieving a // block. PrefetchAfterBlockRetrieved(b Block, kmd KeyMetadata, priority int, hasPrefetched bool) // Shutdown shuts down the prefetcher idempotently. Future calls to // the various Prefetch* methods will return io.EOF. The returned channel // allows upstream components to block until all pending prefetches are // complete. This feature is mainly used for testing, but also to toggle // the prefetcher on and off. Shutdown() <-chan struct{} } // BlockOps gets and puts data blocks to a BlockServer. It performs // the necessary crypto operations on each block. type BlockOps interface { // Get gets the block associated with the given block pointer // (which belongs to the TLF with the given key metadata), // decrypts it if necessary, and fills in the provided block // object with its contents, if the logged-in user has read // permission for that block. cacheLifetime controls the behavior of the // write-through cache once a Get completes. Get(ctx context.Context, kmd KeyMetadata, blockPtr BlockPointer, block Block, cacheLifetime BlockCacheLifetime) error // Ready turns the given block (which belongs to the TLF with // the given key metadata) into encoded (and encrypted) data, // and calculates its ID and size, so that we can do a bunch // of block puts in parallel for every write. Ready() must // guarantee that plainSize <= readyBlockData.QuotaSize(). Ready(ctx context.Context, kmd KeyMetadata, block Block) ( id kbfsblock.ID, plainSize int, readyBlockData ReadyBlockData, err error) // Delete instructs the server to delete the given block references. // It returns the number of not-yet deleted references to // each block reference Delete(ctx context.Context, tlfID tlf.ID, ptrs []BlockPointer) ( liveCounts map[kbfsblock.ID]int, err error) // Archive instructs the server to mark the given block references // as "archived"; that is, they are not being used in the current // view of the folder, and shouldn't be served to anyone other // than folder writers. Archive(ctx context.Context, tlfID tlf.ID, ptrs []BlockPointer) error // TogglePrefetcher activates or deactivates the prefetcher. TogglePrefetcher(ctx context.Context, enable bool) error // Prefetcher retrieves this BlockOps' Prefetcher. Prefetcher() Prefetcher // Shutdown shuts down all the workers performing Get operations Shutdown() } // Duplicate kbfscrypto.AuthTokenRefreshHandler here to work around // gomock's limitations. type authTokenRefreshHandler interface { RefreshAuthToken(context.Context) } // MDServer gets and puts metadata for each top-level directory. The // instantiation should be able to fetch session/user details via KBPKI. On a // put, the server is responsible for 1) ensuring the user has appropriate // permissions for whatever modifications were made; 2) ensuring that // LastModifyingWriter and LastModifyingUser are updated appropriately; and 3) // detecting conflicting writes based on the previous root block ID (i.e., when // it supports strict consistency). On a get, it verifies the logged-in user // has read permissions. // // TODO: Add interface for searching by time type MDServer interface { authTokenRefreshHandler // GetForHandle returns the current (signed/encrypted) metadata // object corresponding to the given top-level folder's handle, if // the logged-in user has read permission on the folder. It // creates the folder if one doesn't exist yet, and the logged-in // user has permission to do so. // // If there is no returned error, then the returned ID must // always be non-null. A nil *RootMetadataSigned may be // returned, but if it is non-nil, then its ID must match the // returned ID. GetForHandle(ctx context.Context, handle tlf.Handle, mStatus MergeStatus) (tlf.ID, *RootMetadataSigned, error) // GetForTLF returns the current (signed/encrypted) metadata object // corresponding to the given top-level folder, if the logged-in // user has read permission on the folder. GetForTLF(ctx context.Context, id tlf.ID, bid BranchID, mStatus MergeStatus) ( *RootMetadataSigned, error) // GetRange returns a range of (signed/encrypted) metadata objects // corresponding to the passed revision numbers (inclusive). GetRange(ctx context.Context, id tlf.ID, bid BranchID, mStatus MergeStatus, start, stop MetadataRevision) ([]*RootMetadataSigned, error) // Put stores the (signed/encrypted) metadata object for the given // top-level folder. Note: If the unmerged bit is set in the metadata // block's flags bitmask it will be appended to the unmerged per-device // history. Put(ctx context.Context, rmds *RootMetadataSigned, extra ExtraMetadata) error // PruneBranch prunes all unmerged history for the given TLF branch. PruneBranch(ctx context.Context, id tlf.ID, bid BranchID) error // RegisterForUpdate tells the MD server to inform the caller when // there is a merged update with a revision number greater than // currHead, which did NOT originate from this same MD server // session. This method returns a chan which can receive only a // single error before it's closed. If the received err is nil, // then there is updated MD ready to fetch which didn't originate // locally; if it is non-nil, then the previous registration // cannot send the next notification (e.g., the connection to the // MD server may have failed). In either case, the caller must // re-register to get a new chan that can receive future update // notifications. RegisterForUpdate(ctx context.Context, id tlf.ID, currHead MetadataRevision) (<-chan error, error) // CheckForRekeys initiates the rekey checking process on the // server. The server is allowed to delay this request, and so it // returns a channel for returning the error. Actual rekey // requests are expected to come in asynchronously. CheckForRekeys(ctx context.Context) <-chan error // TruncateLock attempts to take the history truncation lock for // this folder, for a TTL defined by the server. Returns true if // the lock was successfully taken. TruncateLock(ctx context.Context, id tlf.ID) (bool, error) // TruncateUnlock attempts to release the history truncation lock // for this folder. Returns true if the lock was successfully // released. TruncateUnlock(ctx context.Context, id tlf.ID) (bool, error) // DisableRekeyUpdatesForTesting disables processing rekey updates // received from the mdserver while testing. DisableRekeyUpdatesForTesting() // Shutdown is called to shutdown an MDServer connection. Shutdown() // IsConnected returns whether the MDServer is connected. IsConnected() bool // GetLatestHandleForTLF returns the server's idea of the latest handle for the TLF, // which may not yet be reflected in the MD if the TLF hasn't been rekeyed since it // entered into a conflicting state. For the highest level of confidence, the caller // should verify the mapping with a Merkle tree lookup. GetLatestHandleForTLF(ctx context.Context, id tlf.ID) ( tlf.Handle, error) // OffsetFromServerTime is the current estimate for how off our // local clock is from the mdserver clock. Add this to any // mdserver-provided timestamps to get the "local" time of the // corresponding event. If the returned bool is false, then we // don't have a current estimate for the offset. OffsetFromServerTime() (time.Duration, bool) // GetKeyBundles looks up the key bundles for the given key // bundle IDs. tlfID must be non-zero but either or both wkbID // and rkbID can be zero, in which case nil will be returned // for the respective bundle. If a bundle cannot be found, an // error is returned and nils are returned for both bundles. GetKeyBundles(ctx context.Context, tlfID tlf.ID, wkbID TLFWriterKeyBundleID, rkbID TLFReaderKeyBundleID) ( *TLFWriterKeyBundleV3, *TLFReaderKeyBundleV3, error) } type mdServerLocal interface { MDServer addNewAssertionForTest( uid keybase1.UID, newAssertion keybase1.SocialAssertion) error getCurrentMergedHeadRevision(ctx context.Context, id tlf.ID) ( rev MetadataRevision, err error) isShutdown() bool copy(config mdServerLocalConfig) mdServerLocal } // BlockServer gets and puts opaque data blocks. The instantiation // should be able to fetch session/user details via KBPKI. On a // put/delete, the server is reponsible for: 1) checking that the ID // matches the hash of the buffer; and 2) enforcing writer quotas. type BlockServer interface { authTokenRefreshHandler // Get gets the (encrypted) block data associated with the given // block ID and context, uses the provided block key to decrypt // the block, and fills in the provided block object with its // contents, if the logged-in user has read permission for that // block. Get(ctx context.Context, tlfID tlf.ID, id kbfsblock.ID, context kbfsblock.Context) ( []byte, kbfscrypto.BlockCryptKeyServerHalf, error) // Put stores the (encrypted) block data under the given ID // and context on the server, along with the server half of // the block key. context should contain a kbfsblock.RefNonce // of zero. There will be an initial reference for this block // for the given context. // // Put should be idempotent, although it should also return an // error if, for a given ID, any of the other arguments differ // from previous Put calls with the same ID. // // If this returns a BServerErrorOverQuota, with Throttled=false, // the caller can treat it as informational and otherwise ignore // the error. Put(ctx context.Context, tlfID tlf.ID, id kbfsblock.ID, context kbfsblock.Context, buf []byte, serverHalf kbfscrypto.BlockCryptKeyServerHalf) error // AddBlockReference adds a new reference to the given block, // defined by the given context (which should contain a // non-zero kbfsblock.RefNonce). (Contexts with a // kbfsblock.RefNonce of zero should be used when putting the // block for the first time via Put().) Returns a // BServerErrorBlockNonExistent if id is unknown within this // folder. // // AddBlockReference should be idempotent, although it should // also return an error if, for a given ID and refnonce, any // of the other fields of context differ from previous // AddBlockReference calls with the same ID and refnonce. // // If this returns a BServerErrorOverQuota, with Throttled=false, // the caller can treat it as informational and otherwise ignore // the error. AddBlockReference(ctx context.Context, tlfID tlf.ID, id kbfsblock.ID, context kbfsblock.Context) error // RemoveBlockReferences removes the references to the given block // ID defined by the given contexts. If no references to the block // remain after this call, the server is allowed to delete the // corresponding block permanently. If the reference defined by // the count has already been removed, the call is a no-op. // It returns the number of remaining not-yet-deleted references after this // reference has been removed RemoveBlockReferences(ctx context.Context, tlfID tlf.ID, contexts kbfsblock.ContextMap) (liveCounts map[kbfsblock.ID]int, err error) // ArchiveBlockReferences marks the given block references as // "archived"; that is, they are not being used in the current // view of the folder, and shouldn't be served to anyone other // than folder writers. // // For a given ID/refnonce pair, ArchiveBlockReferences should // be idempotent, although it should also return an error if // any of the other fields of the context differ from previous // calls with the same ID/refnonce pair. ArchiveBlockReferences(ctx context.Context, tlfID tlf.ID, contexts kbfsblock.ContextMap) error // IsUnflushed returns whether a given block is being queued // locally for later flushing to another block server. IsUnflushed(ctx context.Context, tlfID tlf.ID, id kbfsblock.ID) (bool, error) // Shutdown is called to shutdown a BlockServer connection. Shutdown() // GetUserQuotaInfo returns the quota for the user. GetUserQuotaInfo(ctx context.Context) (info *kbfsblock.UserQuotaInfo, err error) } // blockServerLocal is the interface for BlockServer implementations // that store data locally. type blockServerLocal interface { BlockServer // getAllRefsForTest returns all the known block references // for the given TLF, and should only be used during testing. getAllRefsForTest(ctx context.Context, tlfID tlf.ID) ( map[kbfsblock.ID]blockRefMap, error) } // BlockSplitter decides when a file or directory block needs to be split type BlockSplitter interface { // CopyUntilSplit copies data into the block until we reach the // point where we should split, but only if writing to the end of // the last block. If this is writing into the middle of a file, // just copy everything that will fit into the block, and assume // that block boundaries will be fixed later. Return how much was // copied. CopyUntilSplit( block *FileBlock, lastBlock bool, data []byte, off int64) int64 // CheckSplit, given a block, figures out whether it ends at the // right place. If so, return 0. If not, return either the // offset in the block where it should be split, or -1 if more // bytes from the next block should be appended. CheckSplit(block *FileBlock) int64 // MaxPtrsPerBlock describes the number of indirect pointers we // can fit into one indirect block. MaxPtrsPerBlock() int // ShouldEmbedBlockChanges decides whether we should keep the // block changes embedded in the MD or not. ShouldEmbedBlockChanges(bc *BlockChanges) bool } // KeyServer fetches/writes server-side key halves from/to the key server. type KeyServer interface { // GetTLFCryptKeyServerHalf gets a server-side key half for a // device given the key half ID. GetTLFCryptKeyServerHalf(ctx context.Context, serverHalfID TLFCryptKeyServerHalfID, cryptPublicKey kbfscrypto.CryptPublicKey) ( kbfscrypto.TLFCryptKeyServerHalf, error) // PutTLFCryptKeyServerHalves stores a server-side key halves for a // set of users and devices. PutTLFCryptKeyServerHalves(ctx context.Context, keyServerHalves UserDeviceKeyServerHalves) error // DeleteTLFCryptKeyServerHalf deletes a server-side key half for a // device given the key half ID. DeleteTLFCryptKeyServerHalf(ctx context.Context, uid keybase1.UID, kid keybase1.KID, serverHalfID TLFCryptKeyServerHalfID) error // Shutdown is called to free any KeyServer resources. Shutdown() } // NodeChange represents a change made to a node as part of an atomic // file system operation. type NodeChange struct { Node Node // Basenames of entries added/removed. DirUpdated []string FileUpdated []WriteRange } // Observer can be notified that there is an available update for a // given directory. The notification callbacks should not block, or // make any calls to the Notifier interface. Nodes passed to the // observer should not be held past the end of the notification // callback. type Observer interface { // LocalChange announces that the file at this Node has been // updated locally, but not yet saved at the server. LocalChange(ctx context.Context, node Node, write WriteRange) // BatchChanges announces that the nodes have all been updated // together atomically. Each NodeChange in changes affects the // same top-level folder and branch. BatchChanges(ctx context.Context, changes []NodeChange) // TlfHandleChange announces that the handle of the corresponding // folder branch has changed, likely due to previously-unresolved // assertions becoming resolved. This indicates that the listener // should switch over any cached paths for this folder-branch to // the new name. Nodes that were acquired under the old name will // still continue to work, but new lookups on the old name may // either encounter alias errors or entirely new TLFs (in the case // of conflicts). TlfHandleChange(ctx context.Context, newHandle *TlfHandle) } // Notifier notifies registrants of directory changes type Notifier interface { // RegisterForChanges declares that the given Observer wants to // subscribe to updates for the given top-level folders. RegisterForChanges(folderBranches []FolderBranch, obs Observer) error // UnregisterFromChanges declares that the given Observer no // longer wants to subscribe to updates for the given top-level // folders. UnregisterFromChanges(folderBranches []FolderBranch, obs Observer) error } // Clock is an interface for getting the current time type Clock interface { // Now returns the current time. Now() time.Time } // ConflictRenamer deals with names for conflicting directory entries. type ConflictRenamer interface { // ConflictRename returns the appropriately modified filename. ConflictRename(ctx context.Context, op op, original string) ( string, error) } // Config collects all the singleton instance instantiations needed to // run KBFS in one place. The methods below are self-explanatory and // do not require comments. type Config interface { dataVersioner logMaker blockCacher KBFSOps() KBFSOps SetKBFSOps(KBFSOps) KBPKI() KBPKI SetKBPKI(KBPKI) KeyManager() KeyManager SetKeyManager(KeyManager) Reporter() Reporter SetReporter(Reporter) MDCache() MDCache SetMDCache(MDCache) KeyCache() KeyCache SetKeyBundleCache(KeyBundleCache) KeyBundleCache() KeyBundleCache SetKeyCache(KeyCache) SetBlockCache(BlockCache) DirtyBlockCache() DirtyBlockCache SetDirtyBlockCache(DirtyBlockCache) Crypto() Crypto SetCrypto(Crypto) Codec() kbfscodec.Codec SetCodec(kbfscodec.Codec) MDOps() MDOps SetMDOps(MDOps) KeyOps() KeyOps SetKeyOps(KeyOps) BlockOps() BlockOps SetBlockOps(BlockOps) MDServer() MDServer SetMDServer(MDServer) BlockServer() BlockServer SetBlockServer(BlockServer) KeyServer() KeyServer SetKeyServer(KeyServer) KeybaseService() KeybaseService SetKeybaseService(KeybaseService) BlockSplitter() BlockSplitter SetBlockSplitter(BlockSplitter) Notifier() Notifier SetNotifier(Notifier) Clock() Clock SetClock(Clock) ConflictRenamer() ConflictRenamer SetConflictRenamer(ConflictRenamer) MetadataVersion() MetadataVer SetMetadataVersion(MetadataVer) RekeyQueue() RekeyQueue SetRekeyQueue(RekeyQueue) // ReqsBufSize indicates the number of read or write operations // that can be buffered per folder ReqsBufSize() int // MaxFileBytes indicates the maximum supported plaintext size of // a file in bytes. MaxFileBytes() uint64 // MaxNameBytes indicates the maximum supported size of a // directory entry name in bytes. MaxNameBytes() uint32 // MaxDirBytes indicates the maximum supported plaintext size of a // directory in bytes. MaxDirBytes() uint64 // DoBackgroundFlushes says whether we should periodically try to // flush dirty files, even without a sync from the user. Should // be true except for during some testing. DoBackgroundFlushes() bool SetDoBackgroundFlushes(bool) // RekeyWithPromptWaitTime indicates how long to wait, after // setting the rekey bit, before prompting for a paper key. RekeyWithPromptWaitTime() time.Duration SetRekeyWithPromptWaitTime(time.Duration) // GracePeriod specifies a grace period for which a delayed cancellation // waits before actual cancels the context. This is useful for giving // critical portion of a slow remote operation some extra time to finish as // an effort to avoid conflicting. Example include an O_EXCL Create call // interrupted by ALRM signal actually makes it to the server, while // application assumes not since EINTR is returned. A delayed cancellation // allows us to distinguish between successful cancel (where remote operation // didn't make to server) or failed cancel (where remote operation made to // the server). However, the optimal value of this depends on the network // conditions. A long grace period for really good network condition would // just unnecessarily slow down Ctrl-C. // // TODO: make this adaptive and self-change over time based on network // conditions. DelayedCancellationGracePeriod() time.Duration SetDelayedCancellationGracePeriod(time.Duration) // QuotaReclamationPeriod indicates how often should each TLF // should check for quota to reclaim. If the Duration.Seconds() // == 0, quota reclamation should not run automatically. QuotaReclamationPeriod() time.Duration // QuotaReclamationMinUnrefAge indicates the minimum time a block // must have been unreferenced before it can be reclaimed. QuotaReclamationMinUnrefAge() time.Duration // QuotaReclamationMinHeadAge indicates the minimum age of the // most recently merged MD update before we can run reclamation, // to avoid conflicting with a currently active writer. QuotaReclamationMinHeadAge() time.Duration // ResetCaches clears and re-initializes all data and key caches. ResetCaches() // MetricsRegistry may be nil, which should be interpreted as // not using metrics at all. (i.e., as if UseNilMetrics were // set). This differs from how go-metrics treats nil Registry // objects, which is to use the default registry. MetricsRegistry() metrics.Registry SetMetricsRegistry(metrics.Registry) // TLFValidDuration is the time TLFs are valid before identification needs to be redone. TLFValidDuration() time.Duration // SetTLFValidDuration sets TLFValidDuration. SetTLFValidDuration(time.Duration) // Shutdown is called to free config resources. Shutdown(context.Context) error // CheckStateOnShutdown tells the caller whether or not it is safe // to check the state of the system on shutdown. CheckStateOnShutdown() bool } // NodeCache holds Nodes, and allows libkbfs to update them when // things change about the underlying KBFS blocks. It is probably // most useful to instantiate this on a per-folder-branch basis, so // that it can create a Path with the correct DirId and Branch name. type NodeCache interface { // GetOrCreate either makes a new Node for the given // BlockPointer, or returns an existing one. TODO: If we ever // support hard links, we will have to revisit the "name" and // "parent" parameters here. name must not be empty. Returns // an error if parent cannot be found. GetOrCreate(ptr BlockPointer, name string, parent Node) (Node, error) // Get returns the Node associated with the given ptr if one // already exists. Otherwise, it returns nil. Get(ref BlockRef) Node // UpdatePointer updates the BlockPointer for the corresponding // Node. NodeCache ignores this call when oldRef is not cached in // any Node. Returns whether the pointer was updated. UpdatePointer(oldRef BlockRef, newPtr BlockPointer) bool // Move swaps the parent node for the corresponding Node, and // updates the node's name. NodeCache ignores the call when ptr // is not cached. Returns an error if newParent cannot be found. // If newParent is nil, it treats the ptr's corresponding node as // being unlinked from the old parent completely. Move(ref BlockRef, newParent Node, newName string) error // Unlink set the corresponding node's parent to nil and caches // the provided path in case the node is still open. NodeCache // ignores the call when ptr is not cached. The path is required // because the caller may have made changes to the parent nodes // already that shouldn't be reflected in the cached path. Unlink(ref BlockRef, oldPath path) // PathFromNode creates the path up to a given Node. PathFromNode(node Node) path // AllNodes returns the complete set of nodes currently in the cache. AllNodes() []Node } // fileBlockDeepCopier fetches a file block, makes a deep copy of it // (duplicating pointer for any indirect blocks) and generates a new // random temporary block ID for it. It returns the new BlockPointer, // and internally saves the block for future uses. type fileBlockDeepCopier func(context.Context, string, BlockPointer) ( BlockPointer, error) // crAction represents a specific action to take as part of the // conflict resolution process. type crAction interface { // swapUnmergedBlock should be called before do(), and if it // returns true, the caller must use the merged block // corresponding to the returned BlockPointer instead of // unmergedBlock when calling do(). If BlockPointer{} is zeroPtr // (and true is returned), just swap in the regular mergedBlock. swapUnmergedBlock(unmergedChains *crChains, mergedChains *crChains, unmergedBlock *DirBlock) (bool, BlockPointer, error) // do modifies the given merged block in place to resolve the // conflict, and potential uses the provided blockCopyFetchers to // obtain copies of other blocks (along with new BlockPointers) // when requiring a block copy. do(ctx context.Context, unmergedCopier fileBlockDeepCopier, mergedCopier fileBlockDeepCopier, unmergedBlock *DirBlock, mergedBlock *DirBlock) error // updateOps potentially modifies, in place, the slices of // unmerged and merged operations stored in the corresponding // crChains for the given unmerged and merged most recent // pointers. Eventually, the "unmerged" ops will be pushed as // part of a MD update, and so should contain any necessarily // operations to fully merge the unmerged data, including any // conflict resolution. The "merged" ops will be played through // locally, to notify any caches about the newly-obtained merged // data (and any changes to local data that were required as part // of conflict resolution, such as renames). A few things to note: // * A particular action's updateOps method may be called more than // once for different sets of chains, however it should only add // new directory operations (like create/rm/rename) into directory // chains. // * updateOps doesn't necessarily result in correct BlockPointers within // each of those ops; that must happen in a later phase. // * mergedBlock can be nil if the chain is for a file. updateOps(unmergedMostRecent BlockPointer, mergedMostRecent BlockPointer, unmergedBlock *DirBlock, mergedBlock *DirBlock, unmergedChains *crChains, mergedChains *crChains) error // String returns a string representation for this crAction, used // for debugging. String() string } // RekeyQueue is a managed queue of folders needing some rekey action taken upon them // by the current client. type RekeyQueue interface { // Enqueue enqueues a folder for rekey action. Enqueue(tlf.ID) <-chan error // IsRekeyPending returns true if the given folder is in the rekey queue. IsRekeyPending(tlf.ID) bool // GetRekeyChannel will return any rekey completion channel (if pending.) GetRekeyChannel(id tlf.ID) <-chan error // Clear cancels all pending rekey actions and clears the queue. Clear() // Waits for all queued rekeys to finish Wait(ctx context.Context) error } // BareRootMetadata is a read-only interface to the bare serializeable MD that // is signed by the reader or writer. type BareRootMetadata interface { // TlfID returns the ID of the TLF this BareRootMetadata is for. TlfID() tlf.ID // KeyGenerationsToUpdate returns a range that has to be // updated when rekeying. start is included, but end is not // included. This range can be empty (i.e., start >= end), in // which case there's nothing to update, i.e. the TLF is // public, or there aren't any existing key generations. KeyGenerationsToUpdate() (start KeyGen, end KeyGen) // LatestKeyGeneration returns the most recent key generation in this // BareRootMetadata, or PublicKeyGen if this TLF is public. LatestKeyGeneration() KeyGen // IsValidRekeyRequest returns true if the current block is a simple rekey wrt // the passed block. IsValidRekeyRequest(codec kbfscodec.Codec, prevMd BareRootMetadata, user keybase1.UID, prevExtra, extra ExtraMetadata) (bool, error) // MergedStatus returns the status of this update -- has it been // merged into the main folder or not? MergedStatus() MergeStatus // IsRekeySet returns true if the rekey bit is set. IsRekeySet() bool // IsWriterMetadataCopiedSet returns true if the bit is set indicating // the writer metadata was copied. IsWriterMetadataCopiedSet() bool // IsFinal returns true if this is the last metadata block for a given // folder. This is only expected to be set for folder resets. IsFinal() bool // IsWriter returns whether or not the user+device is an authorized writer. IsWriter(user keybase1.UID, deviceKID keybase1.KID, extra ExtraMetadata) bool // IsReader returns whether or not the user+device is an authorized reader. IsReader(user keybase1.UID, deviceKID keybase1.KID, extra ExtraMetadata) bool // DeepCopy returns a deep copy of the underlying data structure. DeepCopy(codec kbfscodec.Codec) (MutableBareRootMetadata, error) // MakeSuccessorCopy returns a newly constructed successor // copy to this metadata revision. It differs from DeepCopy // in that it can perform an up conversion to a new metadata // version. tlfCryptKeyGetter should be a function that // returns a list of TLFCryptKeys for all key generations in // ascending order. MakeSuccessorCopy(codec kbfscodec.Codec, crypto cryptoPure, extra ExtraMetadata, latestMDVer MetadataVer, tlfCryptKeyGetter func() ([]kbfscrypto.TLFCryptKey, error), isReadableAndWriter bool) (mdCopy MutableBareRootMetadata, extraCopy ExtraMetadata, err error) // CheckValidSuccessor makes sure the given BareRootMetadata is a valid // successor to the current one, and returns an error otherwise. CheckValidSuccessor(currID MdID, nextMd BareRootMetadata) error // CheckValidSuccessorForServer is like CheckValidSuccessor but with // server-specific error messages. CheckValidSuccessorForServer(currID MdID, nextMd BareRootMetadata) error // MakeBareTlfHandle makes a tlf.Handle for this // BareRootMetadata. Should be used only by servers and MDOps. MakeBareTlfHandle(extra ExtraMetadata) (tlf.Handle, error) // TlfHandleExtensions returns a list of handle extensions associated with the TLf. TlfHandleExtensions() (extensions []tlf.HandleExtension) // GetDevicePublicKeys returns the kbfscrypto.CryptPublicKeys // for all known users and devices. Returns an error if the // TLF is public. GetUserDevicePublicKeys(extra ExtraMetadata) ( writers, readers UserDevicePublicKeys, err error) // GetTLFCryptKeyParams returns all the necessary info to construct // the TLF crypt key for the given key generation, user, and device // (identified by its crypt public key), or false if not found. This // returns an error if the TLF is public. GetTLFCryptKeyParams(keyGen KeyGen, user keybase1.UID, key kbfscrypto.CryptPublicKey, extra ExtraMetadata) ( kbfscrypto.TLFEphemeralPublicKey, EncryptedTLFCryptKeyClientHalf, TLFCryptKeyServerHalfID, bool, error) // IsValidAndSigned verifies the BareRootMetadata, checks the // writer signature, and returns an error if a problem was // found. This should be the first thing checked on a BRMD // retrieved from an untrusted source, and then the signing // user and key should be validated, either by comparing to // the current device key (using IsLastModifiedBy), or by // checking with KBPKI. IsValidAndSigned(codec kbfscodec.Codec, crypto cryptoPure, extra ExtraMetadata) error // IsLastModifiedBy verifies that the BareRootMetadata is // written by the given user and device (identified by the KID // of the device verifying key), and returns an error if not. IsLastModifiedBy(uid keybase1.UID, key kbfscrypto.VerifyingKey) error // LastModifyingWriter return the UID of the last user to modify the writer metadata. LastModifyingWriter() keybase1.UID // LastModifyingUser return the UID of the last user to modify the any of the metadata. GetLastModifyingUser() keybase1.UID // RefBytes returns the number of newly referenced bytes introduced by this revision of metadata. RefBytes() uint64 // UnrefBytes returns the number of newly unreferenced bytes introduced by this revision of metadata. UnrefBytes() uint64 // DiskUsage returns the estimated disk usage for the folder as of this revision of metadata. DiskUsage() uint64 // RevisionNumber returns the revision number associated with this metadata structure. RevisionNumber() MetadataRevision // BID returns the per-device branch ID associated with this metadata revision. BID() BranchID // GetPrevRoot returns the hash of the previous metadata revision. GetPrevRoot() MdID // IsUnmergedSet returns true if the unmerged bit is set. IsUnmergedSet() bool // GetSerializedPrivateMetadata returns the serialized private metadata as a byte slice. GetSerializedPrivateMetadata() []byte // GetSerializedWriterMetadata serializes the underlying writer metadata and returns the result. GetSerializedWriterMetadata(codec kbfscodec.Codec) ([]byte, error) // Version returns the metadata version. Version() MetadataVer // GetCurrentTLFPublicKey returns the TLF public key for the // current key generation. GetCurrentTLFPublicKey(ExtraMetadata) (kbfscrypto.TLFPublicKey, error) // GetUnresolvedParticipants returns any unresolved readers // and writers present in this revision of metadata. The // returned array should be safe to modify by the caller. GetUnresolvedParticipants() []keybase1.SocialAssertion // GetTLFWriterKeyBundleID returns the ID of the externally-stored writer key bundle, or the zero value if // this object stores it internally. GetTLFWriterKeyBundleID() TLFWriterKeyBundleID // GetTLFReaderKeyBundleID returns the ID of the externally-stored reader key bundle, or the zero value if // this object stores it internally. GetTLFReaderKeyBundleID() TLFReaderKeyBundleID // StoresHistoricTLFCryptKeys returns whether or not history keys are symmetrically encrypted; if not, they're // encrypted per-device. StoresHistoricTLFCryptKeys() bool // GetHistoricTLFCryptKey attempts to symmetrically decrypt the key at the given // generation using the current generation's TLFCryptKey. GetHistoricTLFCryptKey(c cryptoPure, keyGen KeyGen, currentKey kbfscrypto.TLFCryptKey, extra ExtraMetadata) ( kbfscrypto.TLFCryptKey, error) } // MutableBareRootMetadata is a mutable interface to the bare serializeable MD that is signed by the reader or writer. type MutableBareRootMetadata interface { BareRootMetadata // SetRefBytes sets the number of newly referenced bytes introduced by this revision of metadata. SetRefBytes(refBytes uint64) // SetUnrefBytes sets the number of newly unreferenced bytes introduced by this revision of metadata. SetUnrefBytes(unrefBytes uint64) // SetDiskUsage sets the estimated disk usage for the folder as of this revision of metadata. SetDiskUsage(diskUsage uint64) // AddRefBytes increments the number of newly referenced bytes introduced by this revision of metadata. AddRefBytes(refBytes uint64) // AddUnrefBytes increments the number of newly unreferenced bytes introduced by this revision of metadata. AddUnrefBytes(unrefBytes uint64) // AddDiskUsage increments the estimated disk usage for the folder as of this revision of metadata. AddDiskUsage(diskUsage uint64) // ClearRekeyBit unsets any set rekey bit. ClearRekeyBit() // ClearWriterMetadataCopiedBit unsets any set writer metadata copied bit. ClearWriterMetadataCopiedBit() // ClearFinalBit unsets any final bit. ClearFinalBit() // SetUnmerged sets the unmerged bit. SetUnmerged() // SetBranchID sets the branch ID for this metadata revision. SetBranchID(bid BranchID) // SetPrevRoot sets the hash of the previous metadata revision. SetPrevRoot(mdID MdID) // SetSerializedPrivateMetadata sets the serialized private metadata. SetSerializedPrivateMetadata(spmd []byte) // SignWriterMetadataInternally signs the writer metadata, for // versions that store this signature inside the metadata. SignWriterMetadataInternally(ctx context.Context, codec kbfscodec.Codec, signer kbfscrypto.Signer) error // SetLastModifyingWriter sets the UID of the last user to modify the writer metadata. SetLastModifyingWriter(user keybase1.UID) // SetLastModifyingUser sets the UID of the last user to modify any of the metadata. SetLastModifyingUser(user keybase1.UID) // SetRekeyBit sets the rekey bit. SetRekeyBit() // SetFinalBit sets the finalized bit. SetFinalBit() // SetWriterMetadataCopiedBit set the writer metadata copied bit. SetWriterMetadataCopiedBit() // SetRevision sets the revision number of the underlying metadata. SetRevision(revision MetadataRevision) // SetUnresolvedReaders sets the list of unresolved readers associated with this folder. SetUnresolvedReaders(readers []keybase1.SocialAssertion) // SetUnresolvedWriters sets the list of unresolved writers associated with this folder. SetUnresolvedWriters(writers []keybase1.SocialAssertion) // SetConflictInfo sets any conflict info associated with this metadata revision. SetConflictInfo(ci *tlf.HandleExtension) // SetFinalizedInfo sets any finalized info associated with this metadata revision. SetFinalizedInfo(fi *tlf.HandleExtension) // SetWriters sets the list of writers associated with this folder. SetWriters(writers []keybase1.UID) // SetTlfID sets the ID of the underlying folder in the metadata structure. SetTlfID(tlf tlf.ID) // AddKeyGeneration adds a new key generation to this revision // of metadata. If StoresHistoricTLFCryptKeys is false, then // currCryptKey must be zero. Otherwise, currCryptKey must be // zero if there are no existing key generations, and non-zero // for otherwise. // // AddKeyGeneration must only be called on metadata for // private TLFs. // // Note that the TLFPrivateKey corresponding to privKey must // also be stored in PrivateMetadata. AddKeyGeneration(codec kbfscodec.Codec, crypto cryptoPure, currExtra ExtraMetadata, updatedWriterKeys, updatedReaderKeys UserDevicePublicKeys, ePubKey kbfscrypto.TLFEphemeralPublicKey, ePrivKey kbfscrypto.TLFEphemeralPrivateKey, pubKey kbfscrypto.TLFPublicKey, currCryptKey, nextCryptKey kbfscrypto.TLFCryptKey) ( nextExtra ExtraMetadata, serverHalves UserDeviceKeyServerHalves, err error) // UpdateKeyBundles ensures that every device for every writer // and reader in the provided lists has complete TLF crypt key // info, and uses the new ephemeral key pair to generate the // info if it doesn't yet exist. tlfCryptKeys must contain an // entry for each key generation in KeyGenerationsToUpdate(), // in ascending order. // // updatedWriterKeys and updatedReaderKeys usually contains // the full maps of writers to per-device crypt public keys, // but for reader rekey, updatedWriterKeys will be empty and // updatedReaderKeys will contain only a single entry. // // UpdateKeyBundles must only be called on metadata for // private TLFs. // // An array of server halves to push to the server are // returned, with each entry corresponding to each key // generation in KeyGenerationsToUpdate(), in ascending order. UpdateKeyBundles(crypto cryptoPure, extra ExtraMetadata, updatedWriterKeys, updatedReaderKeys UserDevicePublicKeys, ePubKey kbfscrypto.TLFEphemeralPublicKey, ePrivKey kbfscrypto.TLFEphemeralPrivateKey, tlfCryptKeys []kbfscrypto.TLFCryptKey) ( []UserDeviceKeyServerHalves, error) // PromoteReaders converts the given set of users (which may // be empty) from readers to writers. PromoteReaders(readersToPromote map[keybase1.UID]bool, extra ExtraMetadata) error // RevokeRemovedDevices removes key info for any device not in // the given maps, and returns a corresponding map of server // halves to delete from the server. // // Note: the returned server halves may not be for all key // generations, e.g. for MDv3 it's only for the latest key // generation. RevokeRemovedDevices( updatedWriterKeys, updatedReaderKeys UserDevicePublicKeys, extra ExtraMetadata) (ServerHalfRemovalInfo, error) // FinalizeRekey must be called called after all rekeying work // has been performed on the underlying metadata. FinalizeRekey(c cryptoPure, extra ExtraMetadata) error } // KeyBundleCache is an interface to a key bundle cache for use with v3 metadata. type KeyBundleCache interface { // GetTLFReaderKeyBundle returns the TLFReaderKeyBundleV3 for // the given TLFReaderKeyBundleID, or nil if there is none. GetTLFReaderKeyBundle(tlf.ID, TLFReaderKeyBundleID) (*TLFReaderKeyBundleV3, error) // GetTLFWriterKeyBundle returns the TLFWriterKeyBundleV3 for // the given TLFWriterKeyBundleID, or nil if there is none. GetTLFWriterKeyBundle(tlf.ID, TLFWriterKeyBundleID) (*TLFWriterKeyBundleV3, error) // PutTLFReaderKeyBundle stores the given TLFReaderKeyBundleV3. PutTLFReaderKeyBundle(tlf.ID, TLFReaderKeyBundleID, TLFReaderKeyBundleV3) // PutTLFWriterKeyBundle stores the given TLFWriterKeyBundleV3. PutTLFWriterKeyBundle(tlf.ID, TLFWriterKeyBundleID, TLFWriterKeyBundleV3) }
1
15,356
"and returns that" -- it looks like this method has no return value.
keybase-kbfs
go
@@ -212,7 +212,7 @@ class BitmapMasks(BaseInstanceMasks): def flip(self, flip_direction='horizontal'): """See :func:`BaseInstanceMasks.flip`.""" - assert flip_direction in ('horizontal', 'vertical') + assert flip_direction in ('horizontal', 'vertical', 'diagonal') if len(self.masks) == 0: flipped_masks = self.masks
1
from abc import ABCMeta, abstractmethod import mmcv import numpy as np import pycocotools.mask as maskUtils import torch from mmcv.ops.roi_align import roi_align class BaseInstanceMasks(metaclass=ABCMeta): """Base class for instance masks.""" @abstractmethod def rescale(self, scale, interpolation='nearest'): """Rescale masks as large as possible while keeping the aspect ratio. For details can refer to `mmcv.imrescale`. Args: scale (tuple[int]): The maximum size (h, w) of rescaled mask. interpolation (str): Same as :func:`mmcv.imrescale`. Returns: BaseInstanceMasks: The rescaled masks. """ pass @abstractmethod def resize(self, out_shape, interpolation='nearest'): """Resize masks to the given out_shape. Args: out_shape: Target (h, w) of resized mask. interpolation (str): See :func:`mmcv.imresize`. Returns: BaseInstanceMasks: The resized masks. """ pass @abstractmethod def flip(self, flip_direction='horizontal'): """Flip masks alone the given direction. Args: flip_direction (str): Either 'horizontal' or 'vertical'. Returns: BaseInstanceMasks: The flipped masks. """ pass @abstractmethod def pad(self, out_shape, pad_val): """Pad masks to the given size of (h, w). Args: out_shape (tuple[int]): Target (h, w) of padded mask. pad_val (int): The padded value. Returns: BaseInstanceMasks: The padded masks. """ pass @abstractmethod def crop(self, bbox): """Crop each mask by the given bbox. Args: bbox (ndarray): Bbox in format [x1, y1, x2, y2], shape (4, ). Return: BaseInstanceMasks: The cropped masks. """ pass @abstractmethod def crop_and_resize(self, bboxes, out_shape, inds, device, interpolation='bilinear'): """Crop and resize masks by the given bboxes. This function is mainly used in mask targets computation. It firstly align mask to bboxes by assigned_inds, then crop mask by the assigned bbox and resize to the size of (mask_h, mask_w) Args: bboxes (Tensor): Bboxes in format [x1, y1, x2, y2], shape (N, 4) out_shape (tuple[int]): Target (h, w) of resized mask inds (ndarray): Indexes to assign masks to each bbox device (str): Device of bboxes interpolation (str): See `mmcv.imresize` Return: BaseInstanceMasks: the cropped and resized masks. """ pass @abstractmethod def expand(self, expanded_h, expanded_w, top, left): """see :class:`Expand`.""" pass @property @abstractmethod def areas(self): """ndarray: areas of each instance.""" pass @abstractmethod def to_ndarray(self): """Convert masks to the format of ndarray. Return: ndarray: Converted masks in the format of ndarray. """ pass @abstractmethod def to_tensor(self, dtype, device): """Convert masks to the format of Tensor. Args: dtype (str): Dtype of converted mask. device (torch.device): Device of converted masks. Returns: Tensor: Converted masks in the format of Tensor. """ pass class BitmapMasks(BaseInstanceMasks): """This class represents masks in the form of bitmaps. Args: masks (ndarray): ndarray of masks in shape (N, H, W), where N is the number of objects. height (int): height of masks width (int): width of masks """ def __init__(self, masks, height, width): self.height = height self.width = width if len(masks) == 0: self.masks = np.empty((0, self.height, self.width), dtype=np.uint8) else: assert isinstance(masks, (list, np.ndarray)) if isinstance(masks, list): assert isinstance(masks[0], np.ndarray) assert masks[0].ndim == 2 # (H, W) else: assert masks.ndim == 3 # (N, H, W) self.masks = np.stack(masks).reshape(-1, height, width) assert self.masks.shape[1] == self.height assert self.masks.shape[2] == self.width def __getitem__(self, index): """Index the BitmapMask. Args: index (int | ndarray): Indices in the format of integer or ndarray. Returns: :obj:`BitmapMasks`: Indexed bitmap masks. """ masks = self.masks[index].reshape(-1, self.height, self.width) return BitmapMasks(masks, self.height, self.width) def __iter__(self): return iter(self.masks) def __repr__(self): s = self.__class__.__name__ + '(' s += f'num_masks={len(self.masks)}, ' s += f'height={self.height}, ' s += f'width={self.width})' return s def __len__(self): """Number of masks.""" return len(self.masks) def rescale(self, scale, interpolation='nearest'): """See :func:`BaseInstanceMasks.rescale`.""" if len(self.masks) == 0: new_w, new_h = mmcv.rescale_size((self.width, self.height), scale) rescaled_masks = np.empty((0, new_h, new_w), dtype=np.uint8) else: rescaled_masks = np.stack([ mmcv.imrescale(mask, scale, interpolation=interpolation) for mask in self.masks ]) height, width = rescaled_masks.shape[1:] return BitmapMasks(rescaled_masks, height, width) def resize(self, out_shape, interpolation='nearest'): """See :func:`BaseInstanceMasks.resize`.""" if len(self.masks) == 0: resized_masks = np.empty((0, *out_shape), dtype=np.uint8) else: resized_masks = np.stack([ mmcv.imresize(mask, out_shape, interpolation=interpolation) for mask in self.masks ]) return BitmapMasks(resized_masks, *out_shape) def flip(self, flip_direction='horizontal'): """See :func:`BaseInstanceMasks.flip`.""" assert flip_direction in ('horizontal', 'vertical') if len(self.masks) == 0: flipped_masks = self.masks else: flipped_masks = np.stack([ mmcv.imflip(mask, direction=flip_direction) for mask in self.masks ]) return BitmapMasks(flipped_masks, self.height, self.width) def pad(self, out_shape, pad_val=0): """See :func:`BaseInstanceMasks.pad`.""" if len(self.masks) == 0: padded_masks = np.empty((0, *out_shape), dtype=np.uint8) else: padded_masks = np.stack([ mmcv.impad(mask, shape=out_shape, pad_val=pad_val) for mask in self.masks ]) return BitmapMasks(padded_masks, *out_shape) def crop(self, bbox): """See :func:`BaseInstanceMasks.crop`.""" assert isinstance(bbox, np.ndarray) assert bbox.ndim == 1 # clip the boundary bbox = bbox.copy() bbox[0::2] = np.clip(bbox[0::2], 0, self.width) bbox[1::2] = np.clip(bbox[1::2], 0, self.height) x1, y1, x2, y2 = bbox w = np.maximum(x2 - x1, 1) h = np.maximum(y2 - y1, 1) if len(self.masks) == 0: cropped_masks = np.empty((0, h, w), dtype=np.uint8) else: cropped_masks = self.masks[:, y1:y1 + h, x1:x1 + w] return BitmapMasks(cropped_masks, h, w) def crop_and_resize(self, bboxes, out_shape, inds, device='cpu', interpolation='bilinear'): """See :func:`BaseInstanceMasks.crop_and_resize`.""" if len(self.masks) == 0: empty_masks = np.empty((0, *out_shape), dtype=np.uint8) return BitmapMasks(empty_masks, *out_shape) # convert bboxes to tensor if isinstance(bboxes, np.ndarray): bboxes = torch.from_numpy(bboxes).to(device=device) if isinstance(inds, np.ndarray): inds = torch.from_numpy(inds).to(device=device) num_bbox = bboxes.shape[0] fake_inds = torch.arange( num_bbox, device=device).to(dtype=bboxes.dtype)[:, None] rois = torch.cat([fake_inds, bboxes], dim=1) # Nx5 rois = rois.to(device=device) if num_bbox > 0: gt_masks_th = torch.from_numpy(self.masks).to(device).index_select( 0, inds).to(dtype=rois.dtype) targets = roi_align(gt_masks_th[:, None, :, :], rois, out_shape, 1.0, 0, 'avg', True).squeeze(1) resized_masks = (targets >= 0.5).cpu().numpy() else: resized_masks = [] return BitmapMasks(resized_masks, *out_shape) def expand(self, expanded_h, expanded_w, top, left): """See :func:`BaseInstanceMasks.expand`.""" if len(self.masks) == 0: expanded_mask = np.empty((0, expanded_h, expanded_w), dtype=np.uint8) else: expanded_mask = np.zeros((len(self), expanded_h, expanded_w), dtype=np.uint8) expanded_mask[:, top:top + self.height, left:left + self.width] = self.masks return BitmapMasks(expanded_mask, expanded_h, expanded_w) @property def areas(self): """See :py:attr:`BaseInstanceMasks.areas`.""" return self.masks.sum((1, 2)) def to_ndarray(self): """See :func:`BaseInstanceMasks.to_ndarray`.""" return self.masks def to_tensor(self, dtype, device): """See :func:`BaseInstanceMasks.to_tensor`.""" return torch.tensor(self.masks, dtype=dtype, device=device) class PolygonMasks(BaseInstanceMasks): """This class represents masks in the form of polygons. Polygons is a list of three levels. The first level of the list corresponds to objects, the second level to the polys that compose the object, the third level to the poly coordinates Args: masks (list[list[ndarray]]): The first level of the list corresponds to objects, the second level to the polys that compose the object, the third level to the poly coordinates height (int): height of masks width (int): width of masks """ def __init__(self, masks, height, width): assert isinstance(masks, list) if len(masks) > 0: assert isinstance(masks[0], list) assert isinstance(masks[0][0], np.ndarray) self.height = height self.width = width self.masks = masks def __getitem__(self, index): """Index the polygon masks. Args: index (ndarray | List): The indices. Returns: :obj:`PolygonMasks`: The indexed polygon masks. """ if isinstance(index, np.ndarray): index = index.tolist() if isinstance(index, list): masks = [self.masks[i] for i in index] else: try: masks = self.masks[index] except Exception: raise ValueError( f'Unsupported input of type {type(index)} for indexing!') if isinstance(masks[0], np.ndarray): masks = [masks] # ensure a list of three levels return PolygonMasks(masks, self.height, self.width) def __iter__(self): return iter(self.masks) def __repr__(self): s = self.__class__.__name__ + '(' s += f'num_masks={len(self.masks)}, ' s += f'height={self.height}, ' s += f'width={self.width})' return s def __len__(self): """Number of masks.""" return len(self.masks) def rescale(self, scale, interpolation=None): """see :func:`BaseInstanceMasks.rescale`""" new_w, new_h = mmcv.rescale_size((self.width, self.height), scale) if len(self.masks) == 0: rescaled_masks = PolygonMasks([], new_h, new_w) else: rescaled_masks = self.resize((new_h, new_w)) return rescaled_masks def resize(self, out_shape, interpolation=None): """see :func:`BaseInstanceMasks.resize`""" if len(self.masks) == 0: resized_masks = PolygonMasks([], *out_shape) else: h_scale = out_shape[0] / self.height w_scale = out_shape[1] / self.width resized_masks = [] for poly_per_obj in self.masks: resized_poly = [] for p in poly_per_obj: p = p.copy() p[0::2] *= w_scale p[1::2] *= h_scale resized_poly.append(p) resized_masks.append(resized_poly) resized_masks = PolygonMasks(resized_masks, *out_shape) return resized_masks def flip(self, flip_direction='horizontal'): """see :func:`BaseInstanceMasks.flip`""" assert flip_direction in ('horizontal', 'vertical') if len(self.masks) == 0: flipped_masks = PolygonMasks([], self.height, self.width) else: if flip_direction == 'horizontal': dim = self.width idx = 0 else: dim = self.height idx = 1 flipped_masks = [] for poly_per_obj in self.masks: flipped_poly_per_obj = [] for p in poly_per_obj: p = p.copy() p[idx::2] = dim - p[idx::2] flipped_poly_per_obj.append(p) flipped_masks.append(flipped_poly_per_obj) flipped_masks = PolygonMasks(flipped_masks, self.height, self.width) return flipped_masks def crop(self, bbox): """see :func:`BaseInstanceMasks.crop`""" assert isinstance(bbox, np.ndarray) assert bbox.ndim == 1 # clip the boundary bbox = bbox.copy() bbox[0::2] = np.clip(bbox[0::2], 0, self.width) bbox[1::2] = np.clip(bbox[1::2], 0, self.height) x1, y1, x2, y2 = bbox w = np.maximum(x2 - x1, 1) h = np.maximum(y2 - y1, 1) if len(self.masks) == 0: cropped_masks = PolygonMasks([], h, w) else: cropped_masks = [] for poly_per_obj in self.masks: cropped_poly_per_obj = [] for p in poly_per_obj: # pycocotools will clip the boundary p = p.copy() p[0::2] -= bbox[0] p[1::2] -= bbox[1] cropped_poly_per_obj.append(p) cropped_masks.append(cropped_poly_per_obj) cropped_masks = PolygonMasks(cropped_masks, h, w) return cropped_masks def pad(self, out_shape, pad_val=0): """padding has no effect on polygons`""" return PolygonMasks(self.masks, *out_shape) def expand(self, *args, **kwargs): """TODO: Add expand for polygon""" raise NotImplementedError def crop_and_resize(self, bboxes, out_shape, inds, device='cpu', interpolation='bilinear'): """see :func:`BaseInstanceMasks.crop_and_resize`""" out_h, out_w = out_shape if len(self.masks) == 0: return PolygonMasks([], out_h, out_w) resized_masks = [] for i in range(len(bboxes)): mask = self.masks[inds[i]] bbox = bboxes[i, :] x1, y1, x2, y2 = bbox w = np.maximum(x2 - x1, 1) h = np.maximum(y2 - y1, 1) h_scale = out_h / max(h, 0.1) # avoid too large scale w_scale = out_w / max(w, 0.1) resized_mask = [] for p in mask: p = p.copy() # crop # pycocotools will clip the boundary p[0::2] -= bbox[0] p[1::2] -= bbox[1] # resize p[0::2] *= w_scale p[1::2] *= h_scale resized_mask.append(p) resized_masks.append(resized_mask) return PolygonMasks(resized_masks, *out_shape) def to_bitmap(self): """convert polygon masks to bitmap masks.""" bitmap_masks = self.to_ndarray() return BitmapMasks(bitmap_masks, self.height, self.width) @property def areas(self): """Compute areas of masks. This func is modified from `detectron2 <https://github.com/facebookresearch/detectron2/blob/ffff8acc35ea88ad1cb1806ab0f00b4c1c5dbfd9/detectron2/structures/masks.py#L387>`_. The function only works with Polygons using the shoelace formula. Return: ndarray: areas of each instance """ # noqa: W501 area = [] for polygons_per_obj in self.masks: area_per_obj = 0 for p in polygons_per_obj: area_per_obj += self._polygon_area(p[0::2], p[1::2]) area.append(area_per_obj) return np.asarray(area) def _polygon_area(self, x, y): """Compute the area of a component of a polygon. Using the shoelace formula: https://stackoverflow.com/questions/24467972/calculate-area-of-polygon-given-x-y-coordinates Args: x (ndarray): x coordinates of the component y (ndarray): y coordinates of the component Return: float: the are of the component """ # noqa: 501 return 0.5 * np.abs( np.dot(x, np.roll(y, 1)) - np.dot(y, np.roll(x, 1))) def to_ndarray(self): """Convert masks to the format of ndarray.""" if len(self.masks) == 0: return np.empty((0, self.height, self.width), dtype=np.uint8) bitmap_masks = [] for poly_per_obj in self.masks: bitmap_masks.append( polygon_to_bitmap(poly_per_obj, self.height, self.width)) return np.stack(bitmap_masks) def to_tensor(self, dtype, device): """See :func:`BaseInstanceMasks.to_tensor`.""" if len(self.masks) == 0: return torch.empty((0, self.height, self.width), dtype=dtype, device=device) ndarray_masks = self.to_ndarray() return torch.tensor(ndarray_masks, dtype=dtype, device=device) def polygon_to_bitmap(polygons, height, width): """Convert masks from the form of polygons to bitmaps. Args: polygons (list[ndarray]): masks in polygon representation height (int): mask height width (int): mask width Return: ndarray: the converted masks in bitmap representation """ rles = maskUtils.frPyObjects(polygons, height, width) rle = maskUtils.merge(rles) bitmap_mask = maskUtils.decode(rle).astype(np.bool) return bitmap_mask
1
21,146
Modifications are also needed for PolygonMask.
open-mmlab-mmdetection
py
@@ -3,12 +3,9 @@ using System; using System.Net; -using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.Server.Kestrel.Core; -using Microsoft.AspNetCore.Server.Kestrel.Transport.Abstractions.Internal; +using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http; using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; namespace PlatformBenchmarks {
1
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Net; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Server.Kestrel.Core; using Microsoft.AspNetCore.Server.Kestrel.Transport.Abstractions.Internal; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace PlatformBenchmarks { public class Program { public static void Main(string[] args) { BuildWebHost(args).Run(); } public static IWebHost BuildWebHost(string[] args) { var config = new ConfigurationBuilder() .AddEnvironmentVariables(prefix: "ASPNETCORE_") .AddCommandLine(args) .Build(); var host = new WebHostBuilder() .UseBenchmarksConfiguration(config) .UseKestrel((context, options) => { IPEndPoint endPoint = context.Configuration.CreateIPEndPoint(); options.Listen(endPoint, builder => { builder.UseHttpApplication<BenchmarkApplication>(); }); }) .UseStartup<Startup>() .Build(); return host; } } }
1
15,690
Does this really make a difference?
aspnet-KestrelHttpServer
.cs
@@ -70,6 +70,9 @@ public class TestRandomFlRTGCloud extends SolrCloudTestCase { /** Always included in fl so we can vet what doc we're looking at */ private static final FlValidator ID_VALIDATOR = new SimpleFieldValueValidator("id"); + + /** Since nested documents are not tested, when _root_ is declared in schema, it is always the same as id */ + private static final FlValidator ROOT_VALIDATOR = new RenameFieldValueValidator("id" , "_root_"); /** * Types of things we will randomly ask for in fl param, and validate in response docs.
1
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.solr.cloud; import java.io.IOException; import java.lang.invoke.MethodHandles; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.TreeSet; import org.apache.commons.io.FilenameUtils; import org.apache.lucene.util.TestUtil; import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.embedded.JettySolrRunner; import org.apache.solr.client.solrj.impl.CloudSolrClient; import org.apache.solr.client.solrj.impl.HttpSolrClient; import org.apache.solr.client.solrj.request.CollectionAdminRequest; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.SolrDocumentList; import org.apache.solr.common.SolrInputDocument; import org.apache.solr.common.params.ModifiableSolrParams; import org.apache.solr.common.params.SolrParams; import org.apache.solr.common.util.NamedList; import org.apache.solr.response.transform.DocTransformer; import org.apache.solr.response.transform.RawValueTransformerFactory; import org.apache.solr.response.transform.TransformerFactory; import org.apache.solr.util.RandomizeSSL; import org.junit.AfterClass; import org.junit.BeforeClass; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** @see TestCloudPseudoReturnFields */ @RandomizeSSL(clientAuth=0.0,reason="client auth uses too much RAM") public class TestRandomFlRTGCloud extends SolrCloudTestCase { private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); private static final String DEBUG_LABEL = MethodHandles.lookup().lookupClass().getName(); private static final String COLLECTION_NAME = DEBUG_LABEL + "_collection"; /** A basic client for operations at the cloud level, default collection will be set */ private static CloudSolrClient CLOUD_CLIENT; /** One client per node */ private static ArrayList<HttpSolrClient> CLIENTS = new ArrayList<>(5); /** Always included in fl so we can vet what doc we're looking at */ private static final FlValidator ID_VALIDATOR = new SimpleFieldValueValidator("id"); /** * Types of things we will randomly ask for in fl param, and validate in response docs. * * @see #addRandomFlValidators */ private static final List<FlValidator> FL_VALIDATORS = Collections.unmodifiableList (Arrays.<FlValidator>asList( new GlobValidator("*"), new GlobValidator("*_i"), new GlobValidator("*_s"), new GlobValidator("a*"), new DocIdValidator(), new DocIdValidator("my_docid_alias"), new ShardValidator(), new ShardValidator("my_shard_alias"), new ValueAugmenterValidator(42), new ValueAugmenterValidator(1976, "val_alias"), // new RenameFieldValueValidator("id", "my_id_alias"), new SimpleFieldValueValidator("aaa_i"), new RenameFieldValueValidator("bbb_i", "my_int_field_alias"), new SimpleFieldValueValidator("ccc_s"), new RenameFieldValueValidator("ddd_s", "my_str_field_alias"), // // SOLR-9376: RawValueTransformerFactory doesn't work in cloud mode // // new RawFieldValueValidator("json", "eee_s", "my_json_field_alias"), // new RawFieldValueValidator("json", "fff_s"), // new RawFieldValueValidator("xml", "ggg_s", "my_xml_field_alias"), // new RawFieldValueValidator("xml", "hhh_s"), // new NotIncludedValidator("bogus_unused_field_ss"), new NotIncludedValidator("bogus_alias","bogus_alias:other_bogus_field_i"), new NotIncludedValidator("bogus_raw_alias","bogus_raw_alias:[xml f=bogus_raw_field_ss]"), // new FunctionValidator("aaa_i"), // fq field new FunctionValidator("aaa_i", "func_aaa_alias"), new GeoTransformerValidator("geo_1_srpt"), new GeoTransformerValidator("geo_2_srpt","my_geo_alias"), new ExplainValidator(), new ExplainValidator("explain_alias"), new SubQueryValidator(), new NotIncludedValidator("score"), new NotIncludedValidator("score","score_alias:score"))); @BeforeClass public static void createMiniSolrCloudCluster() throws Exception { // 50% runs use single node/shard a FL_VALIDATORS with all validators known to work on single node // 50% runs use multi node/shard with FL_VALIDATORS only containing stuff that works in cloud final boolean singleCoreMode = random().nextBoolean(); // (asuming multi core multi replicas shouldn't matter (assuming multi node) ... final int repFactor = singleCoreMode ? 1 : (usually() ? 1 : 2); // ... but we definitely want to ensure forwarded requests to other shards work ... final int numShards = singleCoreMode ? 1 : 2; // ... including some forwarded requests from nodes not hosting a shard final int numNodes = 1 + (singleCoreMode ? 0 : (numShards * repFactor)); final String configName = DEBUG_LABEL + "_config-set"; final Path configDir = Paths.get(TEST_HOME(), "collection1", "conf"); configureCluster(numNodes).addConfig(configName, configDir).configure(); CLOUD_CLIENT = cluster.getSolrClient(); CLOUD_CLIENT.setDefaultCollection(COLLECTION_NAME); CollectionAdminRequest.createCollection(COLLECTION_NAME, configName, numShards, repFactor) .withProperty("config", "solrconfig-tlog.xml") .withProperty("schema", "schema-psuedo-fields.xml") .process(CLOUD_CLIENT); waitForRecoveriesToFinish(CLOUD_CLIENT); for (JettySolrRunner jetty : cluster.getJettySolrRunners()) { CLIENTS.add(getHttpSolrClient(jetty.getBaseUrl() + "/" + COLLECTION_NAME + "/")); } } @AfterClass private static void afterClass() throws Exception { CLOUD_CLIENT.close(); CLOUD_CLIENT = null; for (HttpSolrClient client : CLIENTS) { client.close(); } CLIENTS = null; } /** * Tests that all TransformerFactories that are implicitly provided by Solr are tested in this class * * @see FlValidator#getDefaultTransformerFactoryName * @see #FL_VALIDATORS * @see TransformerFactory#defaultFactories */ public void testCoverage() throws Exception { final Set<String> implicit = new LinkedHashSet<>(); for (String t : TransformerFactory.defaultFactories.keySet()) { implicit.add(t); } final Set<String> covered = new LinkedHashSet<>(); for (FlValidator v : FL_VALIDATORS) { String t = v.getDefaultTransformerFactoryName(); if (null != t) { covered.add(t); } } // items should only be added to this list if it's known that they do not work with RTG // and a specific Jira for fixing this is listed as a comment final List<String> knownBugs = Arrays.asList ( "xml","json", // SOLR-9376 "child" // way to complicatd to vet with this test, see SOLR-9379 instead ); for (String buggy : knownBugs) { assertFalse(buggy + " is listed as a being a known bug, " + "but it exists in the set of 'covered' TransformerFactories", covered.contains(buggy)); assertTrue(buggy + " is listed as a known bug, " + "but it does not even exist in the set of 'implicit' TransformerFactories", implicit.remove(buggy)); } implicit.removeAll(covered); assertEquals("Some implicit TransformerFactories are not yet tested by this class: " + implicit, 0, implicit.size()); } public void testRandomizedUpdatesAndRTGs() throws Exception { final int maxNumDocs = atLeast(100); final int numSeedDocs = random().nextInt(maxNumDocs / 10); // at most ~10% of the max possible docs final int numIters = atLeast(maxNumDocs * 10); final SolrInputDocument[] knownDocs = new SolrInputDocument[maxNumDocs]; log.info("Starting {} iters by seeding {} of {} max docs", numIters, numSeedDocs, maxNumDocs); int itersSinceLastCommit = 0; for (int i = 0; i < numIters; i++) { itersSinceLastCommit = maybeCommit(random(), itersSinceLastCommit, numIters); if (i < numSeedDocs) { // first N iters all we worry about is seeding knownDocs[i] = addRandomDocument(i); } else { assertOneIter(knownDocs); } } } /** * Randomly chooses to do a commit, where the probability of doing so increases the longer it's been since * a commit was done. * * @returns <code>0</code> if a commit was done, else <code>itersSinceLastCommit + 1</code> */ private static int maybeCommit(final Random rand, final int itersSinceLastCommit, final int numIters) throws IOException, SolrServerException { final float threshold = itersSinceLastCommit / numIters; if (rand.nextFloat() < threshold) { log.info("COMMIT"); assertEquals(0, getRandClient(rand).commit().getStatus()); return 0; } return itersSinceLastCommit + 1; } private void assertOneIter(final SolrInputDocument[] knownDocs) throws IOException, SolrServerException { // we want to occasionally test more then one doc per RTG final int numDocsThisIter = TestUtil.nextInt(random(), 1, atLeast(2)); int numDocsThisIterThatExist = 0; // pick some random docIds for this iteration and ... final int[] docIds = new int[numDocsThisIter]; for (int i = 0; i < numDocsThisIter; i++) { docIds[i] = random().nextInt(knownDocs.length); if (null != knownDocs[docIds[i]]) { // ...check how many already exist numDocsThisIterThatExist++; } } // we want our RTG requests to occasionally include missing/deleted docs, // but that's not the primary focus of the test, so weight the odds accordingly if (random().nextInt(numDocsThisIter + 2) <= numDocsThisIterThatExist) { if (0 < TestUtil.nextInt(random(), 0, 13)) { log.info("RTG: numDocsThisIter={} numDocsThisIterThatExist={}, docIds={}", numDocsThisIter, numDocsThisIterThatExist, docIds); assertRTG(knownDocs, docIds); } else { // sporadically delete some docs instead of doing an RTG log.info("DEL: numDocsThisIter={} numDocsThisIterThatExist={}, docIds={}", numDocsThisIter, numDocsThisIterThatExist, docIds); assertDelete(knownDocs, docIds); } } else { log.info("UPD: numDocsThisIter={} numDocsThisIterThatExist={}, docIds={}", numDocsThisIter, numDocsThisIterThatExist, docIds); assertUpdate(knownDocs, docIds); } } /** * Does some random indexing of the specified docIds and adds them to knownDocs */ private void assertUpdate(final SolrInputDocument[] knownDocs, final int[] docIds) throws IOException, SolrServerException { for (final int docId : docIds) { // TODO: this method should also do some atomic update operations (ie: "inc" and "set") // (but make sure to eval the updates locally as well before modifying knownDocs) knownDocs[docId] = addRandomDocument(docId); } } /** * Deletes the docIds specified and asserts the results are valid, updateing knownDocs accordingly */ private void assertDelete(final SolrInputDocument[] knownDocs, final int[] docIds) throws IOException, SolrServerException { List<String> ids = new ArrayList<>(docIds.length); for (final int docId : docIds) { ids.add("" + docId); knownDocs[docId] = null; } assertEquals("Failed delete: " + docIds, 0, getRandClient(random()).deleteById(ids).getStatus()); } /** * Adds one randomly generated document with the specified docId, asserting success, and returns * the document added */ private SolrInputDocument addRandomDocument(final int docId) throws IOException, SolrServerException { final SolrClient client = getRandClient(random()); final SolrInputDocument doc = sdoc("id", "" + docId, "aaa_i", random().nextInt(), "bbb_i", random().nextInt(), // "ccc_s", TestUtil.randomSimpleString(random()), "ddd_s", TestUtil.randomSimpleString(random()), "eee_s", TestUtil.randomSimpleString(random()), "fff_s", TestUtil.randomSimpleString(random()), "ggg_s", TestUtil.randomSimpleString(random()), "hhh_s", TestUtil.randomSimpleString(random()), // "geo_1_srpt", GeoTransformerValidator.getValueForIndexing(random()), "geo_2_srpt", GeoTransformerValidator.getValueForIndexing(random()), // for testing subqueries "next_2_ids_ss", String.valueOf(docId + 1), "next_2_ids_ss", String.valueOf(docId + 2), // for testing prefix globbing "axx_i", random().nextInt(), "ayy_i", random().nextInt(), "azz_s", TestUtil.randomSimpleString(random())); log.info("ADD: {} = {}", docId, doc); assertEquals(0, client.add(doc).getStatus()); return doc; } /** * Does one or more RTG request for the specified docIds with a randomized fl &amp; fq params, asserting * that the returned document (if any) makes sense given the expected SolrInputDocuments */ private void assertRTG(final SolrInputDocument[] knownDocs, final int[] docIds) throws IOException, SolrServerException { final SolrClient client = getRandClient(random()); // NOTE: not using SolrClient.getById or getByIds because we want to force choice of "id" vs "ids" params final ModifiableSolrParams params = params("qt","/get"); // random fq -- nothing fancy, secondary concern for our test final Integer FQ_MAX = usually() ? null : random().nextInt(); if (null != FQ_MAX) { params.add("fq", "aaa_i:[* TO " + FQ_MAX + "]"); } final Set<FlValidator> validators = new LinkedHashSet<>(); validators.add(ID_VALIDATOR); // always include id so we can be confident which doc we're looking at addRandomFlValidators(random(), validators); FlValidator.addParams(validators, params); final List<String> idsToRequest = new ArrayList<>(docIds.length); final List<SolrInputDocument> docsToExpect = new ArrayList<>(docIds.length); for (int docId : docIds) { // every docId will be included in the request idsToRequest.add("" + docId); // only docs that should actually exist and match our (optional) filter will be expected in response if (null != knownDocs[docId]) { Integer filterVal = (Integer) knownDocs[docId].getFieldValue("aaa_i"); if (null == FQ_MAX || ((null != filterVal) && filterVal.intValue() <= FQ_MAX.intValue())) { docsToExpect.add(knownDocs[docId]); } } } // even w/only 1 docId requested, the response format can vary depending on how we request it final boolean askForList = random().nextBoolean() || (1 != idsToRequest.size()); if (askForList) { if (1 == idsToRequest.size()) { // have to be careful not to try to use "multi" 'id' params with only 1 docId // with a single docId, the only way to ask for a list is with the "ids" param params.add("ids", idsToRequest.get(0)); } else { if (random().nextBoolean()) { // each id in its own param for (String id : idsToRequest) { params.add("id",id); } } else { // add one or more comma separated ids params params.add(buildCommaSepParams(random(), "ids", idsToRequest)); } } } else { assert 1 == idsToRequest.size(); params.add("id",idsToRequest.get(0)); } final QueryResponse rsp = client.query(params); assertNotNull(params.toString(), rsp); final SolrDocumentList docs = getDocsFromRTGResponse(askForList, rsp); assertNotNull(params + " => " + rsp, docs); assertEquals("num docs mismatch: " + params + " => " + docsToExpect + " vs " + docs, docsToExpect.size(), docs.size()); // NOTE: RTG makes no garuntees about the order docs will be returned in when multi requested for (SolrDocument actual : docs) { try { int actualId = assertParseInt("id", actual.getFirstValue("id")); final SolrInputDocument expected = knownDocs[actualId]; assertNotNull("expected null doc but RTG returned: " + actual, expected); Set<String> expectedFieldNames = new TreeSet<>(); for (FlValidator v : validators) { expectedFieldNames.addAll(v.assertRTGResults(validators, expected, actual)); } // ensure only expected field names are in the actual document Set<String> actualFieldNames = new TreeSet<>(actual.getFieldNames()); assertEquals("Actual field names returned differs from expected", expectedFieldNames, actualFieldNames); } catch (AssertionError ae) { throw new AssertionError(params + " => " + actual + ": " + ae.getMessage(), ae); } } } /** * trivial helper method to deal with diff response structure between using a single 'id' param vs * 2 or more 'id' params (or 1 or more 'ids' params). * * @return List from response, or a synthetic one created from single response doc if * <code>expectList</code> was false; May be empty; May be null if response included null list. */ private static SolrDocumentList getDocsFromRTGResponse(final boolean expectList, final QueryResponse rsp) { if (expectList) { return rsp.getResults(); } // else: expect single doc, make our own list... final SolrDocumentList result = new SolrDocumentList(); NamedList<Object> raw = rsp.getResponse(); Object doc = raw.get("doc"); if (null != doc) { result.add((SolrDocument) doc); result.setNumFound(1); } return result; } /** * returns a random SolrClient -- either a CloudSolrClient, or an HttpSolrClient pointed * at a node in our cluster */ public static SolrClient getRandClient(Random rand) { int numClients = CLIENTS.size(); int idx = TestUtil.nextInt(rand, 0, numClients); return (idx == numClients) ? CLOUD_CLIENT : CLIENTS.get(idx); } public static void waitForRecoveriesToFinish(CloudSolrClient client) throws Exception { assert null != client.getDefaultCollection(); AbstractDistribZkTestBase.waitForRecoveriesToFinish(client.getDefaultCollection(), client.getZkStateReader(), true, true, 330); } /** * Abstraction for diff types of things that can be added to an 'fl' param that can validate * the results are correct compared to an expected SolrInputDocument */ private interface FlValidator { /** * Given a list of FlValidators, adds one or more fl params that corrispond to the entire set, * as well as any other special case top level params required by the validators. */ public static void addParams(final Collection<FlValidator> validators, final ModifiableSolrParams params) { final List<String> fls = new ArrayList<>(validators.size()); for (FlValidator v : validators) { params.add(v.getExtraRequestParams()); fls.add(v.getFlParam()); } params.add(buildCommaSepParams(random(), "fl", fls)); } /** * Indicates if this validator is for a transformer that returns true from * {@link DocTransformer#needsSolrIndexSearcher}. Other validators for transformers that * do <em>not</em> require a re-opened searcher (but may have slightly diff behavior depending * on wether a doc comesfrom the index or from the update log) may use this information to * decide wether they wish to enforce stricter assertions on the resulting document. * * The default implementation always returns <code>false</code> * * @see DocIdValidator */ public default boolean requiresRealtimeSearcherReOpen() { return false; } /** * the name of a transformer listed in {@link TransformerFactory#defaultFactories} that this validator * corrisponds to, or null if not applicable. Used for testing coverage of * Solr's implicitly supported transformers. * * Default behavior is to return null * @see #testCoverage */ public default String getDefaultTransformerFactoryName() { return null; } /** * Any special case params that must be added to the request for this validator */ public default SolrParams getExtraRequestParams() { return params(); } /** * Must return a non null String that can be used in an fl param -- either by itself, * or with other items separated by commas */ public String getFlParam(); /** * Given the expected document and the actual document returned from an RTG, this method * should assert that relative to what {@link #getFlParam} returns, the actual document contained * what it should relative to the expected document. * * @param validators all validators in use for this request, including the current one * @param expected a document containing the expected fields &amp; values that should be in the index * @param actual A document that was returned by an RTG request * @return A set of "field names" in the actual document that this validator expected. */ public Collection<String> assertRTGResults(final Collection<FlValidator> validators, final SolrInputDocument expected, final SolrDocument actual); } /** * Some validators behave in a way that "suppresses" real fields even when they would otherwise match a glob * @see GlobValidator */ private interface SuppressRealFields { public Set<String> getSuppressedFields(); } private abstract static class FieldValueValidator implements FlValidator { protected final String expectedFieldName; protected final String actualFieldName; public FieldValueValidator(final String expectedFieldName, final String actualFieldName) { this.expectedFieldName = expectedFieldName; this.actualFieldName = actualFieldName; } public abstract String getFlParam(); public Collection<String> assertRTGResults(final Collection<FlValidator> validators, final SolrInputDocument expected, final SolrDocument actual) { assertEquals(expectedFieldName + " vs " + actualFieldName, expected.getFieldValue(expectedFieldName), actual.getFirstValue(actualFieldName)); return Collections.<String>singleton(actualFieldName); } } private static class SimpleFieldValueValidator extends FieldValueValidator { public SimpleFieldValueValidator(final String fieldName) { super(fieldName, fieldName); } public String getFlParam() { return expectedFieldName; } } private static class RenameFieldValueValidator extends FieldValueValidator implements SuppressRealFields { public RenameFieldValueValidator(final String origFieldName, final String alias) { super(origFieldName, alias); } public String getFlParam() { return actualFieldName + ":" + expectedFieldName; } public Set<String> getSuppressedFields() { return Collections.singleton(expectedFieldName); } } /** * Validator for {@link RawValueTransformerFactory} * * This validator is fairly weak, because it doesn't do anything to verify the conditional logic * in RawValueTransformerFactory realted to the output format -- but that's out of the scope of * this randomized testing. * * What we're primarily concerned with is that the transformer does it's job and puts the string * in the response, regardless of cloud/RTG/uncommited state of the document. */ private static class RawFieldValueValidator extends RenameFieldValueValidator { final String type; final String alias; public RawFieldValueValidator(final String type, final String fieldName, final String alias) { // transformer is weird, default result key doesn't care what params are used... super(fieldName, null == alias ? "["+type+"]" : alias); this.type = type; this.alias = alias; } public RawFieldValueValidator(final String type, final String fieldName) { this(type, fieldName, null); } public String getFlParam() { return (null == alias ? "" : (alias + ":")) + "[" + type + " f=" + expectedFieldName + "]"; } public String getDefaultTransformerFactoryName() { return type; } } /** * enforces that a valid <code>[docid]</code> is present in the response, possibly using a * resultKey alias. By default the only validation of docId values is that they are an integer * greater than or equal to <code>-1</code> -- but if any other validator in use returns true * from {@link #requiresRealtimeSearcherReOpen} then the constraint is tightened and values must * be greater than or equal to <code>0</code> */ private static class DocIdValidator implements FlValidator { private static final String NAME = "docid"; private static final String USAGE = "["+NAME+"]"; private final String resultKey; public DocIdValidator(final String resultKey) { this.resultKey = resultKey; } public DocIdValidator() { this(USAGE); } public String getDefaultTransformerFactoryName() { return NAME; } public String getFlParam() { return USAGE.equals(resultKey) ? resultKey : resultKey+":"+USAGE; } public Collection<String> assertRTGResults(final Collection<FlValidator> validators, final SolrInputDocument expected, final SolrDocument actual) { final Object value = actual.getFirstValue(resultKey); assertNotNull(getFlParam() + " => no value in actual doc", value); assertTrue(USAGE + " must be an Integer: " + value, value instanceof Integer); int minValidDocId = -1; // if it comes from update log for (FlValidator other : validators) { if (other.requiresRealtimeSearcherReOpen()) { minValidDocId = 0; break; } } assertTrue(USAGE + " must be >= " + minValidDocId + ": " + value, minValidDocId <= ((Integer)value).intValue()); return Collections.<String>singleton(resultKey); } } /** Trivial validator of ShardAugmenterFactory */ private static class ShardValidator implements FlValidator { private static final String NAME = "shard"; private static final String USAGE = "["+NAME+"]"; private final String resultKey; public ShardValidator(final String resultKey) { this.resultKey = resultKey; } public ShardValidator() { this(USAGE); } public String getDefaultTransformerFactoryName() { return NAME; } public String getFlParam() { return USAGE.equals(resultKey) ? resultKey : resultKey+":"+USAGE; } public Collection<String> assertRTGResults(final Collection<FlValidator> validators, final SolrInputDocument expected, final SolrDocument actual) { final Object value = actual.getFirstValue(resultKey); assertNotNull(getFlParam() + " => no value in actual doc", value); assertTrue(USAGE + " must be an String: " + value, value instanceof String); // trivial sanity check assertFalse(USAGE + " => blank string", value.toString().trim().isEmpty()); return Collections.<String>singleton(resultKey); } } /** Trivial validator of ValueAugmenter */ private static class ValueAugmenterValidator implements FlValidator { private static final String NAME = "value"; private static String trans(final int value) { return "[" + NAME + " v=" + value + " t=int]"; } private final String resultKey; private final String fl; private final Integer expectedVal; private ValueAugmenterValidator(final String fl, final int expectedVal, final String resultKey) { this.resultKey = resultKey; this.expectedVal = expectedVal; this.fl = fl; } public ValueAugmenterValidator(final int expectedVal, final String resultKey) { this(resultKey + ":" +trans(expectedVal), expectedVal, resultKey); } public ValueAugmenterValidator(final int expectedVal) { // value transformer is weird, default result key doesn't care what params are used... this(trans(expectedVal), expectedVal, "["+NAME+"]"); } public String getDefaultTransformerFactoryName() { return NAME; } public String getFlParam() { return fl; } public Collection<String> assertRTGResults(final Collection<FlValidator> validators, final SolrInputDocument expected, final SolrDocument actual) { final Object actualVal = actual.getFirstValue(resultKey); assertNotNull(getFlParam() + " => no value in actual doc", actualVal); assertEquals(getFlParam(), expectedVal, actualVal); return Collections.<String>singleton(resultKey); } } /** Trivial validator of a ValueSourceAugmenter */ private static class FunctionValidator implements FlValidator { private static String func(String fieldName) { return "add(1.3,sub("+fieldName+","+fieldName+"))"; } protected final String fl; protected final String resultKey; protected final String fieldName; public FunctionValidator(final String fieldName) { this(func(fieldName), fieldName, func(fieldName)); } public FunctionValidator(final String fieldName, final String resultKey) { this(resultKey + ":" + func(fieldName), fieldName, resultKey); } private FunctionValidator(final String fl, final String fieldName, final String resultKey) { this.fl = fl; this.resultKey = resultKey; this.fieldName = fieldName; } /** always returns true */ public boolean requiresRealtimeSearcherReOpen() { return true; } public String getFlParam() { return fl; } public Collection<String> assertRTGResults(final Collection<FlValidator> validators, final SolrInputDocument expected, final SolrDocument actual) { final Object origVal = expected.getFieldValue(fieldName); assertTrue("this validator only works on numeric fields: " + origVal, origVal instanceof Number); assertEquals(fl, 1.3F, actual.getFirstValue(resultKey)); return Collections.<String>singleton(resultKey); } } /** * Trivial validator of a SubQueryAugmenter. * * This validator ignores 90% of the features/complexity * of SubQueryAugmenter, and instead just focuses on the basics of: * <ul> * <li>do a subquery for docs where SUBQ_FIELD contains the id of the top level doc</li> * <li>verify that any subquery match is expected based on indexing pattern</li> * </ul> */ private static class SubQueryValidator implements FlValidator { // HACK to work around SOLR-9396... // // we're using "id" (and only "id") in the subquery.q as a workarround limitation in // "$rows.foo" parsing -- it only works reliably if "foo" is in fl, so we only use "$rows.id", // which we know is in every request (and is a valid integer) public final static String NAME = "subquery"; public final static String SUBQ_KEY = "subq"; public final static String SUBQ_FIELD = "next_2_ids_i"; public String getFlParam() { return SUBQ_KEY+":["+NAME+"]"; } public Collection<String> assertRTGResults(final Collection<FlValidator> validators, final SolrInputDocument expected, final SolrDocument actual) { final int compVal = assertParseInt("expected id", expected.getFieldValue("id")); final Object actualVal = actual.getFieldValue(SUBQ_KEY); assertTrue("Expected a doclist: " + actualVal, actualVal instanceof SolrDocumentList); assertTrue("should be at most 2 docs in doc list: " + actualVal, ((SolrDocumentList) actualVal).getNumFound() <= 2); for (SolrDocument subDoc : (SolrDocumentList) actualVal) { final int subDocIdVal = assertParseInt("subquery id", subDoc.getFirstValue("id")); assertTrue("subDocId="+subDocIdVal+" not in valid range for id="+compVal+" (expected " + (compVal-1) + " or " + (compVal-2) + ")", ((subDocIdVal < compVal) && ((compVal-2) <= subDocIdVal))); } return Collections.<String>singleton(SUBQ_KEY); } public String getDefaultTransformerFactoryName() { return NAME; } public SolrParams getExtraRequestParams() { return params(SubQueryValidator.SUBQ_KEY + ".q", "{!field f=" + SubQueryValidator.SUBQ_FIELD + " v=$row.id}"); } } /** Trivial validator of a GeoTransformer */ private static class GeoTransformerValidator implements FlValidator, SuppressRealFields{ private static final String NAME = "geo"; /** * we're not worried about testing the actual geo parsing/formatting of values, * just that the transformer gets called with the expected field value. * so have a small set of fixed input values we use when indexing docs, * and the expected output for each */ private static final Map<String,String> VALUES = new HashMap<>(); /** * The set of legal field values this validator is willing to test as a list so we can * reliably index into it with random ints */ private static final List<String> ALLOWED_FIELD_VALUES; static { for (int i = -42; i < 66; i+=13) { VALUES.put("POINT( 42 "+i+" )", "{\"type\":\"Point\",\"coordinates\":[42,"+i+"]}"); } ALLOWED_FIELD_VALUES = Collections.unmodifiableList(new ArrayList<>(VALUES.keySet())); } /** * returns a random field value usable when indexing a document that this validator will * be able to handle. */ public static String getValueForIndexing(final Random rand) { return ALLOWED_FIELD_VALUES.get(rand.nextInt(ALLOWED_FIELD_VALUES.size())); } private static String trans(String fieldName) { return "["+NAME+" f="+fieldName+"]"; } protected final String fl; protected final String resultKey; protected final String fieldName; public GeoTransformerValidator(final String fieldName) { // geo transformer is weird, default result key doesn't care what params are used... this(trans(fieldName), fieldName, "["+NAME+"]"); } public GeoTransformerValidator(final String fieldName, final String resultKey) { this(resultKey + ":" + trans(fieldName), fieldName, resultKey); } private GeoTransformerValidator(final String fl, final String fieldName, final String resultKey) { this.fl = fl; this.resultKey = resultKey; this.fieldName = fieldName; } public String getDefaultTransformerFactoryName() { return NAME; } public String getFlParam() { return fl; } public Collection<String> assertRTGResults(final Collection<FlValidator> validators, final SolrInputDocument expected, final SolrDocument actual) { final Object origVal = expected.getFieldValue(fieldName); assertTrue(fl + ": orig field value is not supported: " + origVal, VALUES.containsKey(origVal)); assertEquals(fl, VALUES.get(origVal), actual.getFirstValue(resultKey)); return Collections.<String>singleton(resultKey); } public Set<String> getSuppressedFields() { return Collections.singleton(fieldName); } } /** * Glob based validator. * This class checks that every field in the expected doc exists in the actual doc with the expected * value -- with special exceptions for fields that are "suppressed" (usually via an alias) * * By design, fields that are aliased are "moved" unless the original field name was explicitly included * in the fl, globs don't count. * * @see RenameFieldValueValidator */ private static class GlobValidator implements FlValidator { private final String glob; public GlobValidator(final String glob) { this.glob = glob; } private final Set<String> matchingFieldsCache = new LinkedHashSet<>(); public String getFlParam() { return glob; } private boolean matchesGlob(final String fieldName) { if ( FilenameUtils.wildcardMatch(fieldName, glob) ) { matchingFieldsCache.add(fieldName); // Don't calculate it again return true; } return false; } public Collection<String> assertRTGResults(final Collection<FlValidator> validators, final SolrInputDocument expected, final SolrDocument actual) { final Set<String> renamed = new LinkedHashSet<>(validators.size()); for (FlValidator v : validators) { if (v instanceof SuppressRealFields) { renamed.addAll(((SuppressRealFields)v).getSuppressedFields()); } } // every real field name matching the glob that is not renamed should be in the results Set<String> result = new LinkedHashSet<>(expected.getFieldNames().size()); for (String f : expected.getFieldNames()) { if ( matchesGlob(f) && (! renamed.contains(f) ) ) { result.add(f); assertEquals(glob + " => " + f, expected.getFieldValue(f), actual.getFirstValue(f)); } } return result; } } /** * for things like "score" and "[explain]" where we explicitly expect what we ask for in the fl * to <b>not</b> be returned when using RTG. */ private static class NotIncludedValidator implements FlValidator { private final String fieldName; private final String fl; public NotIncludedValidator(final String fl) { this(fl, fl); } public NotIncludedValidator(final String fieldName, final String fl) { this.fieldName = fieldName; this.fl = fl; } public String getFlParam() { return fl; } public Collection<String> assertRTGResults(final Collection<FlValidator> validators, final SolrInputDocument expected, final SolrDocument actual) { assertEquals(fl, null, actual.getFirstValue(fieldName)); return Collections.emptySet(); } } /** explain should always be ignored when using RTG */ private static class ExplainValidator extends NotIncludedValidator { private final static String NAME = "explain"; private final static String USAGE = "[" + NAME + "]"; public ExplainValidator() { super(USAGE); } public ExplainValidator(final String resultKey) { super(USAGE, resultKey + ":" + USAGE); } public String getDefaultTransformerFactoryName() { return NAME; } } /** helper method for adding a random number (may be 0) of items from {@link #FL_VALIDATORS} */ private static void addRandomFlValidators(final Random r, final Set<FlValidator> validators) { List<FlValidator> copyToShuffle = new ArrayList<>(FL_VALIDATORS); Collections.shuffle(copyToShuffle, r); final int numToReturn = r.nextInt(copyToShuffle.size()); validators.addAll(copyToShuffle.subList(0, numToReturn + 1)); } /** * Given an ordered list of values to include in a (key) param, randomly groups them (ie: comma separated) * into actual param key=values which are returned as a new SolrParams instance */ private static SolrParams buildCommaSepParams(final Random rand, final String key, Collection<String> values) { ModifiableSolrParams result = new ModifiableSolrParams(); List<String> copy = new ArrayList<>(values); while (! copy.isEmpty()) { List<String> slice = copy.subList(0, random().nextInt(1 + copy.size())); result.add(key,String.join(",",slice)); slice.clear(); } return result; } /** helper method for asserting an object is a non-null String can be parsed as an int */ public static int assertParseInt(String msg, Object orig) { assertNotNull(msg + ": is null", orig); assertTrue(msg + ": is not a string: " + orig, orig instanceof String); try { return Integer.parseInt(orig.toString()); } catch (NumberFormatException nfe) { throw new AssertionError(msg + ": can't be parsed as a number: " + orig, nfe); } } }
1
28,011
Added a validator for _root_, which is now added automatically since the schema used here declares _root_.
apache-lucene-solr
java
@@ -76,6 +76,12 @@ public interface RewriteDataFiles extends SnapshotUpdate<RewriteDataFiles, Rewri */ String TARGET_FILE_SIZE_BYTES = "target-file-size-bytes"; + /** + * The estimated cost to open a file, used as a minimum weight when combining splits. By default this + * will use the "read.split.open-file-cost" value in the table properties of the table being updated. + */ + String OPEN_FILE_COST = "open-file-cost"; + /** * Choose BINPACK as a strategy for this rewrite operation * @return this for method chaining
1
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.iceberg.actions; import java.util.List; import org.apache.iceberg.StructLike; import org.apache.iceberg.expressions.Expression; /** * An action for rewriting data files according to a rewrite strategy. * Generally used for optimizing the sizing and layout of data files within a table. */ public interface RewriteDataFiles extends SnapshotUpdate<RewriteDataFiles, RewriteDataFiles.Result> { /** * Enable committing groups of files (see max-file-group-size-bytes) prior to the entire rewrite completing. * This will produce additional commits but allow for progress even if some groups fail to commit. This setting * will not change the correctness of the rewrite operation as file groups can be compacted independently. * <p> * The default is false, which produces a single commit when the entire job has completed. */ String PARTIAL_PROGRESS_ENABLED = "partial-progress.enabled"; boolean PARTIAL_PROGRESS_ENABLED_DEFAULT = false; /** * The maximum amount of Iceberg commits that this rewrite is allowed to produce if partial progress is enabled. This * setting has no effect if partial progress is disabled. */ String PARTIAL_PROGRESS_MAX_COMMITS = "partial-progress.max-commits"; int PARTIAL_PROGRESS_MAX_COMMITS_DEFAULT = 10; /** * The entire rewrite operation is broken down into pieces based on partitioning and within partitions based * on size into groups. These sub-units of the rewrite are referred to as file groups. The largest amount of data that * should be compacted in a single group is controlled by {@link #MAX_FILE_GROUP_SIZE_BYTES}. This helps with * breaking down the rewriting of very large partitions which may not be rewritable otherwise due to the resource * constraints of the cluster. For example a sort based rewrite may not scale to terabyte sized partitions, those * partitions need to be worked on in small subsections to avoid exhaustion of resources. * <p> * When grouping files, the underlying rewrite strategy will use this value as to limit the files which * will be included in a single file group. A group will be processed by a single framework "action". For example, * in Spark this means that each group would be rewritten in its own Spark action. A group will never contain files * for multiple output partitions. */ String MAX_FILE_GROUP_SIZE_BYTES = "max-file-group-size-bytes"; long MAX_FILE_GROUP_SIZE_BYTES_DEFAULT = 1024L * 1024L * 1024L * 100L; // 100 Gigabytes /** * The max number of file groups to be simultaneously rewritten by the rewrite strategy. The structure and * contents of the group is determined by the rewrite strategy. Each file group will be rewritten * independently and asynchronously. **/ String MAX_CONCURRENT_FILE_GROUP_REWRITES = "max-concurrent-file-group-rewrites"; int MAX_CONCURRENT_FILE_GROUP_REWRITES_DEFAULT = 1; /** * The output file size that this rewrite strategy will attempt to generate when rewriting files. By default this * will use the "write.target-file-size-bytes value" in the table properties of the table being updated. */ String TARGET_FILE_SIZE_BYTES = "target-file-size-bytes"; /** * Choose BINPACK as a strategy for this rewrite operation * @return this for method chaining */ default RewriteDataFiles binPack() { return this; } /** * A user provided filter for determining which files will be considered by the rewrite strategy. This will be used * in addition to whatever rules the rewrite strategy generates. For example this would be used for providing a * restriction to only run rewrite on a specific partition. * * @param expression An iceberg expression used to determine which files will be considered for rewriting * @return this for chaining */ RewriteDataFiles filter(Expression expression); /** * A map of file group information to the results of rewriting that file group. If the results are null then * that particular file group failed. We should only have failed groups if partial progress is enabled otherwise we * will report a total failure for the job. */ interface Result { List<FileGroupRewriteResult> rewriteResults(); default int addedDataFilesCount() { return rewriteResults().stream().mapToInt(FileGroupRewriteResult::addedDataFilesCount).sum(); } default int rewrittenDataFilesCount() { return rewriteResults().stream().mapToInt(FileGroupRewriteResult::rewrittenDataFilesCount).sum(); } } /** * For a particular file group, the number of files which are newly created and the number of files * which were formerly part of the table but have been rewritten. */ interface FileGroupRewriteResult { FileGroupInfo info(); int addedDataFilesCount(); int rewrittenDataFilesCount(); } /** * A description of a file group, when it was processed, and within which partition. For use * tracking rewrite operations and for returning results. */ interface FileGroupInfo { /** * returns which file group this is out of the total set of file groups for this rewrite */ int globalIndex(); /** * returns which file group this is out of the set of file groups for this partition */ int partitionIndex(); /** * returns which partition this file group contains files from */ StructLike partition(); } }
1
41,655
The other properties are `file-open-cost`, not `open-file-cost`.
apache-iceberg
java
@@ -337,6 +337,19 @@ AC_ARG_ENABLE(easylogging, [Disable easylogging])) AM_CONDITIONAL(USE_EASYLOGGING, [test x$enable_easylogging != xno]) +case "${host_os}" in + *darwin*) + # libunwind comes standard with the command-line tools on macos + AC_DEFINE([HAVE_LIBUNWIND], [1], + [Define to 1 if you have the <libunwind.h> header file]) + ;; + *) + PKG_CHECK_MODULES(libunwind, libunwind, + AC_DEFINE([HAVE_LIBUNWIND], [1], + [Define to 1 if you have the <libunwind.h> header file])) + ;; +esac + # Need this to pass through ccache for xdrpp, libsodium esc() { out=
1
# -*- Autoconf -*- # Process this file with autoconf to produce a configure script. # Copyright 2015 Stellar Development Foundation and contributors. Licensed # under the Apache License, Version 2.0. See the COPYING file at the root # of this distribution or at http://www.apache.org/licenses/LICENSE-2.0 AC_PREREQ([2.68]) AC_INIT([stellar-core],[0.1],[],[],[http://www.stellar.org]) # tar-ustar is required for long file names when libsodium is bundled AM_INIT_AUTOMAKE([-Wall -Wextra -Wconversion subdir-objects tar-ustar silent-rules]) AC_CONFIG_SRCDIR([configure.ac]) AC_CONFIG_MACRO_DIR([m4]) AC_CANONICAL_HOST AC_ARG_VAR([LIBCXX_PATH], [path to libc++ and libc++abi]) if test -z "${WFLAGS+set}"; then WFLAGS=-Wall # Our large include path set makes for annoying warnings without this WFLAGS="$WFLAGS -Wno-unused-command-line-argument -Qunused-arguments" # Asio's headers have unused typedefs that flood the compilation # output without this WFLAGS="$WFLAGS -Wno-unused-local-typedef" # Also don't _further_ warn if the previous warning flag was unknown WFLAGS="$WFLAGS -Wno-unknown-warning-option" # We want to consider unused MUST_USE results as errors WFLAGS="$WFLAGS -Werror=unused-result" fi test "${CFLAGS+set}" || CFLAGS="-g -O2 -fno-omit-frame-pointer" test "${CXXFLAGS+set}" || CXXFLAGS="$CFLAGS" AC_PROG_CC([clang gcc cc]) AC_PROG_CXX([clang++ g++ c++]) AM_PROG_AR AM_PROG_CC_C_O LT_INIT([disable-shared]) AC_SUBST(LIBTOOL_DEPS) AC_LANG(C++) # if modifying the following macro for a future C++ version, please update CXX # for enable-afl in the fuzzer configuration block below AX_CXX_COMPILE_STDCXX_14(noext,mandatory) AX_FRESH_COMPILER # -pthread seems to be required by -std=c++14 on some hosts AX_APPEND_COMPILE_FLAGS([-pthread]) # additional defines AX_APPEND_COMPILE_FLAGS([-DFMT_HEADER_ONLY=1]) AC_MSG_CHECKING([whether defect report N4387 is resolved]) AC_COMPILE_IFELSE([AC_LANG_SOURCE([[#include <tuple> std::tuple<int, int> f() { return {1, 2}; } ]])], [AC_MSG_RESULT([yes])], [AC_MSG_RESULT([no]); AC_MSG_ERROR([defect report N4387 is not resolved])], AC_MSG_FAILURE) AC_MSG_CHECKING([for c++14 compliant std::weak_ptr move-constructor]) AC_RUN_IFELSE([AC_LANG_PROGRAM([[#include <memory>]], [[std::shared_ptr<int> shared = std::make_shared<int>(0); std::weak_ptr<int> weak1(shared); std::weak_ptr<int> weak2(std::move(weak1)); return !((weak1.expired()) && (weak1.lock() == nullptr)); ]])], [AC_MSG_RESULT([yes])], [AC_MSG_RESULT([no]); AC_MSG_ERROR([non-compliant std::weak_ptr move-constructor])], AC_MSG_FAILURE) AC_MSG_CHECKING([for c++14 compliant std::weak_ptr move-assignment operator]) AC_RUN_IFELSE([AC_LANG_PROGRAM([[#include <memory>]], [[std::shared_ptr<int> shared = std::make_shared<int>(0); std::weak_ptr<int> weak1(shared); std::weak_ptr<int> weak2 = std::move(weak1); return !((weak1.expired()) && (weak1.lock() == nullptr)); ]])], [AC_MSG_RESULT([yes])], [AC_MSG_RESULT([no]); AC_MSG_ERROR([non-compliant std::weak_ptr move-assignment operator])], AC_MSG_FAILURE) AC_ARG_ENABLE([sdfprefs], AS_HELP_STRING([--enable-sdfprefs], [Enable build settings preferred by Stellar developers])) AS_IF([test xyes = "x$enable_sdfprefs"], [AM_SILENT_RULES([yes]) WFLAGS="$WFLAGS -fcolor-diagnostics"]) AS_IF([test xyes != "x$enable_sdfprefs" -a xyes != "x$enable_silent_rules"], ac_configure_args="$ac_configure_args --disable-silent-rules") AX_APPEND_COMPILE_FLAGS($WFLAGS) AC_LANG_PUSH(C) AX_APPEND_COMPILE_FLAGS($WFLAGS) # ensure that we also enable pthread in C code AX_APPEND_COMPILE_FLAGS([-pthread]) AC_LANG_POP(C) unset sanitizeopts AC_ARG_ENABLE([asan], AS_HELP_STRING([--enable-asan], [build with asan (address-sanitizer) instrumentation])) AS_IF([test "x$enable_asan" = "xyes"], [ AC_MSG_NOTICE([ Enabling asan, see https://clang.llvm.org/docs/AddressSanitizer.html ]) sanitizeopts="address" ]) AC_ARG_ENABLE([memcheck], AS_HELP_STRING([--enable-memcheck], [build with memcheck (memory-sanitizer) instrumentation])) AS_IF([test "x$enable_memcheck" = "xyes"], [ AC_MSG_NOTICE([ enabling memory-sanitizer, see https://clang.llvm.org/docs/MemorySanitizer.html ]) AC_MSG_NOTICE([ To completely enable poison destructor set MSAN_OPTIONS=poison_in_dtor=1 before running the program ]) AS_IF([test x != "x$sanitizeopts"], [ AC_MSG_ERROR(Cannot enable multiple checkers at once) ]) sanitizeopts="memory -fsanitize-memory-track-origins=2 -fsanitize-memory-use-after-dtor" if test -z "$LIBCXX_PATH"; then AC_MSG_ERROR(LIBCXX_PATH must be set for memcheck to work) fi CXXFLAGS="$CXXFLAGS -DMSAN_ENABLED" LDFLAGS="$LDFLAGS -fsanitize=$sanitizeopts" ]) AS_IF([test x != "x$LIBCXX_PATH"], [ # use custom libc++ CXXFLAGS="$CXXFLAGS -stdlib=libc++" LDFLAGS="$LDFLAGS -L$LIBCXX_PATH -stdlib=libc++ -lc++abi -Wl,-rpath -Wl,$LIBCXX_PATH" ]) AC_ARG_ENABLE([undefinedcheck], AS_HELP_STRING([--enable-undefinedcheck], [build with undefinedcheck (undefined-behavior-sanitizer) instrumentation])) AS_IF([test "x$enable_undefinedcheck" = "xyes"], [ AC_MSG_NOTICE([ enabling undefined-behavior-sanitizer, see https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html ]) AS_IF([test x != "x$sanitizeopts"], [ AC_MSG_ERROR(Cannot enable multiple checkers at once) ]) sanitizeopts="undefined" ]) AS_IF([test x != "x$sanitizeopts"], [ # Compilation should fail if these options are not supported sanflags="-fsanitize=$sanitizeopts -fno-omit-frame-pointer" CFLAGS="$CFLAGS $sanflags" CXXFLAGS="$CXXFLAGS $sanflags" # compile our own libraries when sanitizers are enabled libsodium_INTERNAL=yes xdrpp_INTERNAL=yes ]) AC_ARG_ENABLE([extrachecks], AS_HELP_STRING([--enable-extrachecks], [build with additional debugging checks enabled])) AS_IF([test "x$enable_extrachecks" = "xyes"], [ # don't try to detect which c++ library we're using CXXFLAGS="$CXXFLAGS -D_GLIBCXX_DEBUG=1 -D_GLIBCXX_SANITIZE_VECTOR=1 -D_LIBCPP_DEBUG=0" ]) AC_ARG_ENABLE([ccache], AS_HELP_STRING([--enable-ccache], [build with ccache])) AS_IF([test "x$enable_ccache" = "xyes"], [ AC_CHECK_PROGS([CCACHE], [ccache]) case "$CC" in *ccache\ *) ;; *) CC="ccache ${CC}" ;; esac case "$CXX" in *ccache\ *) ;; *) CXX="ccache ${CXX}" ;; esac ]) # Permit user to enable AFL instrumentation AC_ARG_ENABLE([afl], AS_HELP_STRING([--enable-afl], [build with AFL (fuzzer) instrumentation])) AS_IF([test "x$enable_afl" = "xyes"], [ AS_IF([test "x$sanitizeopts" != "x"], [ AC_MSG_ERROR([AFL is presently incompatible with sanitizers]) ]) AS_IF([test "x$enable_ccache" = "xyes"], [ AC_MSG_ERROR([AFL is presently incompatible with ccache]) ]) AC_CHECK_PROGS([AFL_FUZZ], [afl-fuzz]) AS_CASE(["$CC"], [clang*], [AC_CHECK_PROGS([AFL_CLANG], [afl-clang-fast]) AC_CHECK_PROGS([AFL_CLANGPP], [afl-clang-fast++]) CC="afl-clang-fast" # below we hard code -std=c++14 since updates to AX_CXX_COMPILE_STDCXX circa 2015 append it to # CXX, not to CXXFLAGS and thus when setting CXX we override this. For a more detailed explanation # see: https://github.com/stellar/docker-stellar-core/pull/66#issuecomment-521886881 CXX="afl-clang-fast++ -std=c++14 -DAFL_LLVM_MODE=1"], [gcc*], [AC_CHECK_PROGS([AFL_GCC], [afl-gcc]) AC_CHECK_PROGS([AFL_GPP], [afl-g++]) CC="afl-gcc" # below we hard code -std=c++14 since updates to AX_CXX_COMPILE_STDCXX circa 2015 append it to # CXX, not to CXXFLAGS and thus when setting CXX we override this. For a more detailed explanation # see: https://github.com/stellar/docker-stellar-core/pull/66#issuecomment-521886881 CXX="afl-g++ -std=c++14"], [AC_MSG_ERROR([Don't know how to instrument CC=$CC with AFL])]) ]) AM_CONDITIONAL([USE_AFL_FUZZ], [test "x$enable_afl" == "xyes"]) # prefer 5.0 as it's the one we use AC_CHECK_PROGS(CLANG_FORMAT, [clang-format-5.0 clang-format]) AM_CONDITIONAL([USE_CLANG_FORMAT], [test "x$CLANG_FORMAT" != "x"]) AX_VALGRIND_CHECK if test yes != "$enable_shared"; then ac_configure_args="$ac_configure_args --disable-shared" fi # We use several features of sqlite that require not just a new version # (eg. partial indexes, >=3.8.0; upserts, >= 3.24.0) but also the carray # extension, which is compiled-out of most platform sqlites. We therefore # always use our own bundled copy, version 3.26.0 at the time of this # writing. sqlite3_CFLAGS='-isystem $(top_srcdir)/lib/sqlite -DSQLITE_CORE -DSQLITE_OMIT_LOAD_EXTENSION=1' sqlite3_LIBS= AC_SUBST(sqlite3_CFLAGS) AC_SUBST(sqlite3_LIBS) PKG_CHECK_MODULES(libsodium, [libsodium >= 1.0.17], :, libsodium_INTERNAL=yes) AX_PKGCONFIG_SUBDIR(lib/libsodium) if test -n "$libsodium_INTERNAL"; then libsodium_LIBS='$(top_builddir)/lib/libsodium/src/libsodium/libsodium.la' fi AX_PKGCONFIG_SUBDIR(lib/xdrpp) AC_MSG_CHECKING(for xdrc) if test -n "$XDRC"; then : elif test -n "$xdrpp_INTERNAL" -a x"$cross_compiling" != xyes; then XDRC='$(top_builddir)/lib/xdrpp/xdrc/xdrc$(EXEEXT)' else AC_PATH_PROG(XDRC, [xdrc]) fi if test -z "$XDRC"; then AC_MSG_ERROR(Cannot find xdrc) fi AC_MSG_RESULT($XDRC) AC_SUBST(XDRC) # Directory needed for xdrc output (won't exist in build directory) mkdir -p src/xdr if test -s "$srcdir/lib/medida.mk"; then libmedida_CFLAGS='-isystem $(top_srcdir)/lib/libmedida/src' libmedida_LIBS='$(top_builddir)/lib/libmedida.a' libmedida_INTERNAL=yes else PKG_CHECK_MODULES(libmedida, libmedida) unset libmedida_INTERNAL fi AM_CONDITIONAL(LIBMEDIDA_INTERNAL, test -n "$libmedida_INTERNAL") AC_SUBST(libmedida_CFLAGS) AC_SUBST(libmedida_LIBS) soci_CFLAGS='-isystem $(top_srcdir)/lib/soci/src/core' soci_LIBS='$(top_builddir)/lib/libsoci.a' AC_SUBST(soci_CFLAGS) AC_SUBST(soci_LIBS) libasio_CFLAGS='-DASIO_SEPARATE_COMPILATION=1 -DASIO_STANDALONE -isystem $(top_srcdir)/lib/asio/asio/include' AC_SUBST(libasio_CFLAGS) AC_ARG_ENABLE(postgres, AS_HELP_STRING([--disable-postgres], [Disable postgres support even when libpq available])) unset have_postgres if test x"$enable_postgres" != xno; then PKG_CHECK_MODULES(libpq, libpq, have_postgres=1) if test -n "$enable_postgres" -a -z "$have_postgres"; then AC_MSG_ERROR([Cannot find postgres library]) fi fi AM_CONDITIONAL(USE_POSTGRES, [test -n "$have_postgres"]) AC_ARG_ENABLE(tests, AS_HELP_STRING([--disable-tests], [Disable building test suite])) AM_CONDITIONAL(BUILD_TESTS, [test x$enable_tests != xno]) AC_ARG_ENABLE(tracy, AS_HELP_STRING([--enable-tracy], [Enable 'tracy' profiler/tracer client stub])) AM_CONDITIONAL(USE_TRACY, [test x$enable_tracy = xyes]) tracy_CFLAGS='-DTRACY_ENABLE -DTRACY_ON_DEMAND -DTRACY_NO_BROADCAST -DTRACY_ONLY_LOCALHOST -DTRACY_ONLY_IPV4' if test x"$enable_tracy" = xyes; then case "${host_os}" in *darwin*) ;; *) LDFLAGS+=" -ldl " ;; esac fi AC_SUBST(tracy_CFLAGS) AC_ARG_ENABLE(tracy-gui, AS_HELP_STRING([--enable-tracy-gui], [Enable 'tracy' profiler/tracer server GUI])) AM_CONDITIONAL(USE_TRACY_GUI, [test x$enable_tracy_gui = xyes]) if test x"$enable_tracy_gui" = xyes; then PKG_CHECK_MODULES(capstone, capstone) PKG_CHECK_MODULES(freetype, freetype2) PKG_CHECK_MODULES(glfw, glfw3) case "${host_os}" in *darwin*) ;; *) PKG_CHECK_MODULES(gtk, gtk+-2.0) ;; esac fi AC_ARG_ENABLE(tracy-capture, AS_HELP_STRING([--enable-tracy-capture], [Enable 'tracy' profiler/tracer capture program])) AM_CONDITIONAL(USE_TRACY_CAPTURE, [test x$enable_tracy_capture = xyes]) AC_ARG_ENABLE(easylogging, AS_HELP_STRING([--disable-easylogging], [Disable easylogging])) AM_CONDITIONAL(USE_EASYLOGGING, [test x$enable_easylogging != xno]) # Need this to pass through ccache for xdrpp, libsodium esc() { out= for arg in "$@"; do out="$out${out+ }$(echo "$arg" | sed "s/'/'\\''/g; s/^/'/; s/\$/'/")" done echo $out } # explicitly propagate CFLAGS, CXXFLAGS and LDFLAGS in case they got modified by global options ac_configure_args="$ac_configure_args $(esc "CC=$CC" "CXX=$CXX" "CFLAGS=$CFLAGS" "CXXFLAGS=$CXXFLAGS" "LDFLAGS=$LDFLAGS")" AC_CONFIG_HEADERS(config.h) AC_CONFIG_FILES(lib/Makefile src/Makefile Makefile) AC_OUTPUT
1
17,688
confused by this: what we need here is not libunwind but libunwind-dev right? Why skipping detection?
stellar-stellar-core
c
@@ -24,8 +24,8 @@ namespace Microsoft.Azure throw new ArgumentNullException("serializer"); } JsonSerializer newSerializer = new JsonSerializer(); - PropertyInfo[] properties = typeof(JsonSerializer).GetProperties(); - foreach (var property in properties.Where(p => p.GetSetMethod() != null)) + var properties = typeof(JsonSerializer).GetTypeInfo().DeclaredProperties; + foreach (var property in properties.Where(p => p.SetMethod != null && !p.SetMethod.IsPrivate)) { property.SetValue(newSerializer, property.GetValue(serializer, null), null); }
1
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Linq; using System.Reflection; using Newtonsoft.Json; namespace Microsoft.Azure { public static class JsonSerializerExtensions { /// <summary> /// Gets a JsonSerializer without specified converter. /// </summary> /// <param name="serializer">JsonSerializer</param> /// <param name="converterToExclude">Converter to exclude from serializer.</param> /// <returns></returns> public static JsonSerializer WithoutConverter(this JsonSerializer serializer, JsonConverter converterToExclude) { if (serializer == null) { throw new ArgumentNullException("serializer"); } JsonSerializer newSerializer = new JsonSerializer(); PropertyInfo[] properties = typeof(JsonSerializer).GetProperties(); foreach (var property in properties.Where(p => p.GetSetMethod() != null)) { property.SetValue(newSerializer, property.GetValue(serializer, null), null); } foreach (var converter in serializer.Converters) { if (converter != converterToExclude) { newSerializer.Converters.Add(converter); } } return newSerializer; } } }
1
20,842
just in case helps, it this related with this PR?
Azure-autorest
java
@@ -88,6 +88,11 @@ def convert_019_100(data): def convert_100_200(data): data["version"] = (2, 0, 0) + data["client_conn"]["address"] = data["client_conn"]["address"]["address"] + data["server_conn"]["address"] = data["server_conn"]["address"]["address"] + data["server_conn"]["source_address"] = data["server_conn"]["source_address"]["address"] + if data["server_conn"]["ip_address"]: + data["server_conn"]["ip_address"] = data["server_conn"]["ip_address"]["address"] return data
1
""" This module handles the import of mitmproxy flows generated by old versions. """ from typing import Any from mitmproxy import version from mitmproxy.utils import strutils def convert_011_012(data): data[b"version"] = (0, 12) return data def convert_012_013(data): data[b"version"] = (0, 13) return data def convert_013_014(data): data[b"request"][b"first_line_format"] = data[b"request"].pop(b"form_in") data[b"request"][b"http_version"] = b"HTTP/" + ".".join( str(x) for x in data[b"request"].pop(b"httpversion")).encode() data[b"response"][b"http_version"] = b"HTTP/" + ".".join( str(x) for x in data[b"response"].pop(b"httpversion")).encode() data[b"response"][b"status_code"] = data[b"response"].pop(b"code") data[b"response"][b"body"] = data[b"response"].pop(b"content") data[b"server_conn"].pop(b"state") data[b"server_conn"][b"via"] = None data[b"version"] = (0, 14) return data def convert_014_015(data): data[b"version"] = (0, 15) return data def convert_015_016(data): for m in (b"request", b"response"): if b"body" in data[m]: data[m][b"content"] = data[m].pop(b"body") if b"msg" in data[b"response"]: data[b"response"][b"reason"] = data[b"response"].pop(b"msg") data[b"request"].pop(b"form_out", None) data[b"version"] = (0, 16) return data def convert_016_017(data): data[b"server_conn"][b"peer_address"] = None data[b"version"] = (0, 17) return data def convert_017_018(data): # convert_unicode needs to be called for every dual release and the first py3-only release data = convert_unicode(data) data["server_conn"]["ip_address"] = data["server_conn"].pop("peer_address") data["marked"] = False data["version"] = (0, 18) return data def convert_018_019(data): # convert_unicode needs to be called for every dual release and the first py3-only release data = convert_unicode(data) data["request"].pop("stickyauth", None) data["request"].pop("stickycookie", None) data["client_conn"]["sni"] = None data["client_conn"]["alpn_proto_negotiated"] = None data["client_conn"]["cipher_name"] = None data["client_conn"]["tls_version"] = None data["server_conn"]["alpn_proto_negotiated"] = None data["mode"] = "regular" data["metadata"] = dict() data["version"] = (0, 19) return data def convert_019_100(data): data["version"] = (1, 0, 0) return data def convert_100_200(data): data["version"] = (2, 0, 0) return data def convert_200_300(data): data["version"] = (3, 0, 0) data["client_conn"]["mitmcert"] = None return data def _convert_dict_keys(o: Any) -> Any: if isinstance(o, dict): return {strutils.always_str(k): _convert_dict_keys(v) for k, v in o.items()} else: return o def _convert_dict_vals(o: dict, values_to_convert: dict) -> dict: for k, v in values_to_convert.items(): if not o or k not in o: continue if v is True: o[k] = strutils.always_str(o[k]) else: _convert_dict_vals(o[k], v) return o def convert_unicode(data: dict) -> dict: """ This method converts between Python 3 and Python 2 dumpfiles. """ data = _convert_dict_keys(data) data = _convert_dict_vals( data, { "type": True, "id": True, "request": { "first_line_format": True }, "error": { "msg": True } } ) return data converters = { (0, 11): convert_011_012, (0, 12): convert_012_013, (0, 13): convert_013_014, (0, 14): convert_014_015, (0, 15): convert_015_016, (0, 16): convert_016_017, (0, 17): convert_017_018, (0, 18): convert_018_019, (0, 19): convert_019_100, (1, 0): convert_100_200, (2, 0): convert_200_300, } def migrate_flow(flow_data): while True: flow_version = tuple(flow_data.get(b"version", flow_data.get("version"))) if flow_version[:2] == version.IVERSION[:2]: break elif flow_version[:2] in converters: flow_data = converters[flow_version[:2]](flow_data) else: v = ".".join(str(i) for i in flow_version) raise ValueError( "{} cannot read files serialized with version {}.".format(version.MITMPROXY, v) ) return flow_data
1
12,888
This is incomplete I think (at least source_address and ip_address are missing)
mitmproxy-mitmproxy
py
@@ -126,7 +126,16 @@ public class DefaultSynchronizer<C> implements Synchronizer { LOG.info("Starting synchronizer."); blockPropagationManager.start(); if (fastSyncDownloader.isPresent()) { - fastSyncDownloader.get().start().whenComplete(this::handleFastSyncResult); + fastSyncDownloader + .get() + .start() + .whenComplete(this::handleFastSyncResult) + .exceptionally( + ex -> { + System.exit(0); + return null; + }); + } else { startFullSync(); }
1
/* * Copyright ConsenSys AG. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * * SPDX-License-Identifier: Apache-2.0 */ package org.hyperledger.besu.ethereum.eth.sync; import static com.google.common.base.Preconditions.checkNotNull; import org.hyperledger.besu.ethereum.ProtocolContext; import org.hyperledger.besu.ethereum.core.Synchronizer; import org.hyperledger.besu.ethereum.eth.manager.EthContext; import org.hyperledger.besu.ethereum.eth.sync.fastsync.FastDownloaderFactory; import org.hyperledger.besu.ethereum.eth.sync.fastsync.FastSyncDownloader; import org.hyperledger.besu.ethereum.eth.sync.fastsync.FastSyncException; import org.hyperledger.besu.ethereum.eth.sync.fastsync.FastSyncState; import org.hyperledger.besu.ethereum.eth.sync.fullsync.FullSyncDownloader; import org.hyperledger.besu.ethereum.eth.sync.state.PendingBlocks; import org.hyperledger.besu.ethereum.eth.sync.state.SyncState; import org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule; import org.hyperledger.besu.ethereum.worldstate.Pruner; import org.hyperledger.besu.ethereum.worldstate.WorldStateStorage; import org.hyperledger.besu.metrics.BesuMetricCategory; import org.hyperledger.besu.plugin.data.SyncStatus; import org.hyperledger.besu.plugin.services.BesuEvents.SyncStatusListener; import org.hyperledger.besu.plugin.services.MetricsSystem; import org.hyperledger.besu.util.ExceptionUtils; import java.nio.file.Path; import java.time.Clock; import java.util.Optional; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class DefaultSynchronizer<C> implements Synchronizer { private static final Logger LOG = LogManager.getLogger(); private final Optional<Pruner> maybePruner; private final SyncState syncState; private final AtomicBoolean running = new AtomicBoolean(false); private final BlockPropagationManager<C> blockPropagationManager; private final Optional<FastSyncDownloader<C>> fastSyncDownloader; private final FullSyncDownloader<C> fullSyncDownloader; public DefaultSynchronizer( final SynchronizerConfiguration syncConfig, final ProtocolSchedule<C> protocolSchedule, final ProtocolContext<C> protocolContext, final WorldStateStorage worldStateStorage, final BlockBroadcaster blockBroadcaster, final Optional<Pruner> maybePruner, final EthContext ethContext, final SyncState syncState, final Path dataDirectory, final Clock clock, final MetricsSystem metricsSystem) { this.maybePruner = maybePruner; this.syncState = syncState; ChainHeadTracker.trackChainHeadForPeers( ethContext, protocolSchedule, protocolContext.getBlockchain(), this::calculateTrailingPeerRequirements, metricsSystem); this.blockPropagationManager = new BlockPropagationManager<>( syncConfig, protocolSchedule, protocolContext, ethContext, syncState, new PendingBlocks(), metricsSystem, blockBroadcaster); this.fullSyncDownloader = new FullSyncDownloader<>( syncConfig, protocolSchedule, protocolContext, ethContext, syncState, metricsSystem); this.fastSyncDownloader = FastDownloaderFactory.create( syncConfig, dataDirectory, protocolSchedule, protocolContext, metricsSystem, ethContext, worldStateStorage, syncState, clock); metricsSystem.createLongGauge( BesuMetricCategory.ETHEREUM, "best_known_block_number", "The estimated highest block available", syncState::bestChainHeight); metricsSystem.createIntegerGauge( BesuMetricCategory.SYNCHRONIZER, "in_sync", "Whether or not the local node has caught up to the best known peer", () -> getSyncStatus().isPresent() ? 0 : 1); } private TrailingPeerRequirements calculateTrailingPeerRequirements() { return fastSyncDownloader .flatMap(FastSyncDownloader::calculateTrailingPeerRequirements) .orElseGet(fullSyncDownloader::calculateTrailingPeerRequirements); } @Override public void start() { if (running.compareAndSet(false, true)) { LOG.info("Starting synchronizer."); blockPropagationManager.start(); if (fastSyncDownloader.isPresent()) { fastSyncDownloader.get().start().whenComplete(this::handleFastSyncResult); } else { startFullSync(); } } else { throw new IllegalStateException("Attempt to start an already started synchronizer."); } } @Override public void stop() { if (running.compareAndSet(true, false)) { LOG.info("Stopping synchronizer"); fastSyncDownloader.ifPresent(FastSyncDownloader::stop); fullSyncDownloader.stop(); maybePruner.ifPresent(Pruner::stop); } } @Override public void awaitStop() throws InterruptedException { if (maybePruner.isPresent()) { maybePruner.get().awaitStop(); } } private void handleFastSyncResult(final FastSyncState result, final Throwable error) { if (!running.get()) { // We've been shutdown which will have triggered the fast sync future to complete return; } final Throwable rootCause = ExceptionUtils.rootCause(error); if (rootCause instanceof FastSyncException) { LOG.error( "Fast sync failed ({}), switching to full sync.", ((FastSyncException) rootCause).getError()); } else if (error != null) { LOG.error("Fast sync failed, switching to full sync.", error); } else { LOG.info( "Fast sync completed successfully with pivot block {}", result.getPivotBlockNumber().getAsLong()); } fastSyncDownloader.ifPresent(FastSyncDownloader::deleteFastSyncState); startFullSync(); } private void startFullSync() { maybePruner.ifPresent(Pruner::start); fullSyncDownloader.start(); } @Override public Optional<SyncStatus> getSyncStatus() { if (!running.get()) { return Optional.empty(); } return syncState.syncStatus(); } @Override public long subscribeSyncStatus(final SyncStatusListener listener) { checkNotNull(listener); return syncState.subscribeSyncStatus(listener); } @Override public boolean unsubscribeSyncStatus(final long subscriberId) { return syncState.unsubscribeSyncStatus(subscriberId); } @Override public long subscribeInSync(final InSyncListener listener) { return syncState.subscribeInSync(listener); } @Override public long subscribeInSync(final InSyncListener listener, final long syncTolerance) { return syncState.subscribeInSync(listener, syncTolerance); } @Override public boolean unsubscribeInSync(final long listenerId) { return syncState.unsubscribeSyncStatus(listenerId); } }
1
22,669
We have a `stop` method here, we should probably be calling that instead of just exiting. There could be important resources to close or cleanup nicely now or in the future.
hyperledger-besu
java
@@ -35,6 +35,7 @@ namespace AutoRest.Extensions //Constraints = parameter.Constraints, Omit these since we don't want to perform parameter validation Documentation = parameter.Documentation, ModelType = parameter.ModelType, + RealPath = new string[] { }, SerializedName = default(string) //Parameter is never serialized directly });
1
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using AutoRest.Core.Model; using Newtonsoft.Json.Linq; using static AutoRest.Core.Utilities.DependencyInjection; using AutoRest.Core.Utilities; namespace AutoRest.Extensions { public static class ParameterGroupExtensionHelper { private class ParameterGroup { public string Name { get; } public Dictionary<Property, Parameter> ParameterMapping { get; } public ParameterGroup(string name, Dictionary<Property, Parameter> parameterMapping) { this.Name = name; this.ParameterMapping = parameterMapping; } } private static Property CreateParameterGroupProperty(Parameter parameter) { Property groupProperty = New<Property>(new { IsReadOnly = false, //Since these properties are used as parameters they are never read only Name = parameter.Name, IsRequired = parameter.IsRequired, DefaultValue = parameter.DefaultValue, //Constraints = parameter.Constraints, Omit these since we don't want to perform parameter validation Documentation = parameter.Documentation, ModelType = parameter.ModelType, SerializedName = default(string) //Parameter is never serialized directly }); // Copy over extensions foreach (var key in parameter.Extensions.Keys) { groupProperty.Extensions[key] = parameter.Extensions[key]; } return groupProperty; } private static ParameterGroup BuildParameterGroup(string parameterGroupName, Method method) { Dictionary<Property, Parameter> parameterMapping = method.Parameters.Where( p => GetParameterGroupName(method.Group, method.Name, p) == parameterGroupName).ToDictionary( CreateParameterGroupProperty, p => p); return new ParameterGroup(parameterGroupName, parameterMapping); } private static string GetParameterGroupName(string methodGroupName, string methodName, Parameter parameter) { if (parameter.Extensions.ContainsKey(SwaggerExtensions.ParameterGroupExtension)) { JContainer extensionObject = parameter.Extensions[SwaggerExtensions.ParameterGroupExtension] as JContainer; if (extensionObject != null) { string specifiedGroupName = extensionObject.Value<string>("name"); string parameterGroupName; if (specifiedGroupName == null) { string postfix = extensionObject.Value<string>("postfix") ?? "Parameters"; parameterGroupName = methodGroupName + "-" + methodName + "-" + postfix; } else { parameterGroupName = specifiedGroupName; } return parameterGroupName; } } return null; } private static IEnumerable<string> ExtractParameterGroupNames(Method method) { return method.Parameters.Select(p => GetParameterGroupName(method.Group, method.Name, p)).Where(name => !string.IsNullOrEmpty(name)).Distinct(); } private static IEnumerable<ParameterGroup> ExtractParameterGroups(Method method) { IEnumerable<string> parameterGroupNames = ExtractParameterGroupNames(method); return parameterGroupNames.Select(parameterGroupName => BuildParameterGroup(parameterGroupName, method)); } private static IEnumerable<Method> GetMethodsUsingParameterGroup(IEnumerable<Method> methods, ParameterGroup parameterGroup) { return methods.Where(m => ExtractParameterGroupNames(m).Contains(parameterGroup.Name)); } private static string GenerateParameterGroupModelText(IEnumerable<Method> methodsWhichUseGroup) { Func<string, string, string> createOperationDisplayString = (group, name) => { return string.IsNullOrEmpty(group) ? name : string.Format(CultureInfo.InvariantCulture, "{0}_{1}", group, name); }; List<Method> methodList = methodsWhichUseGroup.ToList(); if (methodList.Count == 1) { Method method = methodList.Single(); return string.Format(CultureInfo.InvariantCulture, "Additional parameters for the {0} operation.", createOperationDisplayString(method.MethodGroup.Name.ToPascalCase(), method.Name)); } else if (methodList.Count <= 4) { string operationsString = string.Join(", ", methodList.Select( m => string.Format(CultureInfo.InvariantCulture, createOperationDisplayString(m.MethodGroup.Name.ToPascalCase(), m.Name)))); return string.Format(CultureInfo.InvariantCulture, "Additional parameters for a set of operations, such as: {0}.", operationsString); } else { return "Additional parameters for a set of operations."; } } /// <summary> /// Adds the parameter groups to operation parameters. /// </summary> /// <param name="codeModelient"></param> public static void AddParameterGroups(CodeModel codeModel) { if (codeModel == null) { throw new ArgumentNullException("codeModel"); } HashSet<CompositeType> generatedParameterGroups = new HashSet<CompositeType>(); foreach (Method method in codeModel.Methods) { //Copy out flattening transformations as they should be the last List<ParameterTransformation> flatteningTransformations = method.InputParameterTransformation.ToList(); method.InputParameterTransformation.Clear(); //This group name is normalized by each languages code generator later, so it need not happen here. IEnumerable<ParameterGroup> parameterGroups = ExtractParameterGroups(method); List<Parameter> parametersToAddToMethod = new List<Parameter>(); List<Parameter> parametersToRemoveFromMethod = new List<Parameter>(); foreach (ParameterGroup parameterGroup in parameterGroups) { CompositeType parameterGroupType = generatedParameterGroups.FirstOrDefault(item => item.Name.RawValue == parameterGroup.Name); if (parameterGroupType == null) { IEnumerable<Method> methodsWhichUseGroup = GetMethodsUsingParameterGroup(codeModel.Methods, parameterGroup); parameterGroupType = New<CompositeType>(parameterGroup.Name,new { Documentation = GenerateParameterGroupModelText(methodsWhichUseGroup) }); generatedParameterGroups.Add(parameterGroupType); //Add to the service client codeModel.Add(parameterGroupType); } foreach (Property property in parameterGroup.ParameterMapping.Keys) { Property matchingProperty = parameterGroupType.Properties.FirstOrDefault( item => item.Name.RawValue == property.Name.RawValue && item.IsReadOnly == property.IsReadOnly && item.DefaultValue .RawValue== property.DefaultValue.RawValue && item.SerializedName.RawValue == property.SerializedName.RawValue); if (matchingProperty == null) { parameterGroupType.Add(property); } } bool isGroupParameterRequired = parameterGroupType.Properties.Any(p => p.IsRequired); //Create the new parameter object based on the parameter group type Parameter newParameter = New<Parameter>(new { Name = parameterGroup.Name, IsRequired = isGroupParameterRequired, Location = ParameterLocation.None, SerializedName = string.Empty, ModelType = parameterGroupType, Documentation = "Additional parameters for the operation" }); parametersToAddToMethod.Add(newParameter); //Link the grouped parameters to their parent, and remove them from the method parameters foreach (Property property in parameterGroup.ParameterMapping.Keys) { Parameter p = parameterGroup.ParameterMapping[property]; var parameterTransformation = new ParameterTransformation { OutputParameter = p }; parameterTransformation.ParameterMappings.Add(new ParameterMapping { InputParameter = newParameter, InputParameterProperty = property.GetClientName() }); method.InputParameterTransformation.Add(parameterTransformation); parametersToRemoveFromMethod.Add(p); } } method.Remove(p => parametersToRemoveFromMethod.Contains(p)); method.AddRange(parametersToAddToMethod); // Copy back flattening transformations if any flatteningTransformations.ForEach(t => method.InputParameterTransformation.Add(t)); } } } }
1
24,797
fixes ArgNullEx when using both `x-ms-parameter-grouping` and media type `application/xml` in the same operation (issue #2236)
Azure-autorest
java
@@ -33,6 +33,12 @@ const ( // The specified bucket does not exist. ErrCodeNoSuchBucket = "NoSuchBucket" + // ErrCodeBucketNotFound for service response error code + // "NotFound". + // + // The specified bucket does not exist + ErrCodeBucketNotFound = "NotFound" + // ErrCodeNoSuchKey for service response error code // "NoSuchKey". //
1
// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package s3 const ( // ErrCodeBucketAlreadyExists for service response error code // "BucketAlreadyExists". // // The requested bucket name is not available. The bucket namespace is shared // by all users of the system. Select a different name and try again. ErrCodeBucketAlreadyExists = "BucketAlreadyExists" // ErrCodeBucketAlreadyOwnedByYou for service response error code // "BucketAlreadyOwnedByYou". // // The bucket you tried to create already exists, and you own it. Amazon S3 // returns this error in all AWS Regions except in the North Virginia Region. // For legacy compatibility, if you re-create an existing bucket that you already // own in the North Virginia Region, Amazon S3 returns 200 OK and resets the // bucket access control lists (ACLs). ErrCodeBucketAlreadyOwnedByYou = "BucketAlreadyOwnedByYou" // ErrCodeInvalidObjectState for service response error code // "InvalidObjectState". // // Object is archived and inaccessible until restored. ErrCodeInvalidObjectState = "InvalidObjectState" // ErrCodeNoSuchBucket for service response error code // "NoSuchBucket". // // The specified bucket does not exist. ErrCodeNoSuchBucket = "NoSuchBucket" // ErrCodeNoSuchKey for service response error code // "NoSuchKey". // // The specified key does not exist. ErrCodeNoSuchKey = "NoSuchKey" // ErrCodeNoSuchUpload for service response error code // "NoSuchUpload". // // The specified multipart upload does not exist. ErrCodeNoSuchUpload = "NoSuchUpload" // ErrCodeObjectAlreadyInActiveTierError for service response error code // "ObjectAlreadyInActiveTierError". // // This operation is not allowed against this storage tier. ErrCodeObjectAlreadyInActiveTierError = "ObjectAlreadyInActiveTierError" // ErrCodeObjectNotInActiveTierError for service response error code // "ObjectNotInActiveTierError". // // The source object of the COPY operation is not in the active tier and is // only stored in Amazon S3 Glacier. ErrCodeObjectNotInActiveTierError = "ObjectNotInActiveTierError" )
1
10,298
`NotFound` is a generic error code derived from the HTTP response message's status code, and can be returned for any S3 operation that responds with a 404 status code and no other error code present. Due to this the constant `ErrCodeBucketNotFound`. In addition, these constants are generated based on the API model defined by Amazon S3, modifications to the file directly will be lost during regeneration of the API. With that said, we are looking at ways to work with the Amazon S3 team to better represent this error in a way that is more easily consumed.
aws-aws-sdk-go
go
@@ -0,0 +1,18 @@ +test_name 'test generic installers' + +step 'install arbitrary msi via url' do + hosts.each do |host| + if host['platform'] =~ /win/ + # this should be implemented at the host/win/pkg.rb level someday + generic_install_msi_on(host, 'https://releases.hashicorp.com/vagrant/1.8.4/vagrant_1.8.4.msi', {}, {:debug => true}) + end + end +end + +step 'install arbitrary dmg via url' do + hosts.each do |host| + if host['platform'] =~ /osx/ + host.generic_install_dmg('https://releases.hashicorp.com/vagrant/1.8.4/vagrant_1.8.4.dmg', 'Vagrant', 'Vagrant.pkg') + end + end +end
1
1
13,255
@johnduarte I was curious about the case when the operating system was neither `osx` or `win`; in this case, the test will indeed pass, but nothing will have actually really been tested. Should this have a `skip_test` condition at the top?
voxpupuli-beaker
rb
@@ -0,0 +1,10 @@ +package main + +import "time" + +func main() { + for { + println("hello world!") + time.Sleep(time.Second) + } +}
1
1
5,760
I think this example was included by accident? It doesn't seem to belong in this PR (but a separate PR with this would be nice!).
tinygo-org-tinygo
go
@@ -128,7 +128,7 @@ public class RestRequest { * * @param method the HTTP method for the request (GET/POST/DELETE etc) * @param path the URI path, this will automatically be resolved against the users current instance host. - * @param httpEntity the request body if there is one, can be null. + * @param requestEntity the request body if there is one, can be null. */ public RestRequest(RestMethod method, String path, HttpEntity requestEntity) { this(method, path, requestEntity, null);
1
/* * Copyright (c) 2011, salesforce.com, inc. * All rights reserved. * Redistribution and use of this software in source and binary forms, with or * without modification, are permitted provided that the following conditions * are met: * - Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of salesforce.com, inc. nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission of salesforce.com, inc. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package com.salesforce.androidsdk.rest; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.List; import java.util.Map; import org.apache.http.HttpEntity; import org.apache.http.entity.StringEntity; import org.apache.http.protocol.HTTP; import org.json.JSONObject; import com.android.volley.Request; /** * RestRequest: Class to represent any REST request. * * The class offers factory methods to build RestRequest objects for all REST API actions: * <ul> * <li> versions</li> * <li> resources</li> * <li> describeGlobal</li> * <li> metadata</li> * <li> describe</li> * <li> create</li> * <li> retrieve</li> * <li> update</li> * <li> upsert</li> * <li> delete</li> * <li> searchScopeAndOrder</li> * <li> searchResultLayout</li> * </ul> * * It also has constructors to build any arbitrary request. * */ public class RestRequest { /** * Enumeration for all HTTP methods. * */ public enum RestMethod { GET, POST, PUT, DELETE, HEAD, PATCH; // Methods missing from Request.Method public static final int MethodPATCH = 4; public static final int MethodHEAD = 5; public int asVolleyMethod() { switch (this) { case DELETE: return Request.Method.DELETE; case GET: return Request.Method.GET; case POST: return Request.Method.POST; case PUT: return Request.Method.PUT; case HEAD: return MethodHEAD; // not in Request.Method case PATCH: return MethodPATCH; // not in Request.Method default: return -2; // should never happen } } } /** * Enumeration for all REST API actions. */ private enum RestAction { VERSIONS("/services/data/"), RESOURCES("/services/data/%s/"), DESCRIBE_GLOBAL("/services/data/%s/sobjects/"), METADATA("/services/data/%s/sobjects/%s/"), DESCRIBE("/services/data/%s/sobjects/%s/describe/"), CREATE("/services/data/%s/sobjects/%s"), RETRIEVE("/services/data/%s/sobjects/%s/%s"), UPSERT("/services/data/%s/sobjects/%s/%s/%s"), UPDATE("/services/data/%s/sobjects/%s/%s"), DELETE("/services/data/%s/sobjects/%s/%s"), QUERY("/services/data/%s/query"), SEARCH("/services/data/%s/search"), SEARCH_SCOPE_AND_ORDER("/services/data/%s/search/scopeOrder"), SEARCH_RESULT_LAYOUT("/services/data/%s/search/layout"); private final String pathTemplate; private RestAction(String uriTemplate) { this.pathTemplate = uriTemplate; } public String getPath(Object... args) { return String.format(pathTemplate, args); } } private final RestMethod method; private final String path; private final HttpEntity requestEntity; private final Map<String, String> additionalHttpHeaders; /** * Generic constructor for arbitrary requests. * * @param method the HTTP method for the request (GET/POST/DELETE etc) * @param path the URI path, this will automatically be resolved against the users current instance host. * @param httpEntity the request body if there is one, can be null. */ public RestRequest(RestMethod method, String path, HttpEntity requestEntity) { this(method, path, requestEntity, null); } public RestRequest(RestMethod method, String path, HttpEntity requestEntity, Map<String, String> additionalHttpHeaders) { this.method = method; this.path = path; this.requestEntity = requestEntity; this.additionalHttpHeaders = additionalHttpHeaders; } /** * @return HTTP method of the request. */ public RestMethod getMethod() { return method; } /** * @return Path of the request. */ public String getPath() { return path; } /** * @return request HttpEntity */ public HttpEntity getRequestEntity() { return requestEntity; } public Map<String, String> getAdditionalHttpHeaders() { return additionalHttpHeaders; } @Override public String toString() { StringBuffer sb = new StringBuffer(); sb.append(method).append(" ").append(path); return sb.toString(); } /** * Request to get summary information about each Salesforce.com version currently available. * See http://www.salesforce.com/us/developer/docs/api_rest/Content/resources_versions.htm * * @return a JsonNode * @throws IOException * @throws RestException */ public static RestRequest getRequestForVersions() { return new RestRequest(RestMethod.GET, RestAction.VERSIONS.getPath(), null); } /** * Request to list available resources for the specified API version, including resource name and URI. * See http://www.salesforce.com/us/developer/docs/api_rest/Content/resources_discoveryresource.htm * * @param apiVersion * @return a RestRequest * @throws IOException * @throws RestException */ public static RestRequest getRequestForResources(String apiVersion) { return new RestRequest(RestMethod.GET, RestAction.RESOURCES.getPath(apiVersion), null); } /** * Request to list the available objects and their metadata for your organization's data. * See http://www.salesforce.com/us/developer/docs/api_rest/Content/resources_describeGlobal.htm * * @param apiVersion * @return a RestRequest * @throws IOException * @throws RestException */ public static RestRequest getRequestForDescribeGlobal(String apiVersion) { return new RestRequest(RestMethod.GET, RestAction.DESCRIBE_GLOBAL.getPath(apiVersion), null); } /** * Request to describe the individual metadata for the specified object. * See http://www.salesforce.com/us/developer/docs/api_rest/Content/resources_sobject_basic_info.htm * * @param apiVersion * @param objectType * @return a RestRequest * @throws IOException * @throws RestException */ public static RestRequest getRequestForMetadata(String apiVersion, String objectType) { return new RestRequest(RestMethod.GET, RestAction.METADATA.getPath(apiVersion, objectType), null); } /** * Request to completely describe the individual metadata at all levels for the specified object. * See http://www.salesforce.com/us/developer/docs/api_rest/Content/resources_sobject_describe.htm * * @param apiVersion * @param objectType * @return a RestRequest */ public static RestRequest getRequestForDescribe(String apiVersion, String objectType) { return new RestRequest(RestMethod.GET, RestAction.DESCRIBE.getPath(apiVersion, objectType), null); } /** * Request to create a record. * See http://www.salesforce.com/us/developer/docs/api_rest/Content/resources_sobject_retrieve.htm * * @param apiVersion * @param objectType * @param fields * @return a RestRequest * @throws IOException * @throws UnsupportedEncodingException */ public static RestRequest getRequestForCreate(String apiVersion, String objectType, Map<String, Object> fields) throws UnsupportedEncodingException, IOException { HttpEntity fieldsData = prepareFieldsData(fields); return new RestRequest(RestMethod.POST, RestAction.CREATE.getPath(apiVersion, objectType), fieldsData); } /** * Request to retrieve a record by object id. * See http://www.salesforce.com/us/developer/docs/api_rest/Content/resources_sobject_retrieve.htm * * @param apiVersion * @param objectType * @param objectId * @param fieldList * @return a RestRequest * @throws UnsupportedEncodingException */ public static RestRequest getRequestForRetrieve(String apiVersion, String objectType, String objectId, List<String> fieldList) throws UnsupportedEncodingException { StringBuilder path = new StringBuilder(RestAction.RETRIEVE.getPath(apiVersion, objectType, objectId)); if (fieldList != null && fieldList.size() > 0) { path.append("?fields="); path.append(URLEncoder.encode(toCsv(fieldList).toString(), HTTP.UTF_8)); } return new RestRequest(RestMethod.GET, path.toString(), null); } private static StringBuilder toCsv(List<String> fieldList) { StringBuilder fieldsCsv = new StringBuilder(); for (int i=0; i<fieldList.size(); i++) { fieldsCsv.append(fieldList.get(i)); if (i<fieldList.size() - 1) { fieldsCsv.append(","); } } return fieldsCsv; } /** * Request to update a record. * See http://www.salesforce.com/us/developer/docs/api_rest/Content/resources_sobject_retrieve.htm * * @param apiVersion * @param objectType * @param objectId * @param fields * @return a RestRequest * @throws IOException * @throws UnsupportedEncodingException * @throws JsonMappingException * @throws JsonGenerationException */ public static RestRequest getRequestForUpdate(String apiVersion, String objectType, String objectId, Map<String, Object> fields) throws UnsupportedEncodingException, IOException { HttpEntity fieldsData = prepareFieldsData(fields); return new RestRequest(RestMethod.PATCH, RestAction.UPDATE.getPath(apiVersion, objectType, objectId), fieldsData); } /** * Request to upsert (update or insert) a record. * See http://www.salesforce.com/us/developer/docs/api_rest/Content/resources_sobject_upsert.htm * * @param apiVersion * @param objectType * @param externalIdField * @param externalId * @param fields * @return a RestRequest * @throws IOException * @throws UnsupportedEncodingException * @throws JsonMappingException * @throws JsonGenerationException */ public static RestRequest getRequestForUpsert(String apiVersion, String objectType, String externalIdField, String externalId, Map<String, Object> fields) throws UnsupportedEncodingException, IOException { HttpEntity fieldsData = prepareFieldsData(fields); return new RestRequest(RestMethod.PATCH, RestAction.UPSERT.getPath(apiVersion, objectType, externalIdField, externalId), fieldsData); } /** * Request to delete a record. * See http://www.salesforce.com/us/developer/docs/api_rest/Content/resources_sobject_retrieve.htm * * @param apiVersion * @param objectType * @param objectId * @return a RestRequest */ public static RestRequest getRequestForDelete(String apiVersion, String objectType, String objectId) { return new RestRequest(RestMethod.DELETE, RestAction.DELETE.getPath(apiVersion, objectType, objectId), null); } /** * Request to execute the specified SOSL search. * See http://www.salesforce.com/us/developer/docs/api_rest/Content/resources_search.htm * * @param apiVersion * @param q * @return a RestRequest * @throws UnsupportedEncodingException */ public static RestRequest getRequestForSearch(String apiVersion, String q) throws UnsupportedEncodingException { StringBuilder path = new StringBuilder(RestAction.SEARCH.getPath(apiVersion)); path.append("?q="); path.append(URLEncoder.encode(q, HTTP.UTF_8)); return new RestRequest(RestMethod.GET, path.toString(), null); } /** * Request to execute the specified SOQL search. * See http://www.salesforce.com/us/developer/docs/api_rest/Content/resources_query.htm * * @param apiVersion * @param q * @return a RestRequest * @throws UnsupportedEncodingException */ public static RestRequest getRequestForQuery(String apiVersion, String q) throws UnsupportedEncodingException { StringBuilder path = new StringBuilder(RestAction.QUERY.getPath(apiVersion)); path.append("?q="); path.append(URLEncoder.encode(q, HTTP.UTF_8)); return new RestRequest(RestMethod.GET, path.toString(), null); } /** * Request to execute the specified SOQL search. * See http://www.salesforce.com/us/developer/docs/api_rest/Content/resources_search_scope_order.htm * * @param apiVersion * @param q * @return a RestRequest * @throws UnsupportedEncodingException */ public static RestRequest getRequestForSearchScopeAndOrder(String apiVersion) throws UnsupportedEncodingException { StringBuilder path = new StringBuilder(RestAction.SEARCH_SCOPE_AND_ORDER.getPath(apiVersion)); return new RestRequest(RestMethod.GET, path.toString(), null); } /** * Request to execute the specified SOQL search. * See http://www.salesforce.com/us/developer/docs/api_rest/Content/resources_search_layouts.htm * * @param apiVersion * @param objectList * @return a RestRequest * @throws UnsupportedEncodingException */ public static RestRequest getRequestForSearchResultLayout(String apiVersion, List<String> objectList) throws UnsupportedEncodingException { StringBuilder path = new StringBuilder(RestAction.SEARCH_RESULT_LAYOUT.getPath(apiVersion)); path.append("?q="); path.append(URLEncoder.encode(toCsv(objectList).toString(), HTTP.UTF_8)); return new RestRequest(RestMethod.GET, path.toString(), null); } /** * Jsonize map and create a StringEntity out of it * @param fields * @return * @throws UnsupportedEncodingException */ private static StringEntity prepareFieldsData(Map<String, Object> fields) throws UnsupportedEncodingException { if (fields == null) { return null; } else { StringEntity entity = new StringEntity(new JSONObject(fields).toString(), HTTP.UTF_8); entity.setContentType("application/json"); return entity; } } }
1
14,722
Just fixing a bunch of outdated java docs in this file
forcedotcom-SalesforceMobileSDK-Android
java
@@ -51,7 +51,7 @@ namespace Nethermind.TxPool private readonly object _locker = new(); - private readonly ConcurrentDictionary<Address, AddressNonces> _nonces = + private readonly Dictionary<Address, AddressNonces> _nonces = new(); private readonly LruKeyCache<Keccak> _hashCache = new(MemoryAllowance.TxHashCacheSize,
1
// Copyright (c) 2021 Demerzel Solutions Limited // This file is part of the Nethermind library. // // The Nethermind library is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // The Nethermind library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with the Nethermind. If not, see <http://www.gnu.org/licenses/>. using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using System.Timers; using Nethermind.Core; using Nethermind.Core.Caching; using Nethermind.Core.Crypto; using Nethermind.Core.Specs; using Nethermind.Crypto; using Nethermind.Int256; using Nethermind.Logging; using Nethermind.State; using Nethermind.TxPool.Collections; using Timer = System.Timers.Timer; [assembly: InternalsVisibleTo("Nethermind.Blockchain.Test")] namespace Nethermind.TxPool { /// <summary> /// Stores all pending transactions. These will be used by block producer if this node is a miner / validator /// or simply for broadcasting and tracing in other cases. /// </summary> public class TxPool : ITxPool, IDisposable { public static IComparer<Transaction> DefaultComparer { get; } = CompareTxByGasPrice.Instance .ThenBy(CompareTxByTimestamp.Instance) .ThenBy(CompareTxByPoolIndex.Instance) .ThenBy(CompareTxByGasLimit.Instance); private readonly object _locker = new(); private readonly ConcurrentDictionary<Address, AddressNonces> _nonces = new(); private readonly LruKeyCache<Keccak> _hashCache = new(MemoryAllowance.TxHashCacheSize, Math.Min(1024 * 16, MemoryAllowance.TxHashCacheSize), "tx hashes"); /// <summary> /// Number of blocks after which own transaction will not be resurrected any more /// </summary> private const long FadingTimeInBlocks = 64; /// <summary> /// Notification threshold randomizer seed /// </summary> private static int _seed = Environment.TickCount; /// <summary> /// Random number generator for peer notification threshold - no need to be securely random. /// </summary> private static readonly ThreadLocal<Random> Random = new(() => new Random(Interlocked.Increment(ref _seed))); private readonly SortedPool<Keccak, Transaction, Address> _transactions; private readonly IChainHeadSpecProvider _specProvider; private readonly ITxPoolConfig _txPoolConfig; private readonly IReadOnlyStateProvider _stateProvider; private readonly ITxValidator _validator; private readonly IEthereumEcdsa _ecdsa; protected readonly ILogger _logger; /// <summary> /// Transactions published locally (initiated by this node users). /// </summary> private readonly ConcurrentDictionary<Keccak, Transaction> _ownTransactions = new(); /// <summary> /// Own transactions that were already added to the chain but need more confirmations /// before being removed from pending entirely. /// </summary> private readonly ConcurrentDictionary<Keccak, (Transaction tx, long blockNumber)> _fadingOwnTransactions = new(); /// <summary> /// Long term storage for pending transactions. /// </summary> private readonly ITxStorage _txStorage; /// <summary> /// Connected peers that can be notified about transactions. /// </summary> private readonly ConcurrentDictionary<PublicKey, ITxPoolPeer> _peers = new(); /// <summary> /// Timer for rebroadcasting pending own transactions. /// </summary> private readonly Timer _ownTimer; /// <summary> /// Indexes transactions /// </summary> private ulong _txIndex; /// <summary> /// This class stores all known pending transactions that can be used for block production /// (by miners or validators) or simply informing other nodes about known pending transactions (broadcasting). /// </summary> /// <param name="txStorage">Tx storage used to reject known transactions.</param> /// <param name="ecdsa">Used to recover sender addresses from transaction signatures.</param> /// <param name="specProvider">Used for retrieving information on EIPs that may affect tx signature scheme.</param> /// <param name="txPoolConfig"></param> /// <param name="stateProvider"></param> /// <param name="validator"></param> /// <param name="logManager"></param> /// <param name="comparer"></param> public TxPool(ITxStorage txStorage, IEthereumEcdsa ecdsa, IChainHeadSpecProvider specProvider, ITxPoolConfig txPoolConfig, IReadOnlyStateProvider stateProvider, ITxValidator validator, ILogManager? logManager, IComparer<Transaction>? comparer = null) { _ecdsa = ecdsa ?? throw new ArgumentNullException(nameof(ecdsa)); _logger = logManager?.GetClassLogger() ?? throw new ArgumentNullException(nameof(logManager)); _txStorage = txStorage ?? throw new ArgumentNullException(nameof(txStorage)); _specProvider = specProvider ?? throw new ArgumentNullException(nameof(specProvider)); _txPoolConfig = txPoolConfig; _stateProvider = stateProvider ?? throw new ArgumentNullException(nameof(stateProvider)); _validator = validator ?? throw new ArgumentNullException(nameof(validator)); MemoryAllowance.MemPoolSize = txPoolConfig.Size; ThisNodeInfo.AddInfo("Mem est tx :", $"{(LruCache<Keccak, object>.CalculateMemorySize(32, MemoryAllowance.TxHashCacheSize) + LruCache<Keccak, Transaction>.CalculateMemorySize(4096, MemoryAllowance.MemPoolSize)) / 1000 / 1000}MB" .PadLeft(8)); _transactions = new TxDistinctSortedPool(MemoryAllowance.MemPoolSize, logManager, comparer ?? DefaultComparer); _ownTimer = new Timer(500); _ownTimer.Elapsed += OwnTimerOnElapsed; _ownTimer.AutoReset = false; _ownTimer.Start(); } public uint FutureNonceRetention => _txPoolConfig.FutureNonceRetention; public long? BlockGasLimit { get; set; } = null; public Transaction[] GetPendingTransactions() => _transactions.GetSnapshot(); public int GetPendingTransactionsCount() => _transactions.Count; public IDictionary<Address, Transaction[]> GetPendingTransactionsBySender() => _transactions.GetBucketSnapshot(); public Transaction[] GetOwnPendingTransactions() => _ownTransactions.Values.ToArray(); public void AddPeer(ITxPoolPeer peer) { if (!_peers.TryAdd(peer.Id, peer)) { return; } if (_logger.IsTrace) _logger.Trace($"Added a peer to TX pool: {peer.Enode}"); } public void RemovePeer(PublicKey nodeId) { if (!_peers.TryRemove(nodeId, out _)) { return; } if (_logger.IsTrace) _logger.Trace($"Removed a peer from TX pool: {nodeId}"); } public AddTxResult AddTransaction(Transaction tx, TxHandlingOptions handlingOptions) { if (tx.Hash is null) { throw new ArgumentException($"{nameof(tx.Hash)} not set on {nameof(Transaction)}"); } tx.PoolIndex = Interlocked.Increment(ref _txIndex); NewDiscovered?.Invoke(this, new TxEventArgs(tx)); bool managedNonce = (handlingOptions & TxHandlingOptions.ManagedNonce) == TxHandlingOptions.ManagedNonce; bool isPersistentBroadcast = (handlingOptions & TxHandlingOptions.PersistentBroadcast) == TxHandlingOptions.PersistentBroadcast; if (_logger.IsTrace) _logger.Trace( $"Adding transaction {tx.ToString(" ")} - managed nonce: {managedNonce} | persistent broadcast {isPersistentBroadcast}"); return FilterTransaction(tx, managedNonce) ?? AddCore(tx, isPersistentBroadcast); } private AddTxResult AddCore(Transaction tx, bool isPersistentBroadcast) { if (tx.Hash is null) { return AddTxResult.Invalid; } // !!! do not change it to |= bool isKnown = _hashCache.Get(tx.Hash); /* * we need to make sure that the sender is resolved before adding to the distinct tx pool * as the address is used in the distinct value calculation */ if (!isKnown) { lock (_locker) { isKnown |= !_transactions.TryInsert(tx.Hash, tx); } } if (!isKnown) { isKnown |= (_txStorage.Get(tx.Hash) is not null); } if (isKnown) { // If transaction is a bit older and already known then it may be stored in the persistent storage. Metrics.PendingTransactionsKnown++; if (_logger.IsTrace) _logger.Trace($"Skipped adding transaction {tx.ToString(" ")}, already known."); return AddTxResult.AlreadyKnown; } _hashCache.Set(tx.Hash); HandleOwnTransaction(tx, isPersistentBroadcast); NotifySelectedPeers(tx); StoreTx(tx); NewPending?.Invoke(this, new TxEventArgs(tx)); return AddTxResult.Added; } protected virtual AddTxResult? FilterTransaction(Transaction tx, in bool managedNonce) { if (tx.Hash is null) { return AddTxResult.Invalid; } if (_fadingOwnTransactions.ContainsKey(tx.Hash)) { _fadingOwnTransactions.TryRemove(tx.Hash, out (Transaction Tx, long _) fadingTxHolder); _ownTransactions.TryAdd(fadingTxHolder.Tx.Hash, fadingTxHolder.Tx); _ownTimer.Enabled = true; if (_logger.IsTrace) _logger.Trace($"Skipped adding transaction {tx.ToString(" ")}, already known."); return AddTxResult.Added; } Metrics.PendingTransactionsReceived++; if (!_validator.IsWellFormed(tx, _specProvider.GetSpec())) { // It may happen that other nodes send us transactions that were signed for another chain or don't have enough gas. Metrics.PendingTransactionsDiscarded++; if (_logger.IsTrace) _logger.Trace($"Skipped adding transaction {tx.ToString(" ")}, invalid transaction."); return AddTxResult.Invalid; } var gasLimit = Math.Min(BlockGasLimit ?? long.MaxValue, _txPoolConfig.GasLimit ?? long.MaxValue); if (tx.GasLimit > gasLimit) { if (_logger.IsTrace) _logger.Trace($"Skipped adding transaction {tx.ToString(" ")}, gas limit exceeded."); return AddTxResult.GasLimitExceeded; } /* We have encountered multiple transactions that do not resolve sender address properly. * We need to investigate what these txs are and why the sender address is resolved to null. * Then we need to decide whether we really want to broadcast them. */ if (tx.SenderAddress is null) { tx.SenderAddress = _ecdsa.RecoverAddress(tx); if (tx.SenderAddress is null) { if (_logger.IsTrace) _logger.Trace($"Skipped adding transaction {tx.ToString(" ")}, no sender."); return AddTxResult.PotentiallyUseless; } } // As we have limited number of transaction that we store in mem pool its fairly easy to fill it up with // high-priority garbage transactions. We need to filter them as much as possible to use the tx pool space // efficiently. One call to get account from state is not that costly and it only happens after previous checks. // This was modeled by OpenEthereum behavior. var account = _stateProvider.GetAccount(tx.SenderAddress); var currentNonce = account?.Nonce ?? UInt256.Zero; if (tx.Nonce < currentNonce) { if (_logger.IsTrace) _logger.Trace($"Skipped adding transaction {tx.ToString(" ")}, nonce already used."); return AddTxResult.OldNonce; } if (tx.Nonce > currentNonce + FutureNonceRetention) { if (_logger.IsTrace) _logger.Trace($"Skipped adding transaction {tx.ToString(" ")}, nonce in far future."); return AddTxResult.FutureNonce; } bool overflow = UInt256.MultiplyOverflow(tx.GasPrice, (UInt256) tx.GasLimit, out UInt256 cost); overflow |= UInt256.AddOverflow(cost, tx.Value, out cost); if (overflow) { if (_logger.IsTrace) _logger.Trace($"Skipped adding transaction {tx.ToString(" ")}, cost overflow."); return AddTxResult.BalanceOverflow; } else if ((account?.Balance ?? UInt256.Zero) < cost) { if (_logger.IsTrace) _logger.Trace($"Skipped adding transaction {tx.ToString(" ")}, insufficient funds."); return AddTxResult.InsufficientFunds; } if (managedNonce && CheckOwnTransactionAlreadyUsed(tx, currentNonce)) { if (_logger.IsTrace) _logger.Trace($"Skipped adding transaction {tx.ToString(" ")}, nonce already used."); return AddTxResult.OwnNonceAlreadyUsed; } return null; } private void HandleOwnTransaction(Transaction tx, bool isOwn) { if (isOwn) { _ownTransactions.TryAdd(tx.Hash, tx); _ownTimer.Enabled = true; if (_logger.IsDebug) _logger.Debug($"Broadcasting own transaction {tx.Hash} to {_peers.Count} peers"); if (_logger.IsTrace) _logger.Trace($"Broadcasting transaction {tx.ToString(" ")}"); } } private bool CheckOwnTransactionAlreadyUsed(Transaction transaction, UInt256 currentNonce) { Address address = transaction.SenderAddress; lock (_locker) { if (!_nonces.TryGetValue(address, out var addressNonces)) { addressNonces = new AddressNonces(currentNonce); _nonces.TryAdd(address, addressNonces); } if (!addressNonces.Nonces.TryGetValue(transaction.Nonce, out var nonce)) { nonce = new Nonce(transaction.Nonce); addressNonces.Nonces.TryAdd(transaction.Nonce, new Nonce(transaction.Nonce)); } if (!(nonce.TransactionHash is null && nonce.TransactionHash != transaction.Hash)) { // Nonce conflict if (_logger.IsDebug) _logger.Debug( $"Nonce: {nonce.Value} was already used in transaction: '{nonce.TransactionHash}' and cannot be reused by transaction: '{transaction.Hash}'."); return true; } nonce.SetTransactionHash(transaction.Hash!); } return false; } public void RemoveTransaction(Keccak hash, long blockNumber, bool removeBelowThisTxNonce = false) { if (_fadingOwnTransactions.Count > 0) { /* If we receive a remove transaction call then it means that a block was processed (assumed). * If our fading transaction has been included in the main chain more than FadingTimeInBlocks blocks ago * then we can assume that is is set in stone (or rather blockchain) and we do not have to worry about * it any more. */ foreach ((Keccak fadingHash, (Transaction Tx, long BlockNumber) fadingHolder) in _fadingOwnTransactions) { if (fadingHolder.BlockNumber >= blockNumber - FadingTimeInBlocks) { continue; } _fadingOwnTransactions.TryRemove(fadingHash, out _); // Nonce was correct and will never be used again lock (_locker) { Address? address = fadingHolder.Tx.SenderAddress; if (address is null) { continue; } if (!_nonces.TryGetValue(address, out AddressNonces addressNonces)) { continue; } addressNonces.Nonces.TryRemove(fadingHolder.Tx.Nonce, out _); if (addressNonces.Nonces.IsEmpty) { _nonces.TryRemove(address, out _); } } } } ICollection<Transaction>? bucket; Transaction transaction; lock (_locker) { if (_transactions.TryRemove(hash, out transaction, out bucket)) { RemovedPending?.Invoke(this, new TxEventArgs(transaction)); } } if (_ownTransactions.Count != 0) { bool ownIncluded = _ownTransactions.TryRemove(hash, out Transaction fadingTx); if (ownIncluded) { _fadingOwnTransactions.TryAdd(hash, (fadingTx, blockNumber)); if (_logger.IsInfo) _logger.Trace($"Transaction {hash} created on this node was included in the block"); } } _txStorage.Delete(hash); if (_logger.IsTrace) _logger.Trace($"Deleted a transaction: {hash}"); if (bucket != null && removeBelowThisTxNonce) { lock (_locker) { Transaction? txWithSmallestNonce = bucket.FirstOrDefault(); while (txWithSmallestNonce != null && txWithSmallestNonce.Nonce <= transaction.Nonce) { RemoveTransaction(txWithSmallestNonce.Hash!, blockNumber); txWithSmallestNonce = bucket.FirstOrDefault(); } } } } public bool TryGetPendingTransaction(Keccak hash, out Transaction transaction) { lock (_locker) { if (!_transactions.TryGetValue(hash, out transaction)) { // commented out as it puts too much pressure on the database // and it not really required in any scenario // * tx recovery usually will fetch from pending // * get tx via RPC usually will fetch from block or from pending // * internal tx pool scenarios are handled directly elsewhere // transaction = _txStorage.Get(hash); } } return transaction != null; } // TODO: Ensure that nonce is always valid in case of sending own transactions from different nodes. public UInt256 ReserveOwnTransactionNonce(Address address) { lock (_locker) { if (!_nonces.TryGetValue(address, out var addressNonces)) { var currentNonce = _stateProvider.GetNonce(address); addressNonces = new AddressNonces(currentNonce); _nonces.TryAdd(address, addressNonces); return currentNonce; } Nonce incrementedNonce = addressNonces.ReserveNonce(); return incrementedNonce.Value; } } public void Dispose() { _ownTimer.Dispose(); } public event EventHandler<TxEventArgs>? NewDiscovered; public event EventHandler<TxEventArgs>? NewPending; public event EventHandler<TxEventArgs>? RemovedPending; private void Notify(ITxPoolPeer peer, Transaction tx, bool isPriority) { try { peer.SendNewTransaction(tx, isPriority); Metrics.PendingTransactionsSent++; if (_logger.IsTrace) _logger.Trace($"Notified {peer.Enode} about a transaction: {tx.Hash}"); } catch (Exception e) { if (_logger.IsError) _logger.Error($"Failed to notify {peer.Enode} about a transaction: {tx.Hash}", e); } } private void NotifyAllPeers(Transaction tx) { Task.Run(() => { foreach ((_, ITxPoolPeer peer) in _peers) { Notify(peer, tx, true); } }); } private void NotifySelectedPeers(Transaction tx) { Task.Run(() => { foreach ((_, ITxPoolPeer peer) in _peers) { if (tx.DeliveredBy == null) { Notify(peer, tx, true); continue; } if (tx.DeliveredBy.Equals(peer.Id)) { continue; } if (_txPoolConfig.PeerNotificationThreshold < Random.Value.Next(1, 100)) { continue; } Notify(peer, tx, 3 < Random.Value.Next(1, 10)); } }); } private void StoreTx(Transaction tx) { _txStorage.Add(tx); if (_logger.IsTrace) _logger.Trace($"Added a transaction: {tx.Hash}"); } private void OwnTimerOnElapsed(object sender, ElapsedEventArgs e) { if (_ownTransactions.Count > 0) { foreach ((_, Transaction tx) in _ownTransactions) { NotifyAllPeers(tx); } // we only reenable the timer if there are any transaction pending // otherwise adding own transaction will reenable the timer anyway _ownTimer.Enabled = true; } } private class AddressNonces { private Nonce _currentNonce; public ConcurrentDictionary<UInt256, Nonce> Nonces { get; } = new(); public AddressNonces(UInt256 startNonce) { _currentNonce = new Nonce(startNonce); Nonces.TryAdd(_currentNonce.Value, _currentNonce); } public Nonce ReserveNonce() { var nonce = _currentNonce.Increment(); Interlocked.Exchange(ref _currentNonce, nonce); Nonces.TryAdd(nonce.Value, nonce); return nonce; } } private class Nonce { public UInt256 Value { get; } public Keccak? TransactionHash { get; private set; } public Nonce(UInt256 value) { Value = value; } public void SetTransactionHash(Keccak transactionHash) { TransactionHash = transactionHash; } public Nonce Increment() => new(Value + 1); } } }
1
25,102
I think it may be safer not to touch Concurrent to normal.
NethermindEth-nethermind
.cs
@@ -158,6 +158,10 @@ class Server extends EventEmitter { // setup listeners this.s.pool.on('parseError', parseErrorEventHandler(this)); + this.s.pool.on('drain', err => { + this.emit('error', err); + }); + // it is unclear whether consumers should even know about these events // this.s.pool.on('timeout', timeoutEventHandler(this)); // this.s.pool.on('reconnect', reconnectEventHandler(this));
1
'use strict'; const EventEmitter = require('events'); const MongoError = require('../error').MongoError; const Pool = require('../connection/pool'); const relayEvents = require('../utils').relayEvents; const wireProtocol = require('../wireprotocol'); const BSON = require('../connection/utils').retrieveBSON(); const createClientInfo = require('../topologies/shared').createClientInfo; const Logger = require('../connection/logger'); const ServerDescription = require('./server_description').ServerDescription; const ReadPreference = require('../topologies/read_preference'); const monitorServer = require('./monitoring').monitorServer; const MongoParseError = require('../error').MongoParseError; const MongoNetworkError = require('../error').MongoNetworkError; const collationNotSupported = require('../utils').collationNotSupported; const debugOptions = require('../connection/utils').debugOptions; const isSDAMUnrecoverableError = require('../error').isSDAMUnrecoverableError; const makeStateMachine = require('../utils').makeStateMachine; const common = require('./common'); // Used for filtering out fields for logging const DEBUG_FIELDS = [ 'reconnect', 'reconnectTries', 'reconnectInterval', 'emitError', 'cursorFactory', 'host', 'port', 'size', 'keepAlive', 'keepAliveInitialDelay', 'noDelay', 'connectionTimeout', 'checkServerIdentity', 'socketTimeout', 'ssl', 'ca', 'crl', 'cert', 'key', 'rejectUnauthorized', 'promoteLongs', 'promoteValues', 'promoteBuffers', 'servername' ]; const STATE_CLOSING = common.STATE_CLOSING; const STATE_CLOSED = common.STATE_CLOSED; const STATE_CONNECTING = common.STATE_CONNECTING; const STATE_CONNECTED = common.STATE_CONNECTED; const stateTransition = makeStateMachine({ [STATE_CLOSED]: [STATE_CLOSED, STATE_CONNECTING], [STATE_CONNECTING]: [STATE_CONNECTING, STATE_CLOSING, STATE_CONNECTED, STATE_CLOSED], [STATE_CONNECTED]: [STATE_CONNECTED, STATE_CLOSING, STATE_CLOSED], [STATE_CLOSING]: [STATE_CLOSING, STATE_CLOSED] }); /** * * @fires Server#serverHeartbeatStarted * @fires Server#serverHeartbeatSucceeded * @fires Server#serverHeartbeatFailed */ class Server extends EventEmitter { /** * Create a server * * @param {ServerDescription} description * @param {Object} options */ constructor(description, options, topology) { super(); this.s = { // the server description description, // a saved copy of the incoming options options, // the server logger logger: Logger('Server', options), // the bson parser bson: options.bson || new BSON([ BSON.Binary, BSON.Code, BSON.DBRef, BSON.Decimal128, BSON.Double, BSON.Int32, BSON.Long, BSON.Map, BSON.MaxKey, BSON.MinKey, BSON.ObjectId, BSON.BSONRegExp, BSON.Symbol, BSON.Timestamp ]), // client metadata for the initial handshake clientInfo: createClientInfo(options), // state variable to determine if there is an active server check in progress monitoring: false, // the implementation of the monitoring method monitorFunction: options.monitorFunction || monitorServer, // the connection pool pool: null, // the server state state: STATE_CLOSED, credentials: options.credentials, topology }; } get description() { return this.s.description; } get name() { return this.s.description.address; } get autoEncrypter() { if (this.s.options && this.s.options.autoEncrypter) { return this.s.options.autoEncrypter; } return null; } /** * Initiate server connect */ connect(options) { options = options || {}; // do not allow connect to be called on anything that's not disconnected if (this.s.pool && !this.s.pool.isDisconnected() && !this.s.pool.isDestroyed()) { throw new MongoError(`Server instance in invalid state ${this.s.pool.state}`); } // create a pool const addressParts = this.description.address.split(':'); const poolOptions = Object.assign( { host: addressParts[0], port: parseInt(addressParts[1], 10) }, this.s.options, options, { bson: this.s.bson } ); // NOTE: reconnect is explicitly false because of the server selection loop poolOptions.reconnect = false; poolOptions.legacyCompatMode = false; this.s.pool = new Pool(this, poolOptions); // setup listeners this.s.pool.on('parseError', parseErrorEventHandler(this)); // it is unclear whether consumers should even know about these events // this.s.pool.on('timeout', timeoutEventHandler(this)); // this.s.pool.on('reconnect', reconnectEventHandler(this)); // this.s.pool.on('reconnectFailed', errorEventHandler(this)); // relay all command monitoring events relayEvents(this.s.pool, this, ['commandStarted', 'commandSucceeded', 'commandFailed']); stateTransition(this, STATE_CONNECTING); this.s.pool.connect(connectEventHandler(this)); } /** * Destroy the server connection * * @param {Boolean} [options.force=false] Force destroy the pool */ destroy(options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = Object.assign({}, { force: false }, options); if (this.s.state === STATE_CLOSED) { if (typeof callback === 'function') { callback(); } return; } stateTransition(this, STATE_CLOSING); const done = err => { stateTransition(this, STATE_CLOSED); this.emit('closed'); if (typeof callback === 'function') { callback(err, null); } }; if (!this.s.pool) { return done(); } ['close', 'error', 'timeout', 'parseError', 'connect'].forEach(event => { this.s.pool.removeAllListeners(event); }); if (this.s.monitorId) { clearTimeout(this.s.monitorId); } this.s.pool.destroy(options.force, done); } /** * Immediately schedule monitoring of this server. If there already an attempt being made * this will be a no-op. */ monitor(options) { options = options || {}; if (this.s.state !== STATE_CONNECTED || this.s.monitoring) return; if (this.s.monitorId) clearTimeout(this.s.monitorId); this.s.monitorFunction(this, options); } /** * Execute a command * * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) * @param {object} cmd The command hash * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. * @param {Boolean} [options.checkKeys=false] Specify if the bson parser should validate keys. * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. * @param {Boolean} [options.fullResult=false] Return the full envelope instead of just the result document. * @param {ClientSession} [options.session=null] Session to use for the operation * @param {opResultCallback} callback A callback function */ command(ns, cmd, options, callback) { if (typeof options === 'function') { (callback = options), (options = {}), (options = options || {}); } if (this.s.state === STATE_CLOSING || this.s.state === STATE_CLOSED) { callback(new MongoError('server is closed')); return; } const error = basicReadValidations(this, options); if (error) { return callback(error, null); } // Clone the options options = Object.assign({}, options, { wireProtocolCommand: false }); // Debug log if (this.s.logger.isDebug()) { this.s.logger.debug( `executing command [${JSON.stringify({ ns, cmd, options: debugOptions(DEBUG_FIELDS, options) })}] against ${this.name}` ); } // error if collation not supported if (collationNotSupported(this, cmd)) { callback(new MongoError(`server ${this.name} does not support collation`)); return; } wireProtocol.command(this, ns, cmd, options, (err, result) => { if (err) { if (options.session && err instanceof MongoNetworkError) { options.session.serverSession.isDirty = true; } if (isSDAMUnrecoverableError(err, this)) { this.emit('error', err); } } callback(err, result); }); } /** * Execute a query against the server * * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) * @param {object} cmd The command document for the query * @param {object} options Optional settings * @param {function} callback */ query(ns, cmd, cursorState, options, callback) { if (this.s.state === STATE_CLOSING || this.s.state === STATE_CLOSED) { callback(new MongoError('server is closed')); return; } wireProtocol.query(this, ns, cmd, cursorState, options, (err, result) => { if (err) { if (options.session && err instanceof MongoNetworkError) { options.session.serverSession.isDirty = true; } if (isSDAMUnrecoverableError(err, this)) { this.emit('error', err); } } callback(err, result); }); } /** * Execute a `getMore` against the server * * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) * @param {object} cursorState State data associated with the cursor calling this method * @param {object} options Optional settings * @param {function} callback */ getMore(ns, cursorState, batchSize, options, callback) { if (this.s.state === STATE_CLOSING || this.s.state === STATE_CLOSED) { callback(new MongoError('server is closed')); return; } wireProtocol.getMore(this, ns, cursorState, batchSize, options, (err, result) => { if (err) { if (options.session && err instanceof MongoNetworkError) { options.session.serverSession.isDirty = true; } if (isSDAMUnrecoverableError(err, this)) { this.emit('error', err); } } callback(err, result); }); } /** * Execute a `killCursors` command against the server * * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) * @param {object} cursorState State data associated with the cursor calling this method * @param {function} callback */ killCursors(ns, cursorState, callback) { if (this.s.state === STATE_CLOSING || this.s.state === STATE_CLOSED) { if (typeof callback === 'function') { callback(new MongoError('server is closed')); } return; } wireProtocol.killCursors(this, ns, cursorState, (err, result) => { if (err && isSDAMUnrecoverableError(err, this)) { this.emit('error', err); } if (typeof callback === 'function') { callback(err, result); } }); } /** * Insert one or more documents * @method * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) * @param {array} ops An array of documents to insert * @param {boolean} [options.ordered=true] Execute in order or out of order * @param {object} [options.writeConcern={}] Write concern for the operation * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. * @param {ClientSession} [options.session=null] Session to use for the operation * @param {opResultCallback} callback A callback function */ insert(ns, ops, options, callback) { executeWriteOperation({ server: this, op: 'insert', ns, ops }, options, callback); } /** * Perform one or more update operations * @method * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) * @param {array} ops An array of updates * @param {boolean} [options.ordered=true] Execute in order or out of order * @param {object} [options.writeConcern={}] Write concern for the operation * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. * @param {ClientSession} [options.session=null] Session to use for the operation * @param {opResultCallback} callback A callback function */ update(ns, ops, options, callback) { executeWriteOperation({ server: this, op: 'update', ns, ops }, options, callback); } /** * Perform one or more remove operations * @method * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) * @param {array} ops An array of removes * @param {boolean} [options.ordered=true] Execute in order or out of order * @param {object} [options.writeConcern={}] Write concern for the operation * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. * @param {ClientSession} [options.session=null] Session to use for the operation * @param {opResultCallback} callback A callback function */ remove(ns, ops, options, callback) { executeWriteOperation({ server: this, op: 'remove', ns, ops }, options, callback); } } Object.defineProperty(Server.prototype, 'clusterTime', { get: function() { return this.s.topology.clusterTime; }, set: function(clusterTime) { this.s.topology.clusterTime = clusterTime; } }); function basicWriteValidations(server) { if (!server.s.pool) { return new MongoError('server instance is not connected'); } if (server.s.pool.isDestroyed()) { return new MongoError('server instance pool was destroyed'); } return null; } function basicReadValidations(server, options) { const error = basicWriteValidations(server, options); if (error) { return error; } if (options.readPreference && !(options.readPreference instanceof ReadPreference)) { return new MongoError('readPreference must be an instance of ReadPreference'); } } function executeWriteOperation(args, options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || {}; // TODO: once we drop Node 4, use destructuring either here or in arguments. const server = args.server; const op = args.op; const ns = args.ns; const ops = Array.isArray(args.ops) ? args.ops : [args.ops]; if (server.s.state === STATE_CLOSING || server.s.state === STATE_CLOSED) { callback(new MongoError('server is closed')); return; } const error = basicWriteValidations(server, options); if (error) { callback(error, null); return; } if (collationNotSupported(server, options)) { callback(new MongoError(`server ${server.name} does not support collation`)); return; } return wireProtocol[op](server, ns, ops, options, (err, result) => { if (err) { if (options.session && err instanceof MongoNetworkError) { options.session.serverSession.isDirty = true; } if (isSDAMUnrecoverableError(err, server)) { server.emit('error', err); } } callback(err, result); }); } function connectEventHandler(server) { return function(err, conn) { if (server.s.state === STATE_CLOSING || server.s.state === STATE_CLOSED) { return; } if (err) { server.emit('error', new MongoNetworkError(err)); stateTransition(server, STATE_CLOSED); server.emit('close'); return; } const ismaster = conn.ismaster; server.s.lastIsMasterMS = conn.lastIsMasterMS; if (conn.agreedCompressor) { server.s.pool.options.agreedCompressor = conn.agreedCompressor; } if (conn.zlibCompressionLevel) { server.s.pool.options.zlibCompressionLevel = conn.zlibCompressionLevel; } if (conn.ismaster.$clusterTime) { const $clusterTime = conn.ismaster.$clusterTime; server.s.sclusterTime = $clusterTime; } // log the connection event if requested if (server.s.logger.isInfo()) { server.s.logger.info( `server ${server.name} connected with ismaster [${JSON.stringify(ismaster)}]` ); } // we are connected and handshaked (guaranteed by the pool) stateTransition(server, STATE_CONNECTED); server.emit('connect', server); // emit an event indicating that our description has changed server.emit('descriptionReceived', new ServerDescription(server.description.address, ismaster)); }; } function parseErrorEventHandler(server) { return function(err) { stateTransition(this, STATE_CLOSED); server.emit('error', new MongoParseError(err)); }; } module.exports = { Server };
1
16,892
is this for everything, or just legacy?
mongodb-node-mongodb-native
js
@@ -368,6 +368,15 @@ function processNewChange(args) { const change = args.change; const callback = args.callback; const eventEmitter = args.eventEmitter || false; + + if (changeStream.isClosed()) { + if (eventEmitter) return; + + const error = new Error('ChangeStream is closed'); + if (typeof callback === 'function') return callback(error, null); + return changeStream.promiseLibrary.reject(error); + } + const topology = changeStream.topology; const options = changeStream.cursor.options;
1
'use strict'; const EventEmitter = require('events'); const isResumableError = require('./error').isResumableError; const MongoError = require('mongodb-core').MongoError; var cursorOptionNames = ['maxAwaitTimeMS', 'collation', 'readPreference']; const CHANGE_DOMAIN_TYPES = { COLLECTION: Symbol('Collection'), DATABASE: Symbol('Database'), CLUSTER: Symbol('Cluster') }; /** * Creates a new Change Stream instance. Normally created using {@link Collection#watch|Collection.watch()}. * @class ChangeStream * @since 3.0.0 * @param {(MongoClient|Db|Collection)} changeDomain The domain against which to create the change stream * @param {Array} pipeline An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents * @param {object} [options] Optional settings * @param {string} [options.fullDocument='default'] Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred. * @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a change stream query * @param {object} [options.resumeAfter] Specifies the logical starting point for the new change stream. This should be the _id field from a previously returned change stream document. * @param {number} [options.batchSize] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. * @param {object} [options.collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. * @param {ReadPreference} [options.readPreference] The read preference. Defaults to the read preference of the database or collection. See {@link https://docs.mongodb.com/manual/reference/read-preference|read preference documentation}. * @fires ChangeStream#close * @fires ChangeStream#change * @fires ChangeStream#end * @fires ChangeStream#error * @return {ChangeStream} a ChangeStream instance. */ class ChangeStream extends EventEmitter { constructor(changeDomain, pipeline, options) { super(); const Collection = require('./collection'); const Db = require('./db'); const MongoClient = require('./mongo_client'); this.pipeline = pipeline || []; this.options = options || {}; this.cursorNamespace = undefined; this.namespace = {}; if (changeDomain instanceof Collection) { this.type = CHANGE_DOMAIN_TYPES.COLLECTION; this.topology = changeDomain.s.db.serverConfig; this.namespace = { collection: changeDomain.collectionName, database: changeDomain.s.db.databaseName }; this.cursorNamespace = `${this.namespace.database}.${this.namespace.collection}`; } else if (changeDomain instanceof Db) { this.type = CHANGE_DOMAIN_TYPES.DATABASE; this.namespace = { collection: '', database: changeDomain.databaseName }; this.cursorNamespace = this.namespace.database; this.topology = changeDomain.serverConfig; } else if (changeDomain instanceof MongoClient) { this.type = CHANGE_DOMAIN_TYPES.CLUSTER; this.namespace = { collection: '', database: 'admin' }; this.cursorNamespace = this.namespace.database; this.topology = changeDomain.topology; } else { throw new TypeError( 'changeDomain provided to ChangeStream constructor is not an instance of Collection, Db, or MongoClient' ); } this.promiseLibrary = changeDomain.s.promiseLibrary; if (!this.options.readPreference && changeDomain.s.readPreference) { this.options.readPreference = changeDomain.s.readPreference; } // We need to get the operationTime as early as possible const isMaster = this.topology.lastIsMaster(); if (!isMaster) { throw new MongoError('Topology does not have an ismaster yet.'); } this.operationTime = isMaster.operationTime; // Create contained Change Stream cursor this.cursor = createChangeStreamCursor(this); // Listen for any `change` listeners being added to ChangeStream this.on('newListener', eventName => { if (eventName === 'change' && this.cursor && this.listenerCount('change') === 0) { this.cursor.on('data', change => processNewChange({ changeStream: this, change, eventEmitter: true }) ); } }); // Listen for all `change` listeners being removed from ChangeStream this.on('removeListener', eventName => { if (eventName === 'change' && this.listenerCount('change') === 0 && this.cursor) { this.cursor.removeAllListeners('data'); } }); } /** * Check if there is any document still available in the Change Stream * @function ChangeStream.prototype.hasNext * @param {ChangeStream~resultCallback} [callback] The result callback. * @throws {MongoError} * @return {Promise} returns Promise if no callback passed */ hasNext(callback) { return this.cursor.hasNext(callback); } /** * Get the next available document from the Change Stream, returns null if no more documents are available. * @function ChangeStream.prototype.next * @param {ChangeStream~resultCallback} [callback] The result callback. * @throws {MongoError} * @return {Promise} returns Promise if no callback passed */ next(callback) { var self = this; if (this.isClosed()) { if (callback) return callback(new Error('Change Stream is not open.'), null); return self.promiseLibrary.reject(new Error('Change Stream is not open.')); } return this.cursor .next() .then(change => processNewChange({ changeStream: self, change, callback })) .catch(error => processNewChange({ changeStream: self, error, callback })); } /** * Is the cursor closed * @method ChangeStream.prototype.isClosed * @return {boolean} */ isClosed() { if (this.cursor) { return this.cursor.isClosed(); } return true; } /** * Close the Change Stream * @method ChangeStream.prototype.close * @param {ChangeStream~resultCallback} [callback] The result callback. * @return {Promise} returns Promise if no callback passed */ close(callback) { if (!this.cursor) { if (callback) return callback(); return this.promiseLibrary.resolve(); } // Tidy up the existing cursor var cursor = this.cursor; delete this.cursor; return cursor.close(callback); } /** * This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream. * @method * @param {Writable} destination The destination for writing data * @param {object} [options] {@link https://nodejs.org/api/stream.html#stream_readable_pipe_destination_options|Pipe options} * @return {null} */ pipe(destination, options) { if (!this.pipeDestinations) { this.pipeDestinations = []; } this.pipeDestinations.push(destination); return this.cursor.pipe(destination, options); } /** * This method will remove the hooks set up for a previous pipe() call. * @param {Writable} [destination] The destination for writing data * @return {null} */ unpipe(destination) { if (this.pipeDestinations && this.pipeDestinations.indexOf(destination) > -1) { this.pipeDestinations.splice(this.pipeDestinations.indexOf(destination), 1); } return this.cursor.unpipe(destination); } /** * Return a modified Readable stream including a possible transform method. * @method * @param {object} [options] Optional settings. * @param {function} [options.transform] A transformation method applied to each document emitted by the stream. * @return {Cursor} */ stream(options) { this.streamOptions = options; return this.cursor.stream(options); } /** * This method will cause a stream in flowing mode to stop emitting data events. Any data that becomes available will remain in the internal buffer. * @return {null} */ pause() { return this.cursor.pause(); } /** * This method will cause the readable stream to resume emitting data events. * @return {null} */ resume() { return this.cursor.resume(); } } // Create a new change stream cursor based on self's configuration var createChangeStreamCursor = function(self) { if (self.resumeToken) { self.options.resumeAfter = self.resumeToken; } var changeStreamCursor = buildChangeStreamAggregationCommand(self); /** * Fired for each new matching change in the specified namespace. Attaching a `change` * event listener to a Change Stream will switch the stream into flowing mode. Data will * then be passed as soon as it is available. * * @event ChangeStream#change * @type {object} */ if (self.listenerCount('change') > 0) { changeStreamCursor.on('data', function(change) { processNewChange({ changeStream: self, change, eventEmitter: true }); }); } /** * Change stream close event * * @event ChangeStream#close * @type {null} */ changeStreamCursor.on('close', function() { self.emit('close'); }); /** * Change stream end event * * @event ChangeStream#end * @type {null} */ changeStreamCursor.on('end', function() { self.emit('end'); }); /** * Fired when the stream encounters an error. * * @event ChangeStream#error * @type {Error} */ changeStreamCursor.on('error', function(error) { processNewChange({ changeStream: self, error, eventEmitter: true }); }); if (self.pipeDestinations) { const cursorStream = changeStreamCursor.stream(self.streamOptions); for (let pipeDestination in self.pipeDestinations) { cursorStream.pipe(pipeDestination); } } return changeStreamCursor; }; function getResumeToken(self) { return self.resumeToken || self.options.resumeAfter; } function getStartAtOperationTime(self) { const isMaster = self.topology.lastIsMaster() || {}; return ( isMaster.maxWireVersion && isMaster.maxWireVersion >= 7 && self.options.startAtOperationTime ); } var buildChangeStreamAggregationCommand = function(self) { const topology = self.topology; const namespace = self.namespace; const pipeline = self.pipeline; const options = self.options; const cursorNamespace = self.cursorNamespace; var changeStreamStageOptions = { fullDocument: options.fullDocument || 'default' }; const resumeToken = getResumeToken(self); const startAtOperationTime = getStartAtOperationTime(self); if (resumeToken) { changeStreamStageOptions.resumeAfter = resumeToken; } if (startAtOperationTime) { changeStreamStageOptions.startAtOperationTime = startAtOperationTime; } // Map cursor options var cursorOptions = {}; cursorOptionNames.forEach(function(optionName) { if (options[optionName]) { cursorOptions[optionName] = options[optionName]; } }); if (self.type === CHANGE_DOMAIN_TYPES.CLUSTER) { changeStreamStageOptions.allChangesForCluster = true; } var changeStreamPipeline = [{ $changeStream: changeStreamStageOptions }]; changeStreamPipeline = changeStreamPipeline.concat(pipeline); var command = { aggregate: self.type === CHANGE_DOMAIN_TYPES.COLLECTION ? namespace.collection : 1, pipeline: changeStreamPipeline, readConcern: { level: 'majority' }, cursor: { batchSize: options.batchSize || 1 } }; // Create and return the cursor return topology.cursor(cursorNamespace, command, cursorOptions); }; // This method performs a basic server selection loop, satisfying the requirements of // ChangeStream resumability until the new SDAM layer can be used. const SELECTION_TIMEOUT = 30000; function waitForTopologyConnected(topology, options, callback) { setTimeout(() => { if (options && options.start == null) options.start = process.hrtime(); const start = options.start || process.hrtime(); const timeout = options.timeout || SELECTION_TIMEOUT; const readPreference = options.readPreference; if (topology.isConnected({ readPreference })) return callback(null, null); const hrElapsed = process.hrtime(start); const elapsed = (hrElapsed[0] * 1e9 + hrElapsed[1]) / 1e6; if (elapsed > timeout) return callback(new MongoError('Timed out waiting for connection')); waitForTopologyConnected(topology, options, callback); }, 3000); // this is an arbitrary wait time to allow SDAM to transition } // Handle new change events. This method brings together the routes from the callback, event emitter, and promise ways of using ChangeStream. function processNewChange(args) { const changeStream = args.changeStream; const error = args.error; const change = args.change; const callback = args.callback; const eventEmitter = args.eventEmitter || false; const topology = changeStream.topology; const options = changeStream.cursor.options; if (error) { if (isResumableError(error) && !changeStream.attemptingResume) { changeStream.attemptingResume = true; if (!(getResumeToken(changeStream) || getStartAtOperationTime(changeStream))) { const startAtOperationTime = changeStream.cursor.cursorState.operationTime; changeStream.options = Object.assign({ startAtOperationTime }, changeStream.options); } // stop listening to all events from old cursor ['data', 'close', 'end', 'error'].forEach(event => changeStream.cursor.removeAllListeners(event) ); // close internal cursor, ignore errors changeStream.cursor.close(); // attempt recreating the cursor if (eventEmitter) { waitForTopologyConnected(topology, { readPreference: options.readPreference }, err => { if (err) return changeStream.emit('error', err); changeStream.cursor = createChangeStreamCursor(changeStream); }); return; } if (callback) { waitForTopologyConnected(topology, { readPreference: options.readPreference }, err => { if (err) return callback(err, null); changeStream.cursor = createChangeStreamCursor(changeStream); changeStream.next(callback); }); return; } return new Promise((resolve, reject) => { waitForTopologyConnected(topology, { readPreference: options.readPreference }, err => { if (err) return reject(err); resolve(); }); }) .then(() => (changeStream.cursor = createChangeStreamCursor(changeStream))) .then(() => changeStream.next()); } if (eventEmitter) return changeStream.emit('error', error); if (typeof callback === 'function') return callback(error, null); return changeStream.promiseLibrary.reject(error); } changeStream.attemptingResume = false; // Cache the resume token if it is present. If it is not present return an error. if (!change || !change._id) { var noResumeTokenError = new Error( 'A change stream document has been received that lacks a resume token (_id).' ); if (eventEmitter) return changeStream.emit('error', noResumeTokenError); if (typeof callback === 'function') return callback(noResumeTokenError, null); return changeStream.promiseLibrary.reject(noResumeTokenError); } changeStream.resumeToken = change._id; // Return the change if (eventEmitter) return changeStream.emit('change', change); if (typeof callback === 'function') return callback(error, change); return changeStream.promiseLibrary.resolve(change); } /** * The callback format for results * @callback ChangeStream~resultCallback * @param {MongoError} error An error instance representing the error during the execution. * @param {(object|null)} result The result object if the command was executed successfully. */ module.exports = ChangeStream;
1
15,194
I think this should be a `MongoError` right?
mongodb-node-mongodb-native
js
@@ -14,8 +14,10 @@ var ( DdevBin = "ddev" DevTestSites = []testcommon.TestSite{ { - Name: "drupal8", - DownloadURL: "https://github.com/drud/drupal8/archive/v0.2.2.tar.gz", + Name: "drupal8", + SourceURL: "https://github.com/drud/drupal8/archive/v0.2.2.tar.gz", + FileURL: "https://github.com/drud/drupal8/releases/download/v0.2.2/files.tar.gz", + DBURL: "https://github.com/drud/drupal8/releases/download/v0.2.2/db.tar.gz", }, } )
1
package cmd import ( "fmt" "os" "testing" log "github.com/Sirupsen/logrus" "github.com/drud/ddev/pkg/testcommon" ) var ( // DdevBin is the full path to the drud binary DdevBin = "ddev" DevTestSites = []testcommon.TestSite{ { Name: "drupal8", DownloadURL: "https://github.com/drud/drupal8/archive/v0.2.2.tar.gz", }, } ) func TestMain(m *testing.M) { if os.Getenv("DDEV_BINARY_FULLPATH") != "" { DdevBin = os.Getenv("DDEV_BINARY_FULLPATH") } fmt.Println("Running ddev with ddev=", DdevBin) err := os.Setenv("DRUD_NONINTERACTIVE", "true") if err != nil { fmt.Println("could not set noninteractive mode") } for i := range DevTestSites { err = DevTestSites[i].Prepare() if err != nil { log.Fatalln("Prepare() failed in TestMain site=%s, err=", DevTestSites[i].Name, err) } } fmt.Println("Running tests.") testRun := m.Run() for i := range DevTestSites { DevTestSites[i].Cleanup() } os.Exit(testRun) }
1
10,876
This is currently a db.tar.gz with just one .sql file in it. It might be worth another test (or maybe I'll find one) that has more than one sql file in it.
drud-ddev
go
@@ -218,6 +218,14 @@ var _ = infrastructure.DatastoreDescribe("VXLAN topology before adding host IPs policy.Spec.Selector = "has(host-endpoint)" _, err = client.GlobalNetworkPolicies().Create(utils.Ctx, policy, utils.NoOptions) Expect(err).NotTo(HaveOccurred()) + + policy = api.NewGlobalNetworkPolicy() + policy.Name = "allow-all-egress-normal" + policy.Spec.Order = &order + policy.Spec.Egress = []api.Rule{{Action: api.Allow}} + policy.Spec.Selector = "has(host-endpoint)" + _, err = client.GlobalNetworkPolicies().Create(utils.Ctx, policy, utils.NoOptions) + Expect(err).NotTo(HaveOccurred()) }) It("should not block any traffic", func() {
1
// Copyright (c) 2020 Tigera, Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // +build fvtests package fv_test import ( "context" "fmt" "strings" "time" "github.com/projectcalico/felix/fv/connectivity" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/projectcalico/felix/fv/infrastructure" "github.com/projectcalico/felix/fv/utils" "github.com/projectcalico/felix/fv/workload" "github.com/projectcalico/libcalico-go/lib/apiconfig" api "github.com/projectcalico/libcalico-go/lib/apis/v3" client "github.com/projectcalico/libcalico-go/lib/clientv3" "github.com/projectcalico/libcalico-go/lib/ipam" "github.com/projectcalico/libcalico-go/lib/net" "github.com/projectcalico/libcalico-go/lib/options" ) var _ = infrastructure.DatastoreDescribe("VXLAN topology before adding host IPs to IP sets", []apiconfig.DatastoreType{apiconfig.EtcdV3, apiconfig.Kubernetes}, func(getInfra infrastructure.InfraFactory) { for _, vxlanM := range []api.VXLANMode{api.VXLANModeCrossSubnet} { vxlanMode := vxlanM Describe(fmt.Sprintf("VXLAN mode set to %s", vxlanMode), func() { var ( infra infrastructure.DatastoreInfra felixes []*infrastructure.Felix client client.Interface w [3]*workload.Workload hostW [3]*workload.Workload cc *connectivity.Checker ) BeforeEach(func() { infra = getInfra() topologyOptions := infrastructure.DefaultTopologyOptions() topologyOptions.VXLANMode = vxlanMode topologyOptions.IPIPEnabled = false topologyOptions.FelixLogSeverity = "debug" felixes, client = infrastructure.StartNNodeTopology(3, topologyOptions, infra) // Install a default profile that allows all ingress and egress, in the absence of any Policy. infra.AddDefaultAllow() // Wait until the vxlan device appears. Eventually(func() error { for i, f := range felixes { out, err := f.ExecOutput("ip", "link") if err != nil { return err } if strings.Contains(out, "vxlan.calico") { continue } return fmt.Errorf("felix %d has no vxlan device", i) } return nil }, "10s", "100ms").ShouldNot(HaveOccurred()) // Create workloads, using that profile. One on each "host". for ii := range w { wIP := fmt.Sprintf("10.65.%d.2", ii) wName := fmt.Sprintf("w%d", ii) err := client.IPAM().AssignIP(context.Background(), ipam.AssignIPArgs{ IP: net.MustParseIP(wIP), HandleID: &wName, Attrs: map[string]string{ ipam.AttributeNode: felixes[ii].Hostname, }, Hostname: felixes[ii].Hostname, }) Expect(err).NotTo(HaveOccurred()) w[ii] = workload.Run(felixes[ii], wName, "default", wIP, "8055", "tcp") w[ii].ConfigureInDatastore(infra) hostW[ii] = workload.Run(felixes[ii], fmt.Sprintf("host%d", ii), "", felixes[ii].IP, "8055", "tcp") } cc = &connectivity.Checker{} }) AfterEach(func() { if CurrentGinkgoTestDescription().Failed { for _, felix := range felixes { felix.Exec("iptables-save", "-c") felix.Exec("ipset", "list") felix.Exec("ip", "r") felix.Exec("ip", "a") } } for _, wl := range w { wl.Stop() } for _, wl := range hostW { wl.Stop() } for _, felix := range felixes { felix.Stop() } if CurrentGinkgoTestDescription().Failed { infra.DumpErrorData() } infra.Stop() }) It("should use the --random-fully flag in the MASQUERADE rules", func() { for _, felix := range felixes { Eventually(func() string { out, _ := felix.ExecOutput("iptables-save", "-c") return out }, "10s", "100ms").Should(ContainSubstring("--random-fully")) } }) It("should have workload to workload connectivity", func() { cc.ExpectSome(w[0], w[1]) cc.ExpectSome(w[1], w[0]) cc.CheckConnectivity() }) It("should have host to workload connectivity", func() { cc.ExpectSome(felixes[0], w[1]) cc.ExpectSome(felixes[0], w[0]) cc.CheckConnectivity() }) It("should have host to host connectivity", func() { cc.ExpectSome(felixes[0], hostW[1]) cc.ExpectSome(felixes[1], hostW[0]) cc.CheckConnectivity() }) Context("with host protection policy in place", func() { BeforeEach(func() { // Make sure our new host endpoints don't cut felix off from the datastore. err := infra.AddAllowToDatastore("host-endpoint=='true'") Expect(err).NotTo(HaveOccurred()) ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() for _, f := range felixes { hep := api.NewHostEndpoint() hep.Name = "eth0-" + f.Name hep.Labels = map[string]string{ "host-endpoint": "true", } hep.Spec.Node = f.Hostname hep.Spec.ExpectedIPs = []string{f.IP} _, err := client.HostEndpoints().Create(ctx, hep, options.SetOptions{}) Expect(err).NotTo(HaveOccurred()) } }) It("should have workload connectivity but not host connectivity", func() { // Host endpoints (with no policies) block host-host traffic due to default drop. cc.ExpectNone(felixes[0], hostW[1]) cc.ExpectNone(felixes[1], hostW[0]) // But the rules to allow VXLAN between our hosts let the workload traffic through. cc.ExpectSome(w[0], w[1]) cc.ExpectSome(w[1], w[0]) cc.CheckConnectivity() }) }) Context("with all-interfaces host protection policy in place", func() { BeforeEach(func() { // Make sure our new host endpoints don't cut felix off from the datastore. err := infra.AddAllowToDatastore("host-endpoint=='true'") Expect(err).NotTo(HaveOccurred()) ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() for _, f := range felixes { hep := api.NewHostEndpoint() hep.Name = "all-interfaces-" + f.Name hep.Labels = map[string]string{ "host-endpoint": "true", } hep.Spec.Node = f.Hostname hep.Spec.ExpectedIPs = []string{f.IP} hep.Spec.InterfaceName = "*" _, err := client.HostEndpoints().Create(ctx, hep, options.SetOptions{}) Expect(err).NotTo(HaveOccurred()) } policy := api.NewGlobalNetworkPolicy() policy.Name = "allow-all-prednat" order := float64(20) policy.Spec.Order = &order policy.Spec.PreDNAT = true policy.Spec.ApplyOnForward = true policy.Spec.Ingress = []api.Rule{{Action: api.Allow}} policy.Spec.Selector = "has(host-endpoint)" _, err = client.GlobalNetworkPolicies().Create(utils.Ctx, policy, utils.NoOptions) Expect(err).NotTo(HaveOccurred()) }) It("should not block any traffic", func() { // An all-interfaces host endpoint does not block any traffic by default. cc.ExpectSome(felixes[0], hostW[1]) cc.ExpectSome(felixes[1], hostW[0]) cc.ExpectSome(w[0], w[1]) cc.ExpectSome(w[1], w[0]) cc.CheckConnectivity() }) }) Context("after removing BGP address from third node", func() { // Simulate having a host send VXLAN traffic from an unknown source, should get blocked. BeforeEach(func() { Eventually(func() int { return getNumIPSetMembers(felixes[0].Container, "cali40all-vxlan-net") }, "5s", "200ms").Should(Equal(len(felixes) - 1)) ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() node, err := client.Nodes().Get(ctx, felixes[2].Hostname, options.GetOptions{}) Expect(err).NotTo(HaveOccurred()) // Pause felix so it can't touch the dataplane! pid := felixes[2].GetFelixPID() felixes[2].Exec("kill", "-STOP", fmt.Sprint(pid)) node.Spec.BGP = nil _, err = client.Nodes().Update(ctx, node, options.SetOptions{}) }) It("should have no connectivity from third felix and expected number of IPs in whitelist", func() { Eventually(func() int { return getNumIPSetMembers(felixes[0].Container, "cali40all-vxlan-net") }, "5s", "200ms").Should(Equal(len(felixes) - 2)) cc.ExpectSome(w[0], w[1]) cc.ExpectSome(w[1], w[0]) cc.ExpectNone(w[0], w[2]) cc.ExpectNone(w[1], w[2]) cc.ExpectNone(w[2], w[0]) cc.ExpectNone(w[2], w[1]) cc.CheckConnectivity() }) }) // Explicitly verify that the VXLAN whitelist IP set is doing its job (since Felix makes multiple dataplane // changes when the BGP IP disappears and we want to make sure that its the whitelist that's causing the // connectivity to drop). Context("after removing BGP address from third node, all felixes paused", func() { // Simulate having a host send VXLAN traffic from an unknown source, should get blocked. BeforeEach(func() { // Check we initially have the expected number of whitelist entries. for _, f := range felixes { // Wait for Felix to set up the whitelist. Eventually(func() int { return getNumIPSetMembers(f.Container, "cali40all-vxlan-net") }, "5s", "200ms").Should(Equal(len(felixes) - 1)) } // Wait until dataplane has settled. cc.ExpectSome(w[0], w[1]) cc.ExpectSome(w[0], w[2]) cc.ExpectSome(w[1], w[2]) cc.CheckConnectivity() cc.ResetExpectations() // Then pause all the felixes. for _, f := range felixes { pid := f.GetFelixPID() f.Exec("kill", "-STOP", fmt.Sprint(pid)) } }) if vxlanMode == api.VXLANModeAlways { It("after manually removing third node from whitelist should have expected connectivity", func() { felixes[0].Exec("ipset", "del", "cali40all-vxlan-net", felixes[2].IP) cc.ExpectSome(w[0], w[1]) cc.ExpectSome(w[1], w[0]) cc.ExpectSome(w[1], w[2]) cc.ExpectNone(w[2], w[0]) cc.CheckConnectivity() }) } }) It("should configure the vxlan device correctly", func() { // The VXLAN device should appear with default MTU, etc. for _, felix := range felixes { Eventually(func() string { out, _ := felix.ExecOutput("ip", "-d", "link", "show", "vxlan.calico") return out }, "10s", "100ms").Should(ContainSubstring("mtu 1410")) Eventually(func() string { out, _ := felix.ExecOutput("ip", "-d", "link", "show", "vxlan.calico") return out }, "10s", "100ms").Should(ContainSubstring("vxlan id 4096")) Eventually(func() string { out, _ := felix.ExecOutput("ip", "-d", "link", "show", "vxlan.calico") return out }, "10s", "100ms").Should(ContainSubstring("dstport 4789")) } // Change the MTU. felixConfig, err := client.FelixConfigurations().Get(context.Background(), "default", options.GetOptions{}) Expect(err).NotTo(HaveOccurred()) mtu := 1400 vni := 4097 port := 4790 felixConfig.Spec.VXLANMTU = &mtu felixConfig.Spec.VXLANPort = &port felixConfig.Spec.VXLANVNI = &vni _, err = client.FelixConfigurations().Update(context.Background(), felixConfig, options.SetOptions{}) Expect(err).NotTo(HaveOccurred()) // Expect the settings to be changed on the device. for _, felix := range felixes { Eventually(func() string { out, _ := felix.ExecOutput("ip", "-d", "link", "show", "vxlan.calico") return out }, "10s", "100ms").Should(ContainSubstring("mtu 1400")) Eventually(func() string { out, _ := felix.ExecOutput("ip", "-d", "link", "show", "vxlan.calico") return out }, "10s", "100ms").Should(ContainSubstring("vxlan id 4097")) Eventually(func() string { out, _ := felix.ExecOutput("ip", "-d", "link", "show", "vxlan.calico") return out }, "10s", "100ms").Should(ContainSubstring("dstport 4790")) } }) It("should delete the vxlan device when vxlan is disabled", func() { // Wait for the VXLAN device to be created. for _, felix := range felixes { Eventually(func() string { out, _ := felix.ExecOutput("ip", "-d", "link", "show", "vxlan.calico") return out }, "10s", "100ms").Should(ContainSubstring("mtu 1410")) } // Disable VXLAN in Felix. felixConfig, err := client.FelixConfigurations().Get(context.Background(), "default", options.GetOptions{}) Expect(err).NotTo(HaveOccurred()) enabled := false felixConfig.Spec.VXLANEnabled = &enabled _, err = client.FelixConfigurations().Update(context.Background(), felixConfig, options.SetOptions{}) Expect(err).NotTo(HaveOccurred()) // Expect the VXLAN device to be deleted. for _, felix := range felixes { Eventually(func() string { out, _ := felix.ExecOutput("ip", "-d", "link", "show", "vxlan.calico") return out }, "10s", "100ms").ShouldNot(ContainSubstring("mtu 1410")) } }) }) } })
1
17,408
Why these changes to existing tests?
projectcalico-felix
c
@@ -141,6 +141,12 @@ namespace Datadog.Trace.Configuration HeaderTags = HeaderTags.Where(kvp => !string.IsNullOrEmpty(kvp.Key) && !string.IsNullOrEmpty(kvp.Value)) .ToDictionary(kvp => kvp.Key.Trim(), kvp => kvp.Value.Trim()); + var serviceNameMappings = source?.GetDictionary(ConfigurationKeys.ServiceNameMappings) + ?.Where(kvp => !string.IsNullOrEmpty(kvp.Key) && !string.IsNullOrEmpty(kvp.Value)) + ?.ToDictionary(kvp => kvp.Key.Trim(), kvp => kvp.Value.Trim()); + + ServiceNameMappings = new ServiceNames(serviceNameMappings); + DogStatsdPort = source?.GetInt32(ConfigurationKeys.DogStatsdPort) ?? // default value 8125;
1
using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using Datadog.Trace.PlatformHelpers; using Datadog.Trace.Util; using Datadog.Trace.Vendors.Serilog; namespace Datadog.Trace.Configuration { /// <summary> /// Contains Tracer settings. /// </summary> public class TracerSettings { /// <summary> /// The default host value for <see cref="AgentUri"/>. /// </summary> public const string DefaultAgentHost = "localhost"; /// <summary> /// The default port value for <see cref="AgentUri"/>. /// </summary> public const int DefaultAgentPort = 8126; /// <summary> /// Initializes a new instance of the <see cref="TracerSettings"/> class with default values. /// </summary> public TracerSettings() : this(null) { } /// <summary> /// Initializes a new instance of the <see cref="TracerSettings"/> class /// using the specified <see cref="IConfigurationSource"/> to initialize values. /// </summary> /// <param name="source">The <see cref="IConfigurationSource"/> to use when retrieving configuration values.</param> public TracerSettings(IConfigurationSource source) { Environment = source?.GetString(ConfigurationKeys.Environment); ServiceName = source?.GetString(ConfigurationKeys.ServiceName) ?? // backwards compatibility for names used in the past source?.GetString("DD_SERVICE_NAME"); ServiceVersion = source?.GetString(ConfigurationKeys.ServiceVersion); TraceEnabled = source?.GetBool(ConfigurationKeys.TraceEnabled) ?? // default value true; if (AzureAppServices.Metadata.IsRelevant && AzureAppServices.Metadata.IsUnsafeToTrace) { TraceEnabled = false; } var disabledIntegrationNames = source?.GetString(ConfigurationKeys.DisabledIntegrations) ?.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries) ?? Enumerable.Empty<string>(); DisabledIntegrationNames = new HashSet<string>(disabledIntegrationNames, StringComparer.OrdinalIgnoreCase); var adonetExcludedTypes = source?.GetString(ConfigurationKeys.AdoNetExcludedTypes) ?.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries) ?? Enumerable.Empty<string>(); AdoNetExcludedTypes = new HashSet<string>(adonetExcludedTypes, StringComparer.OrdinalIgnoreCase); Integrations = new IntegrationSettingsCollection(source); var agentHost = source?.GetString(ConfigurationKeys.AgentHost) ?? // backwards compatibility for names used in the past source?.GetString("DD_TRACE_AGENT_HOSTNAME") ?? source?.GetString("DATADOG_TRACE_AGENT_HOSTNAME") ?? // default value DefaultAgentHost; var agentPort = source?.GetInt32(ConfigurationKeys.AgentPort) ?? // backwards compatibility for names used in the past source?.GetInt32("DATADOG_TRACE_AGENT_PORT") ?? // default value DefaultAgentPort; var agentUri = source?.GetString(ConfigurationKeys.AgentUri) ?? // default value $"http://{agentHost}:{agentPort}"; AgentUri = new Uri(agentUri); TracesPipeName = source?.GetString(ConfigurationKeys.TracesPipeName); TracesPipeTimeoutMs = source?.GetInt32(ConfigurationKeys.TracesPipeTimeoutMs) #if DEBUG ?? 20_000; #else ?? 100; #endif TracesTransport = source?.GetString(ConfigurationKeys.TracesTransport); if (string.Equals(AgentUri.Host, "localhost", StringComparison.OrdinalIgnoreCase)) { // Replace localhost with 127.0.0.1 to avoid DNS resolution. // When ipv6 is enabled, localhost is first resolved to ::1, which fails // because the trace agent is only bound to ipv4. // This causes delays when sending traces. var builder = new UriBuilder(agentUri) { Host = "127.0.0.1" }; AgentUri = builder.Uri; } AnalyticsEnabled = source?.GetBool(ConfigurationKeys.GlobalAnalyticsEnabled) ?? // default value false; LogsInjectionEnabled = source?.GetBool(ConfigurationKeys.LogsInjectionEnabled) ?? // default value false; MaxTracesSubmittedPerSecond = source?.GetInt32(ConfigurationKeys.MaxTracesSubmittedPerSecond) ?? // default value 100; GlobalTags = source?.GetDictionary(ConfigurationKeys.GlobalTags) ?? // backwards compatibility for names used in the past source?.GetDictionary("DD_TRACE_GLOBAL_TAGS") ?? // default value (empty) new ConcurrentDictionary<string, string>(); // Filter out tags with empty keys or empty values, and trim whitespace GlobalTags = GlobalTags.Where(kvp => !string.IsNullOrEmpty(kvp.Key) && !string.IsNullOrEmpty(kvp.Value)) .ToDictionary(kvp => kvp.Key.Trim(), kvp => kvp.Value.Trim()); HeaderTags = source?.GetDictionary(ConfigurationKeys.HeaderTags) ?? // default value (empty) new ConcurrentDictionary<string, string>(); // Filter out tags with empty keys or empty values, and trim whitespace HeaderTags = HeaderTags.Where(kvp => !string.IsNullOrEmpty(kvp.Key) && !string.IsNullOrEmpty(kvp.Value)) .ToDictionary(kvp => kvp.Key.Trim(), kvp => kvp.Value.Trim()); DogStatsdPort = source?.GetInt32(ConfigurationKeys.DogStatsdPort) ?? // default value 8125; TracerMetricsEnabled = source?.GetBool(ConfigurationKeys.TracerMetricsEnabled) ?? // default value false; RuntimeMetricsEnabled = source?.GetBool(ConfigurationKeys.RuntimeMetricsEnabled) ?? false; CustomSamplingRules = source?.GetString(ConfigurationKeys.CustomSamplingRules); GlobalSamplingRate = source?.GetDouble(ConfigurationKeys.GlobalSamplingRate); StartupDiagnosticLogEnabled = source?.GetBool(ConfigurationKeys.StartupDiagnosticLogEnabled) ?? // default value true; var httpServerErrorStatusCodes = source?.GetString(ConfigurationKeys.HttpServerErrorStatusCodes) ?? // Default value "500-599"; HttpServerErrorStatusCodes = ParseHttpCodesToArray(httpServerErrorStatusCodes); var httpClientErrorStatusCodes = source?.GetString(ConfigurationKeys.HttpClientErrorStatusCodes) ?? // Default value "400-499"; HttpClientErrorStatusCodes = ParseHttpCodesToArray(httpClientErrorStatusCodes); TraceQueueSize = source?.GetInt32(ConfigurationKeys.QueueSize) ?? 1000; } /// <summary> /// Gets or sets the default environment name applied to all spans. /// </summary> /// <seealso cref="ConfigurationKeys.Environment"/> public string Environment { get; set; } /// <summary> /// Gets or sets the service name applied to top-level spans and used to build derived service names. /// </summary> /// <seealso cref="ConfigurationKeys.ServiceName"/> public string ServiceName { get; set; } /// <summary> /// Gets or sets the version tag applied to all spans. /// </summary> /// <seealso cref="ConfigurationKeys.ServiceVersion"/> public string ServiceVersion { get; set; } /// <summary> /// Gets or sets a value indicating whether tracing is enabled. /// Default is <c>true</c>. /// </summary> /// <seealso cref="ConfigurationKeys.TraceEnabled"/> public bool TraceEnabled { get; set; } /// <summary> /// Gets or sets a value indicating whether debug is enabled for a tracer. /// This property is obsolete. Manage the debug setting through GlobalSettings. /// </summary> /// <seealso cref="GlobalSettings.DebugEnabled"/> [Obsolete] public bool DebugEnabled { get; set; } /// <summary> /// Gets or sets the names of disabled integrations. /// </summary> /// <seealso cref="ConfigurationKeys.DisabledIntegrations"/> public HashSet<string> DisabledIntegrationNames { get; set; } /// <summary> /// Gets or sets the AdoNet types to exclude from automatic instrumentation. /// </summary> /// <seealso cref="ConfigurationKeys.AdoNetExcludedTypes"/> public HashSet<string> AdoNetExcludedTypes { get; set; } /// <summary> /// Gets or sets the Uri where the Tracer can connect to the Agent. /// Default is <c>"http://localhost:8126"</c>. /// </summary> /// <seealso cref="ConfigurationKeys.AgentUri"/> /// <seealso cref="ConfigurationKeys.AgentHost"/> /// <seealso cref="ConfigurationKeys.AgentPort"/> public Uri AgentUri { get; set; } /// <summary> /// Gets or sets the key used to determine the transport for sending traces. /// Default is <c>null</c>, which will use the default path decided in <see cref="Agent.Api"/>. /// </summary> /// <seealso cref="ConfigurationKeys.TracesTransport"/> public string TracesTransport { get; set; } /// <summary> /// Gets or sets the windows pipe name where the Tracer can connect to the Agent. /// Default is <c>null</c>. /// </summary> /// <seealso cref="ConfigurationKeys.TracesPipeName"/> public string TracesPipeName { get; set; } /// <summary> /// Gets or sets the timeout in milliseconds for the windows named pipe requests. /// Default is <c>100</c>. /// </summary> /// <seealso cref="ConfigurationKeys.TracesPipeTimeoutMs"/> public int TracesPipeTimeoutMs { get; set; } /// <summary> /// Gets or sets the windows pipe name where the Tracer can send stats. /// Default is <c>null</c>. /// </summary> /// <seealso cref="ConfigurationKeys.MetricsPipeName"/> public string MetricsPipeName { get; set; } /// <summary> /// Gets or sets a value indicating whether default Analytics are enabled. /// Settings this value is a shortcut for setting /// <see cref="Configuration.IntegrationSettings.AnalyticsEnabled"/> on some predetermined integrations. /// See the documentation for more details. /// </summary> /// <seealso cref="ConfigurationKeys.GlobalAnalyticsEnabled"/> public bool AnalyticsEnabled { get; set; } /// <summary> /// Gets or sets a value indicating whether correlation identifiers are /// automatically injected into the logging context. /// Default is <c>false</c>. /// </summary> /// <seealso cref="ConfigurationKeys.LogsInjectionEnabled"/> public bool LogsInjectionEnabled { get; set; } /// <summary> /// Gets or sets a value indicating the maximum number of traces set to AutoKeep (p1) per second. /// Default is <c>100</c>. /// </summary> /// <seealso cref="ConfigurationKeys.MaxTracesSubmittedPerSecond"/> public int MaxTracesSubmittedPerSecond { get; set; } /// <summary> /// Gets or sets a value indicating custom sampling rules. /// </summary> /// <seealso cref="ConfigurationKeys.CustomSamplingRules"/> public string CustomSamplingRules { get; set; } /// <summary> /// Gets or sets a value indicating a global rate for sampling. /// </summary> /// <seealso cref="ConfigurationKeys.GlobalSamplingRate"/> public double? GlobalSamplingRate { get; set; } /// <summary> /// Gets a collection of <see cref="Integrations"/> keyed by integration name. /// </summary> public IntegrationSettingsCollection Integrations { get; } /// <summary> /// Gets or sets the global tags, which are applied to all <see cref="Span"/>s. /// </summary> public IDictionary<string, string> GlobalTags { get; set; } /// <summary> /// Gets or sets the map of header keys to tag names, which are applied to the root <see cref="Span"/> of incoming requests. /// </summary> public IDictionary<string, string> HeaderTags { get; set; } /// <summary> /// Gets or sets the port where the DogStatsd server is listening for connections. /// Default is <c>8125</c>. /// </summary> /// <seealso cref="ConfigurationKeys.DogStatsdPort"/> public int DogStatsdPort { get; set; } /// <summary> /// Gets or sets a value indicating whether internal metrics /// are enabled and sent to DogStatsd. /// </summary> public bool TracerMetricsEnabled { get; set; } /// <summary> /// Gets or sets a value indicating whether runtime metrics /// are enabled and sent to DogStatsd. /// </summary> public bool RuntimeMetricsEnabled { get; set; } /// <summary> /// Gets or sets a value indicating whether the use /// of System.Diagnostics.DiagnosticSource is enabled. /// Default is <c>true</c>. /// </summary> /// <remark> /// This value cannot be set in code. Instead, /// set it using the <c>DD_TRACE_DIAGNOSTIC_SOURCE_ENABLED</c> /// environment variable or in configuration files. /// </remark> public bool DiagnosticSourceEnabled { get => GlobalSettings.Source.DiagnosticSourceEnabled; set { } } /// <summary> /// Gets or sets a value indicating whether the diagnostic log at startup is enabled /// </summary> public bool StartupDiagnosticLogEnabled { get; set; } /// <summary> /// Gets or sets the HTTP status code that should be marked as errors for server integrations. /// </summary> /// <seealso cref="ConfigurationKeys.HttpServerErrorStatusCodes"/> internal bool[] HttpServerErrorStatusCodes { get; set; } /// <summary> /// Gets or sets the HTTP status code that should be marked as errors for client integrations. /// </summary> /// <seealso cref="ConfigurationKeys.HttpClientErrorStatusCodes"/> internal bool[] HttpClientErrorStatusCodes { get; set; } /// <summary> /// Gets a value indicating the size of the trace buffer /// </summary> internal int TraceQueueSize { get; } /// <summary> /// Create a <see cref="TracerSettings"/> populated from the default sources /// returned by <see cref="CreateDefaultConfigurationSource"/>. /// </summary> /// <returns>A <see cref="TracerSettings"/> populated from the default sources.</returns> public static TracerSettings FromDefaultSources() { var source = CreateDefaultConfigurationSource(); return new TracerSettings(source); } /// <summary> /// Creates a <see cref="IConfigurationSource"/> by combining environment variables, /// AppSettings where available, and a local datadog.json file, if present. /// </summary> /// <returns>A new <see cref="IConfigurationSource"/> instance.</returns> public static CompositeConfigurationSource CreateDefaultConfigurationSource() { return GlobalSettings.CreateDefaultConfigurationSource(); } /// <summary> /// Sets the HTTP status code that should be marked as errors for client integrations. /// </summary> /// <seealso cref="ConfigurationKeys.HttpClientErrorStatusCodes"/> /// <param name="statusCodes">Status codes that should be marked as errors</param> public void SetHttpClientErrorStatusCodes(IEnumerable<int> statusCodes) { HttpClientErrorStatusCodes = ParseHttpCodesToArray(string.Join(",", statusCodes)); } /// <summary> /// Sets the HTTP status code that should be marked as errors for server integrations. /// </summary> /// <seealso cref="ConfigurationKeys.HttpServerErrorStatusCodes"/> /// <param name="statusCodes">Status codes that should be marked as errors</param> public void SetHttpServerErrorStatusCodes(IEnumerable<int> statusCodes) { HttpServerErrorStatusCodes = ParseHttpCodesToArray(string.Join(",", statusCodes)); } /// <summary> /// Populate the internal structures. Modifying the settings past this point is not supported /// </summary> internal void Freeze() { Integrations.SetDisabledIntegrations(DisabledIntegrationNames); } internal bool IsErrorStatusCode(int statusCode, bool serverStatusCode) { var source = serverStatusCode ? HttpServerErrorStatusCodes : HttpClientErrorStatusCodes; if (source == null) { return false; } if (statusCode >= source.Length) { return false; } return source[statusCode]; } internal bool IsIntegrationEnabled(IntegrationInfo integration, bool defaultValue = true) { if (TraceEnabled && !DomainMetadata.ShouldAvoidAppDomain()) { return Integrations[integration].Enabled ?? defaultValue; } return false; } internal bool IsIntegrationEnabled(string integrationName) { if (TraceEnabled && !DomainMetadata.ShouldAvoidAppDomain()) { bool? enabled = Integrations[integrationName].Enabled; return enabled != false; } return false; } internal double? GetIntegrationAnalyticsSampleRate(IntegrationInfo integration, bool enabledWithGlobalSetting) { var integrationSettings = Integrations[integration]; var analyticsEnabled = integrationSettings.AnalyticsEnabled ?? (enabledWithGlobalSetting && AnalyticsEnabled); return analyticsEnabled ? integrationSettings.AnalyticsSampleRate : (double?)null; } internal bool IsNetStandardFeatureFlagEnabled() { var value = EnvironmentHelpers.GetEnvironmentVariable("DD_TRACE_NETSTANDARD_ENABLED", string.Empty); return value == "1" || value == "true"; } internal bool[] ParseHttpCodesToArray(string httpStatusErrorCodes) { bool[] httpErrorCodesArray = new bool[600]; void TrySetValue(int index) { if (index >= 0 && index < httpErrorCodesArray.Length) { httpErrorCodesArray[index] = true; } } string[] configurationsArray = httpStatusErrorCodes.Replace(" ", string.Empty).Split(','); foreach (string statusConfiguration in configurationsArray) { int startStatus; // Checks that the value about to be used follows the `401-404` structure or single 3 digit number i.e. `401` else log the warning if (!Regex.IsMatch(statusConfiguration, @"^\d{3}-\d{3}$|^\d{3}$")) { Log.Warning("Wrong format '{0}' for DD_HTTP_SERVER/CLIENT_ERROR_STATUSES configuration.", statusConfiguration); } // If statusConfiguration equals a single value i.e. `401` parse the value and save to the array else if (int.TryParse(statusConfiguration, out startStatus)) { TrySetValue(startStatus); } else { string[] statusCodeLimitsRange = statusConfiguration.Split('-'); startStatus = int.Parse(statusCodeLimitsRange[0]); int endStatus = int.Parse(statusCodeLimitsRange[1]); if (endStatus < startStatus) { startStatus = endStatus; endStatus = int.Parse(statusCodeLimitsRange[0]); } for (int statusCode = startStatus; statusCode <= endStatus; statusCode++) { TrySetValue(statusCode); } } } return httpErrorCodesArray; } } }
1
18,827
It should be `IsNullOrWhitespace` I believe, since we're going to trim the value afterwards (and I just realized the other configuration keys have the same issue)
DataDog-dd-trace-dotnet
.cs
@@ -72,9 +72,9 @@ module Bolt # Returns a hash of implementation name, path to executable, input method (if defined), # and any additional files (name and path) - def select_implementation(target, additional_features = []) + def select_implementation(target, provided_features = []) impl = if (impls = implementations) - available_features = target.features + additional_features + available_features = target.features + provided_features impl = impls.find do |imp| remote_impl = imp['remote'] remote_impl = metadata['remote'] if remote_impl.nil?
1
# frozen_string_literal: true module Bolt class NoImplementationError < Bolt::Error def initialize(target, task) msg = "No suitable implementation of #{task.name} for #{target.name}" super(msg, 'bolt/no-implementation') end end # Represents a Task. # @file and @files are mutually exclusive. # @name [String] name of the task # @file [Hash, nil] containing `filename` and `file_content` # @files [Array<Hash>] where each entry includes `name` and `path` # @metadata [Hash] task metadata Task = Struct.new( :name, :file, :files, :metadata ) do attr_reader :remote def initialize(task, remote: false) super(nil, nil, [], {}) @remote = remote task.reject { |k, _| k == 'parameters' }.each { |k, v| self[k] = v } end def remote_instance self.class.new(to_h.each_with_object({}) { |(k, v), h| h[k.to_s] = v }, remote: true) end def description metadata['description'] end def parameters metadata['parameters'] end def supports_noop metadata['supports_noop'] end def module_name name.split('::').first end def tasks_dir File.join(module_name, 'tasks') end def file_map @file_map ||= files.each_with_object({}) { |file, hsh| hsh[file['name']] = file } end private :file_map # This provides a method we can override in subclasses if the 'path' needs # to be fetched or computed. def file_path(file_name) file_map[file_name]['path'] end def implementations metadata['implementations'] end # Returns a hash of implementation name, path to executable, input method (if defined), # and any additional files (name and path) def select_implementation(target, additional_features = []) impl = if (impls = implementations) available_features = target.features + additional_features impl = impls.find do |imp| remote_impl = imp['remote'] remote_impl = metadata['remote'] if remote_impl.nil? Set.new(imp['requirements']).subset?(available_features) && !!remote_impl == @remote end raise NoImplementationError.new(target, self) unless impl impl = impl.dup impl['path'] = file_path(impl['name']) impl.delete('requirements') impl else raise NoImplementationError.new(target, self) unless !!metadata['remote'] == @remote name = files.first['name'] { 'name' => name, 'path' => file_path(name) } end inmethod = impl['input_method'] || metadata['input_method'] impl['input_method'] = inmethod unless inmethod.nil? mfiles = impl.fetch('files', []) + metadata.fetch('files', []) dirnames, filenames = mfiles.partition { |file| file.end_with?('/') } impl['files'] = filenames.map do |file| path = file_path(file) raise "No file found for reference #{file}" if path.nil? { 'name' => file, 'path' => path } end unless dirnames.empty? files.each do |file| name = file['name'] if dirnames.any? { |dirname| name.start_with?(dirname) } impl['files'] << { 'name' => name, 'path' => file_path(name) } end end end impl end end end
1
11,042
This is just for consistency + searchability with the transports
puppetlabs-bolt
rb
@@ -42,6 +42,7 @@ import ( const ( CertFile = "/tmp/kubeedge/certs/edge.crt" KeyFile = "/tmp/kubeedge/certs/edge.key" + ConfigPath = "/tmp/kubeedge/testData" ) //testServer is a fake http server created for testing
1
/* Copyright 2019 The KubeEdge Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package edgehub import ( "errors" "fmt" "net/http" "net/http/httptest" "os" "reflect" "strings" "testing" "time" "github.com/golang/mock/gomock" "github.com/kubeedge/beehive/pkg/core" "github.com/kubeedge/beehive/pkg/core/context" "github.com/kubeedge/beehive/pkg/core/model" "github.com/kubeedge/kubeedge/edge/mocks/edgehub" connect "github.com/kubeedge/kubeedge/edge/pkg/common/cloudconnection" module "github.com/kubeedge/kubeedge/edge/pkg/common/modules" "github.com/kubeedge/kubeedge/edge/pkg/common/util" _ "github.com/kubeedge/kubeedge/edge/pkg/devicetwin" "github.com/kubeedge/kubeedge/edge/pkg/edgehub/config" ) const ( CertFile = "/tmp/kubeedge/certs/edge.crt" KeyFile = "/tmp/kubeedge/certs/edge.key" ) //testServer is a fake http server created for testing var testServer *httptest.Server // mockAdapter is a mocked adapter implementation var mockAdapter *edgehub.MockAdapter //init() starts the test server and generates test certificates for testing func init() { newTestServer() err := util.GenerateTestCertificate("/tmp/kubeedge/certs/", "edge", "edge") if err != nil { panic("Error in creating fake certificates") } } // initMocks is function to initialize mocks func initMocks(t *testing.T) { mockCtrl := gomock.NewController(t) defer mockCtrl.Finish() mockAdapter = edgehub.NewMockAdapter(mockCtrl) } //newTestServer() starts a fake server for testing func newTestServer() { flag := true testServer = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch { case strings.Contains(r.RequestURI, "/proper_request"): w.Write([]byte("ws://127.0.0.1:20000")) case strings.Contains(r.RequestURI, "/bad_request"): w.WriteHeader(http.StatusBadRequest) case strings.Contains(r.RequestURI, "/wrong_url"): if flag { w.WriteHeader(http.StatusNotFound) flag = false } else { w.Write([]byte("ws://127.0.0.1:20000")) } } })) } //TestNewEdgeHubController() tests whether the EdgeHubController returned is correct or not func TestNewEdgeHubController(t *testing.T) { tests := []struct { name string want *Controller controllerConfig config.ControllerConfig }{ {"Testing if EdgeHubController is returned with correct values", &Controller{ config: &config.ControllerConfig{ HeartbeatPeriod: 150 * time.Second, RefreshInterval: 15 * time.Minute, AuthInfosPath: "/var/IEF/secret", PlacementURL: "https://test_ip:port/v1/placement_external/message_queue", ProjectID: "project_id", NodeID: "node_id", }, stopChan: make(chan struct{}), syncKeeper: make(map[string]chan model.Message), }, config.ControllerConfig{ HeartbeatPeriod: 150 * time.Second, RefreshInterval: 15 * time.Minute, AuthInfosPath: "/var/IEF/secret", PlacementURL: "https://test_ip:port/v1/placement_external/message_queue", ProjectID: "project_id", NodeID: "node_id", }, }} for _, tt := range tests { edgeHubConfig := config.GetConfig() edgeHubConfig.CtrConfig = tt.controllerConfig t.Run(tt.name, func(t *testing.T) { got := NewEdgeHubController() if !reflect.DeepEqual(got.context, tt.want.context) { t.Errorf("NewEdgeHubController() Context= %v, want %v", got.context, tt.want.context) } if !reflect.DeepEqual(got.config, tt.want.config) { t.Errorf("NewEdgeHubController() Config = %v, want %v", got.config, tt.want.config) } if !reflect.DeepEqual(got.chClient, tt.want.chClient) { t.Errorf("NewEdgeHubController() chClient = %v, want %v", got.chClient, tt.want.chClient) } if !reflect.DeepEqual(got.keeperLock, tt.want.keeperLock) { t.Errorf("NewEdgeHubController() KeeperLock = %v, want %v", got.keeperLock, tt.want.keeperLock) } if !reflect.DeepEqual(got.syncKeeper, tt.want.syncKeeper) { t.Errorf("NewEdgeHubController() SyncKeeper = %v, want %v", got.syncKeeper, tt.want.syncKeeper) } }) } } //TestInitial() tests the procurement of the cloudhub client func TestInitial(t *testing.T) { controllerConfig := config.ControllerConfig{ HeartbeatPeriod: 150 * time.Second, RefreshInterval: 15 * time.Minute, AuthInfosPath: "/var/IEF/secret", PlacementURL: testServer.URL + "/proper_request", ProjectID: "foo", NodeID: "bar", } tests := []struct { name string controller Controller webSocketConfig config.WebSocketConfig controllerConfig config.ControllerConfig ctx *context.Context expectedError error }{ {"Valid input", Controller{ config: &controllerConfig, stopChan: make(chan struct{}), syncKeeper: make(map[string]chan model.Message), }, config.WebSocketConfig{ CertFilePath: CertFile, KeyFilePath: KeyFile, }, config.ControllerConfig{ PlacementURL: testServer.URL, ProjectID: "foo", NodeID: "bar", }, context.GetContext(context.MsgCtxTypeChannel), nil}, {"Wrong placement URL", Controller{ config: &controllerConfig, stopChan: make(chan struct{}), syncKeeper: make(map[string]chan model.Message), }, config.WebSocketConfig{ CertFilePath: CertFile, KeyFilePath: KeyFile, }, config.ControllerConfig{ PlacementURL: testServer.URL, ProjectID: "foo", NodeID: "bar", }, context.GetContext(context.MsgCtxTypeChannel), nil}, {"No project Id & node Id", Controller{ config: &controllerConfig, stopChan: make(chan struct{}), syncKeeper: make(map[string]chan model.Message), }, config.WebSocketConfig{ CertFilePath: CertFile, KeyFilePath: KeyFile, }, config.ControllerConfig{ PlacementURL: testServer.URL, ProjectID: "", NodeID: "", }, context.GetContext(context.MsgCtxTypeChannel), nil}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { edgeHubConfig := config.GetConfig() edgeHubConfig.WSConfig = tt.webSocketConfig edgeHubConfig.CtrConfig = tt.controllerConfig if err := tt.controller.initial(tt.ctx); err != tt.expectedError { t.Errorf("EdgeHubController_initial() error = %v, expectedError %v", err, tt.expectedError) } }) } } //TestAddKeepChannel() tests the addition of channel to the syncKeeper func TestAddKeepChannel(t *testing.T) { tests := []struct { name string controller Controller msgID string }{ {"Adding a valid keep channel", Controller{ syncKeeper: make(map[string]chan model.Message), }, "test"}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got := tt.controller.addKeepChannel(tt.msgID) if !reflect.DeepEqual(tt.controller.syncKeeper[tt.msgID], got) { t.Errorf("TestController_addKeepChannel() = %v, want %v", got, tt.controller.syncKeeper[tt.msgID]) } }) } } //TestDeleteKeepChannel() tests the deletion of channel in the syncKeeper func TestDeleteKeepChannel(t *testing.T) { tests := []struct { name string controller Controller msgID string }{ {"Deleting a valid keep channel", Controller{ syncKeeper: make(map[string]chan model.Message), }, "test"}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { tt.controller.addKeepChannel(tt.msgID) tt.controller.deleteKeepChannel(tt.msgID) if _, exist := tt.controller.syncKeeper[tt.msgID]; exist { t.Errorf("TestController_deleteKeepChannel = %v, want %v", tt.controller.syncKeeper[tt.msgID], nil) } }) } } //TestIsSyncResponse() tests whether there exists a channel with the given message_id in the syncKeeper func TestIsSyncResponse(t *testing.T) { tests := []struct { name string controller Controller msgID string want bool }{ {"Sync message response case", Controller{ syncKeeper: make(map[string]chan model.Message), }, "test", true, }, {"Non sync message response case", Controller{ syncKeeper: make(map[string]chan model.Message), }, "", false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if tt.want { tt.controller.addKeepChannel(tt.msgID) } if got := tt.controller.isSyncResponse(tt.msgID); got != tt.want { t.Errorf("TestController_isSyncResponse() = %v, want %v", got, tt.want) } }) } } //TestSendToKeepChannel() tests the reception of response in the syncKeep channel func TestSendToKeepChannel(t *testing.T) { message := model.NewMessage("test_id") tests := []struct { name string controller Controller message *model.Message keepChannelParentID string expectedError error }{ {"SyncKeeper Error Case in send to keep channel", Controller{ context: context.GetContext(context.MsgCtxTypeChannel), syncKeeper: make(map[string]chan model.Message), }, message, "wrong_id", fmt.Errorf("failed to get sync keeper channel, messageID:%+v", *message)}, {"Negative Test Case without syncKeeper Error ", Controller{ context: context.GetContext(context.MsgCtxTypeChannel), syncKeeper: make(map[string]chan model.Message), }, model.NewMessage("test_id"), "test_id", fmt.Errorf("failed to send message to sync keep channel")}, {"Send to keep channel with valid input", Controller{ context: context.GetContext(context.MsgCtxTypeChannel), syncKeeper: make(map[string]chan model.Message), }, model.NewMessage("test_id"), "test_id", nil}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { keep := tt.controller.addKeepChannel(tt.keepChannelParentID) if tt.expectedError == nil { receive := func() { <-keep } go receive() } time.Sleep(1 * time.Second) err := tt.controller.sendToKeepChannel(*tt.message) if !reflect.DeepEqual(err, tt.expectedError) { t.Errorf("TestController_sendToKeepChannel() error = %v, expectedError %v", err, tt.expectedError) } }) } } //TestDispatch() tests whether the messages are properly dispatched to their respective modules func TestDispatch(t *testing.T) { tests := []struct { name string controller Controller message *model.Message expectedError error isResponse bool }{ {"dispatch with valid input", Controller{ context: context.GetContext(context.MsgCtxTypeChannel), syncKeeper: make(map[string]chan model.Message), }, model.NewMessage("").BuildRouter(ModuleNameEdgeHub, module.TwinGroup, "", ""), nil, false}, {"Error Case in dispatch", Controller{ context: context.GetContext(context.MsgCtxTypeChannel), syncKeeper: make(map[string]chan model.Message), }, model.NewMessage("test").BuildRouter(ModuleNameEdgeHub, module.EdgedGroup, "", ""), fmt.Errorf("msg_group not found"), true}, {"Response Case in dispatch", Controller{ context: context.GetContext(context.MsgCtxTypeChannel), syncKeeper: make(map[string]chan model.Message), }, model.NewMessage("test").BuildRouter(ModuleNameEdgeHub, module.TwinGroup, "", ""), nil, true}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if tt.expectedError == nil && !tt.isResponse { receive := func() { keepChannel := tt.controller.addKeepChannel(tt.message.GetParentID()) <-keepChannel } go receive() } time.Sleep(1 * time.Second) err := tt.controller.dispatch(*tt.message) if !reflect.DeepEqual(err, tt.expectedError) { t.Errorf("TestController_dispatch() error = %v, wantErr %v", err, tt.expectedError) } }) } } //TestRouteToEdge() is used to test whether the message received from websocket is dispatched to the required modules func TestRouteToEdge(t *testing.T) { initMocks(t) tests := []struct { name string controller Controller receiveTimes int }{ {"Route to edge with proper input", Controller{ context: context.GetContext(context.MsgCtxTypeChannel), chClient: mockAdapter, syncKeeper: make(map[string]chan model.Message), stopChan: make(chan struct{}), }, 0}, {"Receive Error in route to edge", Controller{ context: context.GetContext(context.MsgCtxTypeChannel), chClient: mockAdapter, syncKeeper: make(map[string]chan model.Message), stopChan: make(chan struct{}), }, 1}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { mockAdapter.EXPECT().Receive().Return(*model.NewMessage("test").BuildRouter(ModuleNameEdgeHub, module.EdgedGroup, "", ""), nil).Times(tt.receiveTimes) mockAdapter.EXPECT().Receive().Return(*model.NewMessage("test").BuildRouter(ModuleNameEdgeHub, module.TwinGroup, "", ""), nil).Times(tt.receiveTimes) mockAdapter.EXPECT().Receive().Return(*model.NewMessage(""), errors.New("Connection Refused")).Times(1) go tt.controller.routeToEdge() stop := <-tt.controller.stopChan if stop != struct{}{} { t.Errorf("TestRouteToEdge error got: %v want: %v", stop, struct{}{}) } }) } } //TestSendToCloud() tests whether the send to cloud functionality works properly func TestSendToCloud(t *testing.T) { initMocks(t) msg := model.NewMessage("").BuildHeader("test_id", "", 1) msg.Header.Sync = true tests := []struct { name string controller Controller message model.Message expectedError error waitError bool mockError error }{ {"send to cloud with proper input", Controller{ context: context.GetContext(context.MsgCtxTypeChannel), chClient: mockAdapter, config: &config.ControllerConfig{ HeartbeatPeriod: 6 * time.Second, }, syncKeeper: make(map[string]chan model.Message), }, *msg, nil, false, nil}, {"Wait Error in send to cloud", Controller{ chClient: mockAdapter, config: &config.ControllerConfig{ HeartbeatPeriod: 3 * time.Second, }, syncKeeper: make(map[string]chan model.Message), }, *msg, nil, true, nil}, {"Send Failure in send to cloud", Controller{ chClient: mockAdapter, config: &config.ControllerConfig{ HeartbeatPeriod: 3 * time.Second, }, syncKeeper: make(map[string]chan model.Message), }, model.Message{}, fmt.Errorf("failed to send message, error: Connection Refused"), false, errors.New("Connection Refused")}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { mockAdapter.EXPECT().Send(gomock.Any()).Return(tt.mockError).Times(1) if !tt.waitError && tt.expectedError == nil { go tt.controller.sendToCloud(tt.message) time.Sleep(1 * time.Second) tempChannel := tt.controller.syncKeeper["test_id"] tempChannel <- *model.NewMessage("test_id") time.Sleep(1 * time.Second) if _, exist := tt.controller.syncKeeper["test_id"]; exist { t.Errorf("SendToCloud() error in receiving message") } return } err := tt.controller.sendToCloud(tt.message) if !reflect.DeepEqual(err, tt.expectedError) { t.Errorf("SendToCloud() error = %v, wantErr %v", err, tt.expectedError) } time.Sleep(tt.controller.config.HeartbeatPeriod + 2*time.Second) if _, exist := tt.controller.syncKeeper["test_id"]; exist { t.Errorf("SendToCloud() error in waiting for timeout") } }) } } //TestRouteToCloud() tests the reception of the message from the beehive framework and forwarding of that message to cloud func TestRouteToCloud(t *testing.T) { initMocks(t) testContext := context.GetContext(context.MsgCtxTypeChannel) tests := []struct { name string controller Controller }{ {"Route to cloud with valid input", Controller{ context: testContext, chClient: mockAdapter, stopChan: make(chan struct{}), }}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { mockAdapter.EXPECT().Send(gomock.Any()).Return(errors.New("Connection Refused")).AnyTimes() go tt.controller.routeToCloud() time.Sleep(2 * time.Second) core.Register(&EdgeHub{}) testContext.AddModule(ModuleNameEdgeHub) msg := model.NewMessage("").BuildHeader("test_id", "", 1) testContext.Send(ModuleNameEdgeHub, *msg) stopChan := <-tt.controller.stopChan if stopChan != struct{}{} { t.Errorf("Error in route to cloud") } }) } } //TestKeepalive() tests whether ping message sent to the cloud at regular intervals happens properly func TestKeepalive(t *testing.T) { initMocks(t) tests := []struct { name string controller Controller }{ {"Heartbeat failure Case", Controller{ config: &config.ControllerConfig{ PlacementURL: testServer.URL + "/proper_request", ProjectID: "foo", NodeID: "bar", }, chClient: mockAdapter, stopChan: make(chan struct{}), }}, } edgeHubConfig := config.GetConfig() edgeHubConfig.WSConfig = config.WebSocketConfig{ CertFilePath: CertFile, KeyFilePath: KeyFile, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { mockAdapter.EXPECT().Send(gomock.Any()).Return(nil).Times(1) mockAdapter.EXPECT().Send(gomock.Any()).Return(errors.New("Connection Refused")).Times(1) go tt.controller.keepalive() got := <-tt.controller.stopChan if got != struct{}{} { t.Errorf("TestKeepalive() StopChan = %v, want %v", got, struct{}{}) } }) } } //TestPubConnectInfo() checks the connection information sent to the required group func TestPubConnectInfo(t *testing.T) { initMocks(t) testContext := context.GetContext(context.MsgCtxTypeChannel) tests := []struct { name string controller Controller isConnected bool content string }{ {"Cloud connected case", Controller{ context: testContext, stopChan: make(chan struct{}), syncKeeper: make(map[string]chan model.Message), }, true, connect.CloudConnected}, {"Cloud disconnected case", Controller{ context: testContext, stopChan: make(chan struct{}), syncKeeper: make(map[string]chan model.Message), }, false, connect.CloudDisconnected}, } for _, tt := range tests { modules := core.GetModules() for name, module := range modules { testContext.AddModule(name) testContext.AddModuleGroup(name, module.Group()) } t.Run(tt.name, func(t *testing.T) { tt.controller.pubConnectInfo(tt.isConnected) t.Run("TestMessageContent", func(t *testing.T) { msg, err := testContext.Receive(module.TwinGroup) if err != nil { t.Errorf("Error in receiving message from twin group: %v", err) } else if msg.Content != tt.content { t.Errorf("TestPubConnectInfo() Content of message received in twin group : %v, want: %v", msg.Content, tt.content) } }) }) } } //TestPostUrlRequst() tests the request sent to the placement URL and its corresponding response func TestPostUrlRequst(t *testing.T) { tests := []struct { name string controller Controller client *http.Client want string expectedError error }{ {"post URL request with valid input ", Controller{ config: &config.ControllerConfig{ PlacementURL: testServer.URL + "/proper_request", ProjectID: "foo", NodeID: "bar", }, }, &http.Client{}, "ws://127.0.0.1:20000/foo/bar/events", nil}, {"post URL request with invalid input", Controller{ config: &config.ControllerConfig{ PlacementURL: testServer.URL + "/bad_request", ProjectID: "foo", NodeID: "bar", }, }, &http.Client{}, "", fmt.Errorf("bad request")}, {"post URL request with wrong URL", Controller{ config: &config.ControllerConfig{ PlacementURL: testServer.URL + "/wrong_url", ProjectID: "foo", NodeID: "bar", }, }, &http.Client{}, "ws://127.0.0.1:20000/foo/bar/events", nil}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := tt.controller.postURLRequst(tt.client) if !reflect.DeepEqual(err, tt.expectedError) { t.Errorf("Controller.postUrlRequst() error = %v, expectedError %v", err, tt.expectedError) return } if got != tt.want { t.Errorf("Controller.postUrlRequst() = %v, want %v", got, tt.want) } }) } } //TestGetCloudHubUrl() tests the procurement of the cloudHub URL from the placement server func TestGetCloudHubUrl(t *testing.T) { tests := []struct { name string controller Controller webSocketConfig config.WebSocketConfig want string expectedError error }{ {"Get valid cloudhub URL", Controller{ config: &config.ControllerConfig{ PlacementURL: testServer.URL + "/proper_request", ProjectID: "foo", NodeID: "bar", }, }, config.WebSocketConfig{ CertFilePath: CertFile, KeyFilePath: KeyFile, }, "wss://0.0.0.0:10000/e632aba927ea4ac2b575ec1603d56f10/fb4ebb70-2783-42b8-b3ef-63e2fd6d242e/events", nil}, {"Invalid cloudhub URL", Controller{ config: &config.ControllerConfig{ PlacementURL: testServer.URL + "/bad_request", ProjectID: "foo", NodeID: "bar", }, }, config.WebSocketConfig{ CertFilePath: CertFile, KeyFilePath: KeyFile, }, "wss://0.0.0.0:10000/e632aba927ea4ac2b575ec1603d56f10/fb4ebb70-2783-42b8-b3ef-63e2fd6d242e/events", nil}, {"Wrong certificate paths", Controller{ config: &config.ControllerConfig{ PlacementURL: testServer.URL + "/proper_request", ProjectID: "foo", NodeID: "bar", }, }, config.WebSocketConfig{ CertFilePath: "/wrong_path/edge.crt", KeyFilePath: "/wrong_path/edge.key", }, "wss://0.0.0.0:10000/e632aba927ea4ac2b575ec1603d56f10/fb4ebb70-2783-42b8-b3ef-63e2fd6d242e/events", nil}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { edgeHubConfig := config.GetConfig() edgeHubConfig.WSConfig = tt.webSocketConfig got, err := tt.controller.getCloudHubURL() if !reflect.DeepEqual(err, tt.expectedError) { t.Errorf("Controller.getCloudHubUrl() error = %v, expectedError %v", err, tt.expectedError) } if got != tt.want { t.Errorf("Controller.getCloudHubUrl() = %v, want %v", got, tt.want) } }) } defer func() { err := os.RemoveAll("/tmp/kubeedge/") if err != nil { fmt.Println("Error in Removing temporary files created for testing: ", err) } }() }
1
9,663
please run gofmt.
kubeedge-kubeedge
go
@@ -1,4 +1,4 @@ -package porcelain_test +package porcelain import ( "context"
1
package porcelain_test import ( "context" "testing" "time" cid "gx/ipfs/QmR8BauakNcBa3RbE4nbQu76PDiJgoQgz8AJdhJuiU4TAw/go-cid" "github.com/filecoin-project/go-filecoin/address" "github.com/filecoin-project/go-filecoin/porcelain" "github.com/filecoin-project/go-filecoin/types" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) var newCid = types.NewCidForTestGetter() var newAddr = address.NewForTestGetter() type fakePlumbing struct { assert *assert.Assertions require *require.Assertions msgCid cid.Cid sendCnt int messageSend func(ctx context.Context, from, to address.Address, value *types.AttoFIL, gasPrice types.AttoFIL, gasLimit types.GasUnits, method string, params ...interface{}) (cid.Cid, error) messageWait func(ctx context.Context, msgCid cid.Cid, cb func(*types.Block, *types.SignedMessage, *types.MessageReceipt) error) error } // Satisfy the plumbing API: func (fp *fakePlumbing) MessageSend(ctx context.Context, from, to address.Address, value *types.AttoFIL, gasPrice types.AttoFIL, gasLimit types.GasUnits, method string, params ...interface{}) (cid.Cid, error) { return fp.messageSend(ctx, from, to, value, gasPrice, gasLimit, method, params...) } func (fp *fakePlumbing) MessageWait(ctx context.Context, msgCid cid.Cid, cb func(*types.Block, *types.SignedMessage, *types.MessageReceipt) error) error { return fp.messageWait(ctx, msgCid, cb) } // Fake implementations we'll use. func (fp *fakePlumbing) successfulMessageSend(ctx context.Context, from, to address.Address, value *types.AttoFIL, gasPrice types.AttoFIL, gasLimit types.GasUnits, method string, params ...interface{}) (cid.Cid, error) { fp.msgCid = newCid() fp.sendCnt++ return fp.msgCid, nil } func (fp *fakePlumbing) successfulMessageWait(ctx context.Context, msgCid cid.Cid, cb func(*types.Block, *types.SignedMessage, *types.MessageReceipt) error) error { fp.require.NotEqual(cid.Undef, fp.msgCid) fp.assert.True(fp.msgCid.Equals(msgCid)) cb(&types.Block{}, &types.SignedMessage{}, &types.MessageReceipt{ExitCode: 0, Return: []types.Bytes{}}) return nil } func (fp *fakePlumbing) unsuccessfulMessageWait(ctx context.Context, msgCid cid.Cid, cb func(*types.Block, *types.SignedMessage, *types.MessageReceipt) error) error { fp.require.NotEqual(cid.Undef, fp.msgCid) fp.assert.True(fp.msgCid.Equals(msgCid)) return context.DeadlineExceeded } func TestMessageSendWithRetry(t *testing.T) { t.Parallel() val, gasPrice, gasLimit := types.NewAttoFILFromFIL(0), types.NewGasPrice(0), types.NewGasUnits(0) t.Run("succeeds on first try", func(t *testing.T) { require := require.New(t) assert := assert.New(t) ctx := context.Background() from, to := newAddr(), newAddr() fp := &fakePlumbing{assert: assert, require: require} fp.messageSend = fp.successfulMessageSend fp.messageWait = fp.successfulMessageWait err := porcelain.MessageSendWithRetry(ctx, fp, 10 /* retries */, 1*time.Second /* wait time*/, from, to, val, "", gasPrice, gasLimit) require.NoError(err) assert.Equal(1, fp.sendCnt) }) t.Run("retries if not successful", func(t *testing.T) { require := require.New(t) assert := assert.New(t) ctx := context.Background() from, to := newAddr(), newAddr() fp := &fakePlumbing{assert: assert, require: require} fp.messageSend = fp.successfulMessageSend fp.messageWait = fp.unsuccessfulMessageWait err := porcelain.MessageSendWithRetry(ctx, fp, 10 /* retries */, 1*time.Second /* wait time*/, from, to, val, "", gasPrice, gasLimit) require.NoError(err) assert.Equal(10, fp.sendCnt) }) t.Run("respects top-level context", func(t *testing.T) { require := require.New(t) assert := assert.New(t) ctx, cancel := context.WithCancel(context.Background()) from, to := newAddr(), newAddr() fp := &fakePlumbing{assert: assert, require: require} fp.messageSend = fp.successfulMessageSend // This MessageWait cancels and ctx and returns unsuccessfully. The effect is // canceling the global context during the first run; we expect it not to retry // if that is the case ie sendCnt to be 1. fp.messageWait = func(ctx context.Context, msgCid cid.Cid, cb func(*types.Block, *types.SignedMessage, *types.MessageReceipt) error) error { cancel() return nil } err := porcelain.MessageSendWithRetry(ctx, fp, 10 /* retries */, 1*time.Second /* wait time*/, from, to, val, "", gasPrice, gasLimit) require.Error(err) assert.Equal(1, fp.sendCnt) }) }
1
16,358
thats kind of a bummer, why do we have to give it full access? if it is just for the private interfaces i'd personally rather have those interfaces pollute the public exported symbols than open the tests up like this.
filecoin-project-venus
go
@@ -69,6 +69,11 @@ func (s *store) initialize() { continue } + // Ignore in case appNodes with appID not existed in store. + if s.apps[appID] == nil { + continue + } + // Add the missing resource into the dependedResources of the app. key := provider.MakeResourceKey(an.resource) s.apps[appID].addDependedResource(uid, key, an.resource, now)
1
// Copyright 2020 The PipeCD Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package kubernetes import ( "sync" "time" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" provider "github.com/pipe-cd/pipe/pkg/app/piped/cloudprovider/kubernetes" "github.com/pipe-cd/pipe/pkg/config" "github.com/pipe-cd/pipe/pkg/model" ) const ( eventCacheSize = 900 eventCacheMaxSize = 1000 eventCacheCleanOffset = 50 ) type store struct { pipedConfig *config.PipedSpec apps map[string]*appNodes // The map with the key is "resource's uid" and the value is "appResource". // Because the depended resource does not include the appID in its annotations // so this is used to determine the application of a depended resource. resources map[string]appResource mu sync.RWMutex events []model.KubernetesResourceStateEvent iterators map[int]int nextIteratorID int eventMu sync.Mutex } type appResource struct { appID string owners []metav1.OwnerReference resource *unstructured.Unstructured } func (s *store) initialize() { s.mu.Lock() defer s.mu.Unlock() now := time.Now() // Try to determine the application ID of all resources. for uid, an := range s.resources { // Resource has already assigned into an application. if an.appID != "" { continue } appID := s.findAppIDByOwners(an.owners) if appID == "" { continue } // Add the missing resource into the dependedResources of the app. key := provider.MakeResourceKey(an.resource) s.apps[appID].addDependedResource(uid, key, an.resource, now) an.appID = appID s.resources[uid] = an } // Remove all resources which do not have appID. for uid, an := range s.resources { if an.appID == "" { delete(s.resources, uid) } } // Clean all initial events. s.events = nil } func (s *store) addResource(obj *unstructured.Unstructured, appID string) { var ( uid = string(obj.GetUID()) key = provider.MakeResourceKey(obj) owners = obj.GetOwnerReferences() now = time.Now() ) // If this is a resource managed by PipeCD // it must contain appID in its annotations and has no owners. if appID != "" && len(owners) == 0 { // When this obj is for a new application // we register a new application to the apps. s.mu.Lock() app, ok := s.apps[appID] if !ok { app = &appNodes{ appID: appID, managingNodes: make(map[string]node), dependedNodes: make(map[string]node), version: model.ApplicationLiveStateVersion{ Timestamp: now.Unix(), }, } s.apps[appID] = app } s.mu.Unlock() // Append the resource to the application's managingNodes. if event, ok := app.addManagingResource(uid, key, obj, now); ok { s.addEvent(event) } // And update the resources. s.mu.Lock() s.resources[uid] = appResource{appID: appID, owners: owners, resource: obj} s.mu.Unlock() return } // Try to determine the application ID by traveling its owners. if appID == "" { s.mu.RLock() appID = s.findAppIDByOwners(owners) s.mu.RUnlock() } // Append the resource to the application's dependedNodes. if appID != "" { s.mu.RLock() app, ok := s.apps[appID] s.mu.RUnlock() if ok { if event, ok := app.addDependedResource(uid, key, obj, now); ok { s.addEvent(event) } } } // And update the resources. s.mu.Lock() s.resources[uid] = appResource{appID: appID, owners: owners, resource: obj} s.mu.Unlock() } func (s *store) onAddResource(obj *unstructured.Unstructured) { appID := obj.GetAnnotations()[provider.LabelApplication] s.addResource(obj, appID) } func (s *store) onUpdateResource(oldObj, obj *unstructured.Unstructured) { uid := string(obj.GetUID()) appID := obj.GetAnnotations()[provider.LabelApplication] // Depended nodes may not contain the app id in its annotations. // In that case, preventing them from overwriting with an empty id if appID == "" { s.mu.RLock() if r, ok := s.resources[uid]; ok { appID = r.appID } s.mu.RUnlock() } s.addResource(obj, appID) } func (s *store) onDeleteResource(obj *unstructured.Unstructured) { var ( uid = string(obj.GetUID()) appID = obj.GetAnnotations()[provider.LabelApplication] key = provider.MakeResourceKey(obj) owners = obj.GetOwnerReferences() now = time.Now() ) // If this is a resource managed by PipeCD // it must contain appID in its annotations and has no owners. if appID != "" && len(owners) == 0 { s.mu.Lock() delete(s.resources, uid) s.mu.Unlock() s.mu.RLock() app, ok := s.apps[appID] s.mu.RUnlock() if ok { if event, ok := app.deleteManagingResource(uid, key, now); ok { s.addEvent(event) } } return } // Handle depended nodes from here. if appID == "" { s.mu.RLock() if r, ok := s.resources[uid]; ok { appID = r.appID } s.mu.RUnlock() } // Try to determine the application ID by traveling its owners. if appID == "" { s.mu.RLock() appID = s.findAppIDByOwners(owners) s.mu.RUnlock() } // This must be done before deleting the resource from the dependedNodes // to ensure that all items in the resources list can be found from one of the app. s.mu.Lock() delete(s.resources, uid) s.mu.Unlock() // Delete the resource to the application's dependedNodes. s.mu.RLock() app, ok := s.apps[appID] s.mu.RUnlock() if ok { if event, ok := app.deleteDependedResource(uid, key, now); ok { s.addEvent(event) } } } func (s *store) getAppManagingNodes(appID string) map[string]node { s.mu.RLock() app, ok := s.apps[appID] s.mu.RUnlock() if !ok { return nil } return app.getManagingNodes() } func (s *store) findAppIDByOwners(owners []metav1.OwnerReference) string { for _, ref := range owners { owner, ok := s.resources[string(ref.UID)] // Owner does not present in the resources. if !ok { continue } // The owner is containing the appID. if owner.appID != "" { return owner.appID } // Try with the owners of the owner. if appID := s.findAppIDByOwners(owner.owners); appID != "" { return appID } } return "" } func (s *store) getAppLiveState(appID string) (AppState, bool) { s.mu.RLock() app, ok := s.apps[appID] s.mu.RUnlock() if !ok { return AppState{}, false } var ( nodes, version = app.getNodes() resources = make([]*model.KubernetesResourceState, 0, len(nodes)) ) for i := range nodes { state := nodes[i].state resources = append(resources, &state) } return AppState{ Resources: resources, Version: version, }, true } func (s *store) GetAppLiveManifests(appID string) []provider.Manifest { s.mu.RLock() app, ok := s.apps[appID] s.mu.RUnlock() if !ok { return nil } nodes := app.getManagingNodes() manifests := make([]provider.Manifest, 0, len(nodes)) for i := range nodes { manifests = append(manifests, nodes[i].Manifest()) } return manifests } func (s *store) addEvent(event model.KubernetesResourceStateEvent) { s.eventMu.Lock() defer s.eventMu.Unlock() s.events = append(s.events, event) if len(s.events) < eventCacheMaxSize { return } num := len(s.events) - eventCacheSize s.removeOldEvents(num) } func (s *store) nextEvents(iteratorID, maxNum int) []model.KubernetesResourceStateEvent { s.eventMu.Lock() defer s.eventMu.Unlock() var ( from = s.iterators[iteratorID] to = len(s.events) length = to - from ) if length <= 0 { return nil } if length > maxNum { to = from + maxNum - 1 } events := s.events[from:to] s.iterators[iteratorID] = to s.cleanStaleEvents() return events } func (s *store) cleanStaleEvents() { var min int for _, v := range s.iterators { if v < min { min = v } } if min < eventCacheCleanOffset { return } s.removeOldEvents(min) } func (s *store) removeOldEvents(num int) { if len(s.events) < num { return } s.events = s.events[num-1:] for k := range s.iterators { newIndex := s.iterators[k] - num if newIndex < 0 { newIndex = 0 } s.iterators[k] = newIndex } } func (s *store) newEventIterator() EventIterator { s.eventMu.Lock() id := s.nextIteratorID s.nextIteratorID++ s.eventMu.Unlock() return EventIterator{ id: id, store: s, } }
1
19,351
Because this is an unexpected situation so can you add a log here to help us figure out what resource is causing this problem?
pipe-cd-pipe
go
@@ -554,12 +554,11 @@ public class OverseerCollectionMessageHandler implements OverseerMessageHandler, final String collectionName = message.getStr(ZkStateReader.COLLECTION_PROP); //the rest of the processing is based on writing cluster state properties //remove the property here to avoid any errors down the pipeline due to this property appearing - String configName = (String) message.getProperties().remove(CollectionAdminParams.COLL_CONF); + String configName = (String) message.getProperties().get(CollectionAdminParams.COLL_CONF); if(configName != null) { validateConfigOrThrowSolrException(configName); - createConfNode(cloudManager.getDistribStateManager(), configName, collectionName); reloadCollection(null, new ZkNodeProps(NAME, collectionName), results); }
1
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.solr.cloud.api.collections; import java.io.IOException; import java.lang.invoke.MethodHandles; import java.net.URI; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import com.google.common.collect.ImmutableMap; import org.apache.commons.lang3.StringUtils; import org.apache.solr.client.solrj.SolrResponse; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.cloud.AlreadyExistsException; import org.apache.solr.client.solrj.cloud.BadVersionException; import org.apache.solr.client.solrj.cloud.DistribStateManager; import org.apache.solr.client.solrj.cloud.SolrCloudManager; import org.apache.solr.client.solrj.impl.BaseHttpSolrClient; import org.apache.solr.client.solrj.impl.HttpSolrClient; import org.apache.solr.client.solrj.request.AbstractUpdateRequest; import org.apache.solr.client.solrj.request.UpdateRequest; import org.apache.solr.client.solrj.response.UpdateResponse; import org.apache.solr.cloud.LockTree; import org.apache.solr.cloud.Overseer; import org.apache.solr.cloud.OverseerMessageHandler; import org.apache.solr.cloud.OverseerNodePrioritizer; import org.apache.solr.cloud.OverseerSolrResponse; import org.apache.solr.cloud.Stats; import org.apache.solr.cloud.ZkController; import org.apache.solr.cloud.overseer.ClusterStateMutator; import org.apache.solr.cloud.overseer.OverseerAction; import org.apache.solr.common.SolrCloseable; import org.apache.solr.common.SolrException; import org.apache.solr.common.SolrException.ErrorCode; import org.apache.solr.common.cloud.ClusterState; import org.apache.solr.common.cloud.DocCollection; import org.apache.solr.common.cloud.DocRouter; import org.apache.solr.common.cloud.Replica; import org.apache.solr.common.cloud.Slice; import org.apache.solr.common.cloud.SolrZkClient; import org.apache.solr.common.cloud.UrlScheme; import org.apache.solr.common.cloud.ZkConfigManager; import org.apache.solr.common.cloud.ZkCoreNodeProps; import org.apache.solr.common.cloud.ZkNodeProps; import org.apache.solr.common.cloud.ZkStateReader; import org.apache.solr.common.params.CollectionAdminParams; import org.apache.solr.common.params.CollectionParams.CollectionAction; import org.apache.solr.common.params.CoreAdminParams; import org.apache.solr.common.params.CoreAdminParams.CoreAdminAction; import org.apache.solr.common.params.ModifiableSolrParams; import org.apache.solr.common.util.ExecutorUtil; import org.apache.solr.common.util.NamedList; import org.apache.solr.common.util.SimpleOrderedMap; import org.apache.solr.common.util.SolrNamedThreadFactory; import org.apache.solr.common.util.StrUtils; import org.apache.solr.common.util.SuppressForbidden; import org.apache.solr.common.util.TimeSource; import org.apache.solr.common.util.Utils; import org.apache.solr.core.backup.BackupId; import org.apache.solr.core.backup.repository.BackupRepository; import org.apache.solr.handler.component.HttpShardHandlerFactory; import org.apache.solr.handler.component.ShardHandler; import org.apache.solr.handler.component.ShardRequest; import org.apache.solr.handler.component.ShardResponse; import org.apache.solr.logging.MDCLoggingContext; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.apache.solr.common.cloud.ZkStateReader.COLLECTION_PROP; import static org.apache.solr.common.cloud.ZkStateReader.CORE_NAME_PROP; import static org.apache.solr.common.cloud.ZkStateReader.CORE_NODE_NAME_PROP; import static org.apache.solr.common.cloud.ZkStateReader.ELECTION_NODE_PROP; import static org.apache.solr.common.cloud.ZkStateReader.NODE_NAME_PROP; import static org.apache.solr.common.cloud.ZkStateReader.PROPERTY_PROP; import static org.apache.solr.common.cloud.ZkStateReader.PROPERTY_VALUE_PROP; import static org.apache.solr.common.cloud.ZkStateReader.REJOIN_AT_HEAD_PROP; import static org.apache.solr.common.cloud.ZkStateReader.REPLICA_PROP; import static org.apache.solr.common.cloud.ZkStateReader.SHARD_ID_PROP; import static org.apache.solr.common.params.CollectionAdminParams.COLLECTION; import static org.apache.solr.common.params.CollectionParams.CollectionAction.*; import static org.apache.solr.common.params.CommonAdminParams.ASYNC; import static org.apache.solr.common.params.CommonParams.NAME; import static org.apache.solr.common.util.Utils.makeMap; /** * A {@link OverseerMessageHandler} that handles Collections API related * overseer messages. */ public class OverseerCollectionMessageHandler implements OverseerMessageHandler, SolrCloseable { public static final String NUM_SLICES = "numShards"; public static final boolean CREATE_NODE_SET_SHUFFLE_DEFAULT = true; public static final String CREATE_NODE_SET_SHUFFLE = CollectionAdminParams.CREATE_NODE_SET_SHUFFLE_PARAM; public static final String CREATE_NODE_SET_EMPTY = "EMPTY"; public static final String CREATE_NODE_SET = CollectionAdminParams.CREATE_NODE_SET_PARAM; public static final String ROUTER = "router"; public static final String SHARDS_PROP = "shards"; public static final String REQUESTID = "requestid"; public static final String ONLY_IF_DOWN = "onlyIfDown"; public static final String SHARD_UNIQUE = "shardUnique"; public static final String ONLY_ACTIVE_NODES = "onlyactivenodes"; static final String SKIP_CREATE_REPLICA_IN_CLUSTER_STATE = "skipCreateReplicaInClusterState"; public static final Map<String, Object> COLLECTION_PROPS_AND_DEFAULTS = Collections.unmodifiableMap(makeMap( ROUTER, DocRouter.DEFAULT_NAME, ZkStateReader.REPLICATION_FACTOR, "1", ZkStateReader.NRT_REPLICAS, "1", ZkStateReader.TLOG_REPLICAS, "0", DocCollection.PER_REPLICA_STATE, null, ZkStateReader.PULL_REPLICAS, "0")); private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); public static final String FAILURE_FIELD = "failure"; public static final String SUCCESS_FIELD = "success"; Overseer overseer; HttpShardHandlerFactory shardHandlerFactory; String adminPath; ZkStateReader zkStateReader; SolrCloudManager cloudManager; String myId; Stats stats; TimeSource timeSource; // Set that tracks collections that are currently being processed by a running task. // This is used for handling mutual exclusion of the tasks. final private LockTree lockTree = new LockTree(); ExecutorService tpe = new ExecutorUtil.MDCAwareThreadPoolExecutor(5, 10, 0L, TimeUnit.MILLISECONDS, new SynchronousQueue<>(), new SolrNamedThreadFactory("OverseerCollectionMessageHandlerThreadFactory")); protected static final Random RANDOM; static { // We try to make things reproducible in the context of our tests by initializing the random instance // based on the current seed String seed = System.getProperty("tests.seed"); if (seed == null) { RANDOM = new Random(); } else { RANDOM = new Random(seed.hashCode()); } } final Map<CollectionAction, Cmd> commandMap; private volatile boolean isClosed; public OverseerCollectionMessageHandler(ZkStateReader zkStateReader, String myId, final HttpShardHandlerFactory shardHandlerFactory, String adminPath, Stats stats, Overseer overseer, OverseerNodePrioritizer overseerPrioritizer) { this.zkStateReader = zkStateReader; this.shardHandlerFactory = shardHandlerFactory; this.adminPath = adminPath; this.myId = myId; this.stats = stats; this.overseer = overseer; this.cloudManager = overseer.getSolrCloudManager(); this.timeSource = cloudManager.getTimeSource(); this.isClosed = false; commandMap = new ImmutableMap.Builder<CollectionAction, Cmd>() .put(REPLACENODE, new ReplaceNodeCmd(this)) .put(DELETENODE, new DeleteNodeCmd(this)) .put(BACKUP, new BackupCmd(this)) .put(RESTORE, new RestoreCmd(this)) .put(DELETEBACKUP, new DeleteBackupCmd(this)) .put(CREATESNAPSHOT, new CreateSnapshotCmd(this)) .put(DELETESNAPSHOT, new DeleteSnapshotCmd(this)) .put(SPLITSHARD, new SplitShardCmd(this)) .put(ADDROLE, new OverseerRoleCmd(this, ADDROLE, overseerPrioritizer)) .put(REMOVEROLE, new OverseerRoleCmd(this, REMOVEROLE, overseerPrioritizer)) .put(MOCK_COLL_TASK, this::mockOperation) .put(MOCK_SHARD_TASK, this::mockOperation) .put(MOCK_REPLICA_TASK, this::mockOperation) .put(CREATESHARD, new CreateShardCmd(this)) .put(MIGRATE, new MigrateCmd(this)) .put(CREATE, new CreateCollectionCmd(this)) .put(MODIFYCOLLECTION, this::modifyCollection) .put(ADDREPLICAPROP, this::processReplicaAddPropertyCommand) .put(DELETEREPLICAPROP, this::processReplicaDeletePropertyCommand) .put(BALANCESHARDUNIQUE, this::balanceProperty) .put(REBALANCELEADERS, this::processRebalanceLeaders) .put(RELOAD, this::reloadCollection) .put(DELETE, new DeleteCollectionCmd(this)) .put(CREATEALIAS, new CreateAliasCmd(this)) .put(DELETEALIAS, new DeleteAliasCmd(this)) .put(ALIASPROP, new SetAliasPropCmd(this)) .put(MAINTAINROUTEDALIAS, new MaintainRoutedAliasCmd(this)) .put(OVERSEERSTATUS, new OverseerStatusCmd(this)) .put(DELETESHARD, new DeleteShardCmd(this)) .put(DELETEREPLICA, new DeleteReplicaCmd(this)) .put(ADDREPLICA, new AddReplicaCmd(this)) .put(MOVEREPLICA, new MoveReplicaCmd(this)) .put(REINDEXCOLLECTION, new ReindexCollectionCmd(this)) .put(RENAME, new RenameCmd(this)) .build() ; } @Override @SuppressWarnings("unchecked") public OverseerSolrResponse processMessage(ZkNodeProps message, String operation) { MDCLoggingContext.setCollection(message.getStr(COLLECTION)); MDCLoggingContext.setShard(message.getStr(SHARD_ID_PROP)); MDCLoggingContext.setReplica(message.getStr(REPLICA_PROP)); log.debug("OverseerCollectionMessageHandler.processMessage : {} , {}", operation, message); @SuppressWarnings({"rawtypes"}) NamedList results = new NamedList(); try { CollectionAction action = getCollectionAction(operation); Cmd command = commandMap.get(action); if (command != null) { command.call(cloudManager.getClusterStateProvider().getClusterState(), message, results); } else { throw new SolrException(ErrorCode.BAD_REQUEST, "Unknown operation:" + operation); } } catch (Exception e) { String collName = message.getStr("collection"); if (collName == null) collName = message.getStr(NAME); if (collName == null) { SolrException.log(log, "Operation " + operation + " failed", e); } else { SolrException.log(log, "Collection: " + collName + " operation: " + operation + " failed", e); } results.add("Operation " + operation + " caused exception:", e); SimpleOrderedMap<Object> nl = new SimpleOrderedMap<>(); nl.add("msg", e.getMessage()); nl.add("rspCode", e instanceof SolrException ? ((SolrException)e).code() : -1); results.add("exception", nl); } return new OverseerSolrResponse(results); } @SuppressForbidden(reason = "Needs currentTimeMillis for mock requests") @SuppressWarnings({"unchecked"}) private void mockOperation(ClusterState state, ZkNodeProps message, @SuppressWarnings({"rawtypes"})NamedList results) throws InterruptedException { //only for test purposes Thread.sleep(message.getInt("sleep", 1)); if (log.isInfoEnabled()) { log.info("MOCK_TASK_EXECUTED time {} data {}", System.currentTimeMillis(), Utils.toJSONString(message)); } results.add("MOCK_FINISHED", System.currentTimeMillis()); } private CollectionAction getCollectionAction(String operation) { CollectionAction action = CollectionAction.get(operation); if (action == null) { throw new SolrException(ErrorCode.BAD_REQUEST, "Unknown operation:" + operation); } return action; } @SuppressWarnings({"unchecked"}) private void reloadCollection(ClusterState clusterState, ZkNodeProps message, @SuppressWarnings({"rawtypes"})NamedList results) { ModifiableSolrParams params = new ModifiableSolrParams(); params.set(CoreAdminParams.ACTION, CoreAdminAction.RELOAD.toString()); String asyncId = message.getStr(ASYNC); collectionCmd(message, params, results, Replica.State.ACTIVE, asyncId, Collections.emptySet()); } @SuppressWarnings("unchecked") private void processRebalanceLeaders(ClusterState clusterState, ZkNodeProps message, @SuppressWarnings({"rawtypes"})NamedList results) throws Exception { checkRequired(message, COLLECTION_PROP, SHARD_ID_PROP, CORE_NAME_PROP, ELECTION_NODE_PROP, CORE_NODE_NAME_PROP, NODE_NAME_PROP, REJOIN_AT_HEAD_PROP); ModifiableSolrParams params = new ModifiableSolrParams(); params.set(COLLECTION_PROP, message.getStr(COLLECTION_PROP)); params.set(SHARD_ID_PROP, message.getStr(SHARD_ID_PROP)); params.set(REJOIN_AT_HEAD_PROP, message.getStr(REJOIN_AT_HEAD_PROP)); params.set(CoreAdminParams.ACTION, CoreAdminAction.REJOINLEADERELECTION.toString()); params.set(CORE_NAME_PROP, message.getStr(CORE_NAME_PROP)); params.set(CORE_NODE_NAME_PROP, message.getStr(CORE_NODE_NAME_PROP)); params.set(ELECTION_NODE_PROP, message.getStr(ELECTION_NODE_PROP)); params.set(NODE_NAME_PROP, message.getStr(NODE_NAME_PROP)); String baseUrl = UrlScheme.INSTANCE.getBaseUrlForNodeName(message.getStr(NODE_NAME_PROP)); ShardRequest sreq = new ShardRequest(); sreq.nodeName = message.getStr(ZkStateReader.CORE_NAME_PROP); // yes, they must use same admin handler path everywhere... params.set("qt", adminPath); sreq.purpose = ShardRequest.PURPOSE_PRIVATE; sreq.shards = new String[] {baseUrl}; sreq.actualShards = sreq.shards; sreq.params = params; ShardHandler shardHandler = shardHandlerFactory.getShardHandler(); shardHandler.submit(sreq, baseUrl, sreq.params); } @SuppressWarnings("unchecked") private void processReplicaAddPropertyCommand(ClusterState clusterState, ZkNodeProps message, @SuppressWarnings({"rawtypes"})NamedList results) throws Exception { checkRequired(message, COLLECTION_PROP, SHARD_ID_PROP, REPLICA_PROP, PROPERTY_PROP, PROPERTY_VALUE_PROP); SolrZkClient zkClient = zkStateReader.getZkClient(); Map<String, Object> propMap = new HashMap<>(); propMap.put(Overseer.QUEUE_OPERATION, ADDREPLICAPROP.toLower()); propMap.putAll(message.getProperties()); ZkNodeProps m = new ZkNodeProps(propMap); overseer.offerStateUpdate(Utils.toJSON(m)); } private void processReplicaDeletePropertyCommand(ClusterState clusterState, ZkNodeProps message, @SuppressWarnings({"rawtypes"})NamedList results) throws Exception { checkRequired(message, COLLECTION_PROP, SHARD_ID_PROP, REPLICA_PROP, PROPERTY_PROP); SolrZkClient zkClient = zkStateReader.getZkClient(); Map<String, Object> propMap = new HashMap<>(); propMap.put(Overseer.QUEUE_OPERATION, DELETEREPLICAPROP.toLower()); propMap.putAll(message.getProperties()); ZkNodeProps m = new ZkNodeProps(propMap); overseer.offerStateUpdate(Utils.toJSON(m)); } private void balanceProperty(ClusterState clusterState, ZkNodeProps message, @SuppressWarnings({"rawtypes"})NamedList results) throws Exception { if (StringUtils.isBlank(message.getStr(COLLECTION_PROP)) || StringUtils.isBlank(message.getStr(PROPERTY_PROP))) { throw new SolrException(ErrorCode.BAD_REQUEST, "The '" + COLLECTION_PROP + "' and '" + PROPERTY_PROP + "' parameters are required for the BALANCESHARDUNIQUE operation, no action taken"); } SolrZkClient zkClient = zkStateReader.getZkClient(); Map<String, Object> m = new HashMap<>(); m.put(Overseer.QUEUE_OPERATION, BALANCESHARDUNIQUE.toLower()); m.putAll(message.getProperties()); overseer.offerStateUpdate(Utils.toJSON(m)); } /** * Get collection status from cluster state. * Can return collection status by given shard name. * * * @param collection collection map parsed from JSON-serialized {@link ClusterState} * @param name collection name * @param requestedShards a set of shards to be returned in the status. * An empty or null values indicates <b>all</b> shards. * @return map of collection properties */ @SuppressWarnings("unchecked") private Map<String, Object> getCollectionStatus(Map<String, Object> collection, String name, Set<String> requestedShards) { if (collection == null) { throw new SolrException(ErrorCode.BAD_REQUEST, "Collection: " + name + " not found"); } if (requestedShards == null || requestedShards.isEmpty()) { return collection; } else { Map<String, Object> shards = (Map<String, Object>) collection.get("shards"); Map<String, Object> selected = new HashMap<>(); for (String selectedShard : requestedShards) { if (!shards.containsKey(selectedShard)) { throw new SolrException(ErrorCode.BAD_REQUEST, "Collection: " + name + " shard: " + selectedShard + " not found"); } selected.put(selectedShard, shards.get(selectedShard)); collection.put("shards", selected); } return collection; } } @SuppressWarnings("unchecked") void deleteReplica(ClusterState clusterState, ZkNodeProps message, @SuppressWarnings({"rawtypes"})NamedList results, Runnable onComplete) throws Exception { ((DeleteReplicaCmd) commandMap.get(DELETEREPLICA)).deleteReplica(clusterState, message, results, onComplete); } boolean waitForCoreNodeGone(String collectionName, String shard, String replicaName, int timeoutms) throws InterruptedException { try { zkStateReader.waitForState(collectionName, timeoutms, TimeUnit.MILLISECONDS, (c) -> { if (c == null) return true; Slice slice = c.getSlice(shard); if(slice == null || slice.getReplica(replicaName) == null) { return true; } return false; }); } catch (TimeoutException e) { return false; } return true; } void deleteCoreNode(String collectionName, String replicaName, Replica replica, String core) throws Exception { ZkNodeProps m = new ZkNodeProps( Overseer.QUEUE_OPERATION, OverseerAction.DELETECORE.toLower(), ZkStateReader.CORE_NAME_PROP, core, ZkStateReader.NODE_NAME_PROP, replica.getNodeName(), ZkStateReader.COLLECTION_PROP, collectionName, ZkStateReader.CORE_NODE_NAME_PROP, replicaName); overseer.offerStateUpdate(Utils.toJSON(m)); } void checkRequired(ZkNodeProps message, String... props) { for (String prop : props) { if(message.get(prop) == null){ throw new SolrException(ErrorCode.BAD_REQUEST, StrUtils.join(Arrays.asList(props),',') +" are required params" ); } } } void checkResults(String label, NamedList<Object> results, boolean failureIsFatal) throws SolrException { Object failure = results.get("failure"); if (failure == null) { failure = results.get("error"); } if (failure != null) { String msg = "Error: " + label + ": " + Utils.toJSONString(results); if (failureIsFatal) { throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, msg); } else { log.error(msg); } } } @SuppressWarnings({"unchecked"}) void commit(@SuppressWarnings({"rawtypes"})NamedList results, String slice, Replica parentShardLeader) { log.debug("Calling soft commit to make sub shard updates visible"); String coreUrl = new ZkCoreNodeProps(parentShardLeader).getCoreUrl(); // HttpShardHandler is hard coded to send a QueryRequest hence we go direct // and we force open a searcher so that we have documents to show upon switching states UpdateResponse updateResponse = null; try { updateResponse = softCommit(coreUrl); processResponse(results, null, coreUrl, updateResponse, slice, Collections.emptySet()); } catch (Exception e) { processResponse(results, e, coreUrl, updateResponse, slice, Collections.emptySet()); throw new SolrException(ErrorCode.SERVER_ERROR, "Unable to call distrib softCommit on: " + coreUrl, e); } } static UpdateResponse softCommit(String url) throws SolrServerException, IOException { try (HttpSolrClient client = new HttpSolrClient.Builder(url) .withConnectionTimeout(30000) .withSocketTimeout(120000) .build()) { UpdateRequest ureq = new UpdateRequest(); ureq.setParams(new ModifiableSolrParams()); ureq.setAction(AbstractUpdateRequest.ACTION.COMMIT, false, true, true); return ureq.process(client); } } String waitForCoreNodeName(String collectionName, String msgNodeName, String msgCore) { try { DocCollection collection = zkStateReader.waitForState(collectionName, 320, TimeUnit.SECONDS, c -> ClusterStateMutator.getAssignedCoreNodeName(c, msgNodeName, msgCore) != null ); return ClusterStateMutator.getAssignedCoreNodeName(collection, msgNodeName, msgCore); } catch (TimeoutException | InterruptedException e) { SolrZkClient.checkInterrupted(e); throw new SolrException(ErrorCode.SERVER_ERROR, "Failed waiting for coreNodeName", e); } } ClusterState waitForNewShard(String collectionName, String sliceName) throws KeeperException, InterruptedException { log.debug("Waiting for slice {} of collection {} to be available", sliceName, collectionName); try { zkStateReader.waitForState(collectionName, 320, TimeUnit.SECONDS, c -> { return c != null && c.getSlice(sliceName) != null; }); } catch (TimeoutException | InterruptedException e) { SolrZkClient.checkInterrupted(e); throw new SolrException(ErrorCode.SERVER_ERROR, "Failed waiting for new slice", e); } return zkStateReader.getClusterState(); } DocRouter.Range intersect(DocRouter.Range a, DocRouter.Range b) { if (a == null || b == null || !a.overlaps(b)) { return null; } else if (a.isSubsetOf(b)) return a; else if (b.isSubsetOf(a)) return b; else if (b.includes(a.max)) { return new DocRouter.Range(b.min, a.max); } else { return new DocRouter.Range(a.min, b.max); } } void addPropertyParams(ZkNodeProps message, ModifiableSolrParams params) { // Now add the property.key=value pairs for (String key : message.keySet()) { if (key.startsWith(CollectionAdminParams.PROPERTY_PREFIX)) { params.set(key, message.getStr(key)); } } } void addPropertyParams(ZkNodeProps message, Map<String, Object> map) { // Now add the property.key=value pairs for (String key : message.keySet()) { if (key.startsWith(CollectionAdminParams.PROPERTY_PREFIX)) { map.put(key, message.getStr(key)); } } } private void modifyCollection(ClusterState clusterState, ZkNodeProps message, @SuppressWarnings({"rawtypes"})NamedList results) throws Exception { final String collectionName = message.getStr(ZkStateReader.COLLECTION_PROP); //the rest of the processing is based on writing cluster state properties //remove the property here to avoid any errors down the pipeline due to this property appearing String configName = (String) message.getProperties().remove(CollectionAdminParams.COLL_CONF); if(configName != null) { validateConfigOrThrowSolrException(configName); createConfNode(cloudManager.getDistribStateManager(), configName, collectionName); reloadCollection(null, new ZkNodeProps(NAME, collectionName), results); } overseer.offerStateUpdate(Utils.toJSON(message)); try { zkStateReader.waitForState(collectionName, 30, TimeUnit.SECONDS, c -> { if (c == null) return false; for (Map.Entry<String,Object> updateEntry : message.getProperties().entrySet()) { String updateKey = updateEntry.getKey(); if (!updateKey.equals(ZkStateReader.COLLECTION_PROP) && !updateKey.equals(Overseer.QUEUE_OPERATION) && updateEntry.getValue() != null // handled below in a separate conditional && !updateEntry.getValue().equals(c.get(updateKey))) { return false; } if (updateEntry.getValue() == null && c.containsKey(updateKey)) { return false; } } return true; }); } catch (TimeoutException | InterruptedException e) { SolrZkClient.checkInterrupted(e); log.debug("modifyCollection(ClusterState={}, ZkNodeProps={}, NamedList={})", clusterState, message, results, e); throw new SolrException(ErrorCode.SERVER_ERROR, "Failed to modify collection", e); } // if switching to/from read-only mode reload the collection if (message.keySet().contains(ZkStateReader.READ_ONLY)) { reloadCollection(null, new ZkNodeProps(NAME, collectionName), results); } } void cleanupCollection(String collectionName, @SuppressWarnings({"rawtypes"})NamedList results) throws Exception { log.error("Cleaning up collection [{}].", collectionName); Map<String, Object> props = makeMap( Overseer.QUEUE_OPERATION, DELETE.toLower(), NAME, collectionName); commandMap.get(DELETE).call(zkStateReader.getClusterState(), new ZkNodeProps(props), results); } Map<String, Replica> waitToSeeReplicasInState(String collectionName, Collection<String> coreNames) throws InterruptedException { assert coreNames.size() > 0; Map<String, Replica> results = new ConcurrentHashMap<>(); long maxWait = Long.getLong("solr.waitToSeeReplicasInStateTimeoutSeconds", 120); // could be a big cluster try { zkStateReader.waitForState(collectionName, maxWait, TimeUnit.SECONDS, c -> { if (c == null) return false; // We write into a ConcurrentHashMap, which will be ok if called multiple times by multiple threads c.getSlices().stream().flatMap(slice -> slice.getReplicas().stream()) .filter(r -> coreNames.contains(r.getCoreName())) // Only the elements that were asked for... .forEach(r -> results.putIfAbsent(r.getCoreName(), r)); // ...get added to the map log.debug("Expecting {} cores, found {}", coreNames, results); return results.size() == coreNames.size(); }); } catch (TimeoutException e) { throw new SolrException(ErrorCode.SERVER_ERROR, e.getMessage(), e); } return results; } @SuppressWarnings({"rawtypes"}) void cleanBackup(BackupRepository repository, URI backupPath, BackupId backupId) throws Exception { ((DeleteBackupCmd)commandMap.get(DELETEBACKUP)) .deleteBackupIds(backupPath, repository, Collections.singleton(backupId), new NamedList()); } void deleteBackup(BackupRepository repository, URI backupPath, int maxNumBackup, @SuppressWarnings({"rawtypes"}) NamedList results) throws Exception { ((DeleteBackupCmd)commandMap.get(DELETEBACKUP)) .keepNumberOfBackup(repository, backupPath, maxNumBackup, results); } List<ZkNodeProps> addReplica(ClusterState clusterState, ZkNodeProps message, @SuppressWarnings({"rawtypes"})NamedList results, Runnable onComplete) throws Exception { return ((AddReplicaCmd) commandMap.get(ADDREPLICA)).addReplica(clusterState, message, results, onComplete); } void validateConfigOrThrowSolrException(String configName) throws IOException, KeeperException, InterruptedException { boolean isValid = cloudManager.getDistribStateManager().hasData(ZkConfigManager.CONFIGS_ZKNODE + "/" + configName); if(!isValid) { throw new SolrException(ErrorCode.BAD_REQUEST, "Can not find the specified config set: " + configName); } } /** * This doesn't validate the config (path) itself and is just responsible for creating the confNode. * That check should be done before the config node is created. */ public static void createConfNode(DistribStateManager stateManager, String configName, String coll) throws IOException, AlreadyExistsException, BadVersionException, KeeperException, InterruptedException { if (configName != null) { String collDir = ZkStateReader.COLLECTIONS_ZKNODE + "/" + coll; log.debug("creating collections conf node {} ", collDir); byte[] data = Utils.toJSON(makeMap(ZkController.CONFIGNAME_PROP, configName)); if (stateManager.hasData(collDir)) { stateManager.setData(collDir, data, -1); } else { stateManager.makePath(collDir, data, CreateMode.PERSISTENT, false); } } else { throw new SolrException(ErrorCode.BAD_REQUEST,"Unable to get config name"); } } /** * Send request to all replicas of a collection * @return List of replicas which is not live for receiving the request */ List<Replica> collectionCmd(ZkNodeProps message, ModifiableSolrParams params, NamedList<Object> results, Replica.State stateMatcher, String asyncId, Set<String> okayExceptions) { log.info("Executing Collection Cmd={}, asyncId={}", params, asyncId); String collectionName = message.getStr(NAME); ShardHandler shardHandler = shardHandlerFactory.getShardHandler(); ClusterState clusterState = zkStateReader.getClusterState(); DocCollection coll = clusterState.getCollection(collectionName); List<Replica> notLivesReplicas = new ArrayList<>(); final ShardRequestTracker shardRequestTracker = new ShardRequestTracker(asyncId); for (Slice slice : coll.getSlices()) { notLivesReplicas.addAll(shardRequestTracker.sliceCmd(clusterState, params, stateMatcher, slice, shardHandler)); } shardRequestTracker.processResponses(results, shardHandler, false, null, okayExceptions); return notLivesReplicas; } private void processResponse(NamedList<Object> results, ShardResponse srsp, Set<String> okayExceptions) { Throwable e = srsp.getException(); String nodeName = srsp.getNodeName(); SolrResponse solrResponse = srsp.getSolrResponse(); String shard = srsp.getShard(); processResponse(results, e, nodeName, solrResponse, shard, okayExceptions); } @SuppressWarnings("deprecation") private void processResponse(NamedList<Object> results, Throwable e, String nodeName, SolrResponse solrResponse, String shard, Set<String> okayExceptions) { String rootThrowable = null; if (e instanceof BaseHttpSolrClient.RemoteSolrException) { rootThrowable = ((BaseHttpSolrClient.RemoteSolrException) e).getRootThrowable(); } if (e != null && (rootThrowable == null || !okayExceptions.contains(rootThrowable))) { log.error("Error from shard: {}", shard, e); addFailure(results, nodeName, e.getClass().getName() + ":" + e.getMessage()); } else { addSuccess(results, nodeName, solrResponse.getResponse()); } } @SuppressWarnings("unchecked") private static void addFailure(NamedList<Object> results, String key, Object value) { SimpleOrderedMap<Object> failure = (SimpleOrderedMap<Object>) results.get("failure"); if (failure == null) { failure = new SimpleOrderedMap<>(); results.add("failure", failure); } failure.add(key, value); } @SuppressWarnings("unchecked") private static void addSuccess(NamedList<Object> results, String key, Object value) { SimpleOrderedMap<Object> success = (SimpleOrderedMap<Object>) results.get("success"); if (success == null) { success = new SimpleOrderedMap<>(); results.add("success", success); } success.add(key, value); } private NamedList<Object> waitForCoreAdminAsyncCallToComplete(String nodeName, String requestId) { ShardHandler shardHandler = shardHandlerFactory.getShardHandler(); ModifiableSolrParams params = new ModifiableSolrParams(); params.set(CoreAdminParams.ACTION, CoreAdminAction.REQUESTSTATUS.toString()); params.set(CoreAdminParams.REQUESTID, requestId); int counter = 0; ShardRequest sreq; do { sreq = new ShardRequest(); params.set("qt", adminPath); sreq.purpose = 1; String replica = zkStateReader.getBaseUrlForNodeName(nodeName); sreq.shards = new String[] {replica}; sreq.actualShards = sreq.shards; sreq.params = params; shardHandler.submit(sreq, replica, sreq.params); ShardResponse srsp; do { srsp = shardHandler.takeCompletedOrError(); if (srsp != null) { NamedList<Object> results = new NamedList<>(); processResponse(results, srsp, Collections.emptySet()); if (srsp.getSolrResponse().getResponse() == null) { NamedList<Object> response = new NamedList<>(); response.add("STATUS", "failed"); return response; } String r = (String) srsp.getSolrResponse().getResponse().get("STATUS"); if (r.equals("running")) { log.debug("The task is still RUNNING, continuing to wait."); try { Thread.sleep(1000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } continue; } else if (r.equals("completed")) { log.debug("The task is COMPLETED, returning"); return srsp.getSolrResponse().getResponse(); } else if (r.equals("failed")) { // TODO: Improve this. Get more information. log.debug("The task is FAILED, returning"); return srsp.getSolrResponse().getResponse(); } else if (r.equals("notfound")) { log.debug("The task is notfound, retry"); if (counter++ < 5) { try { Thread.sleep(1000); } catch (InterruptedException e) { } break; } throw new SolrException(ErrorCode.BAD_REQUEST, "Invalid status request for requestId: " + requestId + "" + srsp.getSolrResponse().getResponse().get("STATUS") + "retried " + counter + "times"); } else { throw new SolrException(ErrorCode.BAD_REQUEST, "Invalid status request " + srsp.getSolrResponse().getResponse().get("STATUS")); } } } while (srsp != null); } while(true); } @Override public String getName() { return "Overseer Collection Message Handler"; } @Override public String getTimerName(String operation) { return "collection_" + operation; } @Override public String getTaskKey(ZkNodeProps message) { return message.containsKey(COLLECTION_PROP) ? message.getStr(COLLECTION_PROP) : message.getStr(NAME); } // -1 is not a possible batchSessionId so -1 will force initialization of lockSession private long sessionId = -1; private LockTree.Session lockSession; /** * Grabs an exclusive lock for this particular task. * @return <code>null</code> if locking is not possible. When locking is not possible, it will remain * impossible for the passed value of <code>batchSessionId</code>. This is to guarantee tasks are executed * in queue order (and a later task is not run earlier than its turn just because it happens that a lock got released). */ @Override public Lock lockTask(ZkNodeProps message, long batchSessionId) { if (sessionId != batchSessionId) { //this is always called in the same thread. //Each batch is supposed to have a new taskBatch //So if taskBatch changes we must create a new Session lockSession = lockTree.getSession(); sessionId = batchSessionId; } return lockSession.lock(getCollectionAction(message.getStr(Overseer.QUEUE_OPERATION)), Arrays.asList( getTaskKey(message), message.getStr(ZkStateReader.SHARD_ID_PROP), message.getStr(ZkStateReader.REPLICA_PROP)) ); } @Override public void close() throws IOException { this.isClosed = true; if (tpe != null) { if (!tpe.isShutdown()) { ExecutorUtil.shutdownAndAwaitTermination(tpe); } } } @Override public boolean isClosed() { return isClosed; } protected interface Cmd { void call(ClusterState state, ZkNodeProps message, @SuppressWarnings({"rawtypes"})NamedList results) throws Exception; } /* * backward compatibility reasons, add the response with the async ID as top level. * This can be removed in Solr 9 */ @Deprecated static boolean INCLUDE_TOP_LEVEL_RESPONSE = true; public ShardRequestTracker syncRequestTracker() { return new ShardRequestTracker(null); } public ShardRequestTracker asyncRequestTracker(String asyncId) { return new ShardRequestTracker(asyncId); } public class ShardRequestTracker{ private final String asyncId; private final NamedList<String> shardAsyncIdByNode = new NamedList<String>(); private ShardRequestTracker(String asyncId) { this.asyncId = asyncId; } /** * Send request to all replicas of a slice * @return List of replicas which is not live for receiving the request */ public List<Replica> sliceCmd(ClusterState clusterState, ModifiableSolrParams params, Replica.State stateMatcher, Slice slice, ShardHandler shardHandler) { List<Replica> notLiveReplicas = new ArrayList<>(); for (Replica replica : slice.getReplicas()) { if ((stateMatcher == null || Replica.State.getState(replica.getStr(ZkStateReader.STATE_PROP)) == stateMatcher)) { if (clusterState.liveNodesContain(replica.getStr(ZkStateReader.NODE_NAME_PROP))) { // For thread safety, only simple clone the ModifiableSolrParams ModifiableSolrParams cloneParams = new ModifiableSolrParams(); cloneParams.add(params); cloneParams.set(CoreAdminParams.CORE, replica.getStr(ZkStateReader.CORE_NAME_PROP)); sendShardRequest(replica.getStr(ZkStateReader.NODE_NAME_PROP), cloneParams, shardHandler); } else { notLiveReplicas.add(replica); } } } return notLiveReplicas; } public void sendShardRequest(String nodeName, ModifiableSolrParams params, ShardHandler shardHandler) { sendShardRequest(nodeName, params, shardHandler, adminPath, zkStateReader); } public void sendShardRequest(String nodeName, ModifiableSolrParams params, ShardHandler shardHandler, String adminPath, ZkStateReader zkStateReader) { if (asyncId != null) { String coreAdminAsyncId = asyncId + Math.abs(System.nanoTime()); params.set(ASYNC, coreAdminAsyncId); track(nodeName, coreAdminAsyncId); } ShardRequest sreq = new ShardRequest(); params.set("qt", adminPath); sreq.purpose = 1; String replica = zkStateReader.getBaseUrlForNodeName(nodeName); sreq.shards = new String[] {replica}; sreq.actualShards = sreq.shards; sreq.nodeName = nodeName; sreq.params = params; shardHandler.submit(sreq, replica, sreq.params); } void processResponses(NamedList<Object> results, ShardHandler shardHandler, boolean abortOnError, String msgOnError) { processResponses(results, shardHandler, abortOnError, msgOnError, Collections.emptySet()); } void processResponses(NamedList<Object> results, ShardHandler shardHandler, boolean abortOnError, String msgOnError, Set<String> okayExceptions) { // Processes all shard responses ShardResponse srsp; do { srsp = shardHandler.takeCompletedOrError(); if (srsp != null) { processResponse(results, srsp, okayExceptions); Throwable exception = srsp.getException(); if (abortOnError && exception != null) { // drain pending requests while (srsp != null) { srsp = shardHandler.takeCompletedOrError(); } throw new SolrException(ErrorCode.SERVER_ERROR, msgOnError, exception); } } } while (srsp != null); // If request is async wait for the core admin to complete before returning if (asyncId != null) { waitForAsyncCallsToComplete(results); // TODO: Shouldn't we abort with msgOnError exception when failure? shardAsyncIdByNode.clear(); } } private void waitForAsyncCallsToComplete(NamedList<Object> results) { for (Map.Entry<String,String> nodeToAsync:shardAsyncIdByNode) { final String node = nodeToAsync.getKey(); final String shardAsyncId = nodeToAsync.getValue(); log.debug("I am Waiting for :{}/{}", node, shardAsyncId); NamedList<Object> reqResult = waitForCoreAdminAsyncCallToComplete(node, shardAsyncId); if (INCLUDE_TOP_LEVEL_RESPONSE) { results.add(shardAsyncId, reqResult); } if ("failed".equalsIgnoreCase(((String)reqResult.get("STATUS")))) { log.error("Error from shard {}: {}", node, reqResult); addFailure(results, node, reqResult); } else { addSuccess(results, node, reqResult); } } } /** @deprecated consider to make it private after {@link CreateCollectionCmd} refactoring*/ @Deprecated void track(String nodeName, String coreAdminAsyncId) { shardAsyncIdByNode.add(nodeName, coreAdminAsyncId); } } }
1
40,402
just observing that this innocent looking change seems important to this PR. Previously this data had disappeared from the state.
apache-lucene-solr
java
@@ -1442,7 +1442,8 @@ short ExExeUtilHBaseBulkLoadTcb::work() ComCondition *cond; Lng32 entryNumber; while ((cond = diagsArea->findCondition(EXE_ERROR_ROWS_FOUND, &entryNumber)) != NULL) { - errorRowCount = cond->getOptionalInteger(0); + if (errorRowCount < cond->getOptionalInteger(0)) + errorRowCount = cond->getOptionalInteger(0); diagsArea->deleteWarning(entryNumber); } diagsArea->setRowCount(0);
1
/********************************************************************** // @@@ START COPYRIGHT @@@ // // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. // // @@@ END COPYRIGHT @@@ **********************************************************************/ /* -*-C++-*- ***************************************************************************** * * File: ExExeUtilLoad.cpp * Description: * * * Language: C++ * * * * ***************************************************************************** */ #include <iostream> using std::cerr; using std::endl; #include <fstream> using std::ofstream; #include <stdio.h> #include "ComCextdecs.h" #include "cli_stdh.h" #include "ex_stdh.h" #include "sql_id.h" #include "ex_transaction.h" #include "ComTdb.h" #include "ex_tcb.h" #include "ComSqlId.h" #include "ExExeUtil.h" #include "ex_exe_stmt_globals.h" #include "exp_expr.h" #include "exp_clause_derived.h" #include "ComRtUtils.h" #include "ExStats.h" #include "ExpLOB.h" #include "ExpLOBenums.h" #include "ExpLOBinterface.h" #include "ExpLOBexternal.h" #include "str.h" #include "ExpHbaseInterface.h" #include "ExHbaseAccess.h" #include "ExpErrorEnums.h" /////////////////////////////////////////////////////////////////// ex_tcb * ExExeUtilCreateTableAsTdb::build(ex_globals * glob) { ExExeUtilCreateTableAsTcb * exe_util_tcb; exe_util_tcb = new(glob->getSpace()) ExExeUtilCreateTableAsTcb(*this, glob); exe_util_tcb->registerSubtasks(); return (exe_util_tcb); } //////////////////////////////////////////////////////////////// // Constructor for class ExExeUtilCreateTableAsTcb /////////////////////////////////////////////////////////////// ExExeUtilCreateTableAsTcb::ExExeUtilCreateTableAsTcb( const ComTdbExeUtil & exe_util_tdb, ex_globals * glob) : ExExeUtilTcb( exe_util_tdb, NULL, glob), step_(INITIAL_), tableExists_(FALSE) { // Allocate the private state in each entry of the down queue qparent_.down->allocatePstate(this); } ////////////////////////////////////////////////////// // work() for ExExeUtilCreateTableAsTcb ////////////////////////////////////////////////////// short ExExeUtilCreateTableAsTcb::work() { Lng32 cliRC = 0; short retcode = 0; Int64 rowsAffected = 0; NABoolean redriveCTAS = FALSE; // if no parent request, return if (qparent_.down->isEmpty()) return WORK_OK; // if no room in up queue, won't be able to return data/status. // Come back later. if (qparent_.up->isFull()) return WORK_OK; ex_queue_entry * pentry_down = qparent_.down->getHeadEntry(); ExExeUtilPrivateState & pstate = *((ExExeUtilPrivateState*) pentry_down->pstate); // Get the globals stucture of the master executor. ExExeStmtGlobals *exeGlob = getGlobals()->castToExExeStmtGlobals(); ExMasterStmtGlobals *masterGlob = exeGlob->castToExMasterStmtGlobals(); ContextCli *currContext = masterGlob->getStatement()->getContext(); ExTransaction *ta = getGlobals()->castToExExeStmtGlobals()-> castToExMasterStmtGlobals()->getStatement()->getContext()->getTransaction(); while (1) { switch (step_) { case INITIAL_: { NABoolean xnAlreadyStarted = ta->xnInProgress(); // allow a user transaction if NO LOAD was specified if (xnAlreadyStarted && !ctaTdb().noLoad()) { *getDiagsArea() << DgSqlCode(-20123) << DgString0("This DDL operation"); step_ = ERROR_; break; } doSidetreeInsert_ = TRUE; if (xnAlreadyStarted) doSidetreeInsert_ = FALSE; else if ( ctaTdb().siQuery_ == (NABasicPtr) NULL ) doSidetreeInsert_ = FALSE; tableExists_ = FALSE; if (ctaTdb().ctQuery_) step_ = CREATE_; else step_ = ALTER_TO_NOAUDIT_; } break; case CREATE_: { tableExists_ = FALSE; // issue the create table command cliRC = cliInterface()->executeImmediate( ctaTdb().ctQuery_); if (cliRC < 0) { if (((cliRC == -1055) || // SQ table err msg (cliRC == -1390)) && // Traf err msg (ctaTdb().loadIfExists())) { SQL_EXEC_ClearDiagnostics(NULL); tableExists_ = TRUE; if (ctaTdb().deleteData()) step_ = DELETE_DATA_; else step_ = ALTER_TO_NOAUDIT_; break; } else { cliInterface()->retrieveSQLDiagnostics(getDiagsArea()); step_ = ERROR_; break; } } // a transaction may not have existed prior to the create stmt, // but if autocommit was off, a transaction would now exist. // turn off sidetree insert. if (ta->xnInProgress()) doSidetreeInsert_ = FALSE; if (ctaTdb().noLoad()) step_ = DONE_; else step_ = ALTER_TO_NOAUDIT_; } break; case DELETE_DATA_: case DELETE_DATA_AND_ERROR_: { char * ddQuery = new(getMyHeap()) char[strlen("DELETE DATA FROM; ") + strlen(ctaTdb().getTableName()) + 100]; strcpy(ddQuery, "DELETE DATA FROM "); strcat(ddQuery, ctaTdb().getTableName()); strcat(ddQuery, ";"); cliRC = cliInterface()->executeImmediate(ddQuery, NULL,NULL,TRUE,NULL,TRUE); // Delete new'd characters NADELETEBASIC(ddQuery, getHeap()); ddQuery = NULL; if (cliRC < 0) { if (step_ == DELETE_DATA_) { step_ = ERROR_; break; } // delete data returned an error. // As a last resort, drop this table. SQL_EXEC_ClearDiagnostics(NULL); step_ = DROP_AND_ERROR_; break; } if (step_ == DELETE_DATA_AND_ERROR_) { if (doSidetreeInsert_) { cliRC = changeAuditAttribute(ctaTdb().getTableName(),TRUE); } step_ = ERROR_; } else step_ = ALTER_TO_NOAUDIT_; } break; case ALTER_TO_NOAUDIT_: { if (NOT doSidetreeInsert_) { step_ = INSERT_VSBB_; break; } step_ = INSERT_SIDETREE_; } break; case INSERT_SIDETREE_: { ex_queue_entry * up_entry = qparent_.up->getTailEntry(); ComDiagsArea *diagsArea = up_entry->getDiagsArea(); // issue the insert command cliInterface()->clearGlobalDiags(); // All internal queries issued from CliInterface assume that // they are in ISO_MAPPING. // That causes mxcmp to use the default charset as iso88591 // for unprefixed literals. // The insert...select being issued out here contains the user // specified query and any literals in that should be using // the default_charset. // So we send the isoMapping charset instead of the // enum ISO_MAPPING. Int32 savedIsoMapping = currContext->getSessionDefaults()->getIsoMappingEnum(); cliInterface()->setIsoMapping (currContext->getSessionDefaults()->getIsoMappingEnum()); redriveCTAS = currContext->getSessionDefaults()->getRedriveCTAS(); if (redriveCTAS) { if (childQueryId_ == NULL) childQueryId_ = new (getHeap()) char[ComSqlId::MAX_QUERY_ID_LEN+1]; childQueryIdLen_ = ComSqlId::MAX_QUERY_ID_LEN; cliRC = cliInterface()->executeImmediatePrepare2( ctaTdb().siQuery_, childQueryId_, &childQueryIdLen_, &childQueryCostInfo_, &childQueryCompStatsInfo_, NULL, NULL, &rowsAffected,TRUE); if (cliRC >= 0) { childQueryId_[childQueryIdLen_] = '\0'; Statement *ctasStmt = masterGlob->getStatement(); cliRC = ctasStmt->setChildQueryInfo(diagsArea, childQueryId_, childQueryIdLen_, &childQueryCostInfo_, &childQueryCompStatsInfo_); if (cliRC < 0) { step_ = HANDLE_ERROR_; break; } if (outputBuf_ == NULL) outputBuf_ = new (getHeap()) char[ComSqlId::MAX_QUERY_ID_LEN+100]; // str_sprintf(outputBuf_, "childQidBegin: %s ", childQueryId_); moveRowToUpQueue(outputBuf_); step_ = INSERT_SIDETREE_EXECUTE_; return WORK_RESCHEDULE_AND_RETURN; } } else { cliRC = cliInterface()->executeImmediatePrepare( ctaTdb().siQuery_, NULL, NULL, &rowsAffected,TRUE); } cliInterface()->setIsoMapping(savedIsoMapping); if (cliRC < 0) { // sidetree insert prepare failed. // Try vsbb insert step_ = ALTER_TO_AUDIT_AND_INSERT_VSBB_; break; } step_ = INSERT_SIDETREE_EXECUTE_; } break; case INSERT_SIDETREE_EXECUTE_: { cliRC = cliInterface()->executeImmediateExec( ctaTdb().siQuery_, NULL, NULL, TRUE, &rowsAffected); if (cliRC < 0) { cliInterface()->retrieveSQLDiagnostics(getDiagsArea()); step_ = HANDLE_ERROR_; } else { masterGlob->setRowsAffected(rowsAffected); step_ = ALTER_TO_AUDIT_; } redriveCTAS = currContext->getSessionDefaults()->getRedriveCTAS(); if (redriveCTAS) { str_sprintf(outputBuf_, "childQidEnd: %s ", childQueryId_); moveRowToUpQueue(outputBuf_); return WORK_RESCHEDULE_AND_RETURN; } } break; case ALTER_TO_AUDIT_: case ALTER_TO_AUDIT_AND_INSERT_VSBB_: { if (step_ == ALTER_TO_AUDIT_AND_INSERT_VSBB_) step_ = INSERT_VSBB_; else step_ = UPD_STATS_; } break; case INSERT_VSBB_: { ex_queue_entry * up_entry = qparent_.up->getTailEntry(); ComDiagsArea *diagsArea = up_entry->getDiagsArea(); // issue the insert command Int64 rowsAffected = 0; Int32 savedIsoMapping = currContext->getSessionDefaults()->getIsoMappingEnum(); cliInterface()->setIsoMapping (currContext->getSessionDefaults()->getIsoMappingEnum()); NABoolean redriveCTAS = currContext->getSessionDefaults()->getRedriveCTAS(); if (redriveCTAS) { if (childQueryId_ == NULL) childQueryId_ = new (getHeap()) char[ComSqlId::MAX_QUERY_ID_LEN+1]; cliRC = cliInterface()->executeImmediatePrepare2( ctaTdb().viQuery_, childQueryId_, &childQueryIdLen_, &childQueryCostInfo_, &childQueryCompStatsInfo_, NULL, NULL, &rowsAffected,TRUE); cliInterface()->setIsoMapping(savedIsoMapping); if (cliRC >= 0) { childQueryId_[childQueryIdLen_] = '\0'; Statement *ctasStmt = masterGlob->getStatement(); cliRC = ctasStmt->setChildQueryInfo(diagsArea, childQueryId_, childQueryIdLen_, &childQueryCostInfo_, &childQueryCompStatsInfo_); if (cliRC < 0) { step_ = HANDLE_ERROR_; break; } if (outputBuf_ == NULL) outputBuf_ = new (getHeap()) char[ComSqlId::MAX_QUERY_ID_LEN+100]; // str_sprintf(outputBuf_, "childQidBegin: %s ", childQueryId_); moveRowToUpQueue(outputBuf_); step_ = INSERT_VSBB_EXECUTE_; return WORK_RESCHEDULE_AND_RETURN; } else { step_ = HANDLE_ERROR_; break; } } else { cliRC = cliInterface()->executeImmediate( ctaTdb().viQuery_, NULL, NULL, TRUE, &rowsAffected,TRUE); cliInterface()->setIsoMapping(savedIsoMapping); if (cliRC < 0) { cliInterface()->retrieveSQLDiagnostics(getDiagsArea()); step_ = HANDLE_ERROR_; } else { masterGlob->setRowsAffected(rowsAffected); step_ = UPD_STATS_; } } } break; case INSERT_VSBB_EXECUTE_: { cliRC = cliInterface()->executeImmediateExec( ctaTdb().viQuery_, NULL, NULL, TRUE, &rowsAffected); if (cliRC < 0) { cliInterface()->retrieveSQLDiagnostics(getDiagsArea()); step_ = HANDLE_ERROR_; } else { str_sprintf(outputBuf_, "childQidEnd: %s ", childQueryId_); moveRowToUpQueue(outputBuf_); masterGlob->setRowsAffected(rowsAffected); step_ = UPD_STATS_; return WORK_RESCHEDULE_AND_RETURN; } } break; case UPD_STATS_: { if ((ctaTdb().threshold_ == -1) || ((ctaTdb().threshold_ > 0) && (masterGlob->getRowsAffected() < ctaTdb().threshold_))) { step_ = DONE_; break; } // issue the upd stats command char * usQuery = new(getHeap()) char[strlen(ctaTdb().usQuery_) + 10 + 1]; str_sprintf(usQuery, ctaTdb().usQuery_, masterGlob->getRowsAffected()); cliRC = cliInterface()->executeImmediate(usQuery,NULL,NULL,TRUE,NULL,TRUE); NADELETEBASIC(usQuery, getHeap()); if (cliRC < 0) { cliInterface()->retrieveSQLDiagnostics(getDiagsArea()); step_ = HANDLE_ERROR_; break; } step_ = DONE_; } break; case HANDLE_ERROR_: { if ((ctaTdb().ctQuery_) && (ctaTdb().loadIfExists())) { // error case and 'load if exists' specified. // Do not drop the table, only delete data from it. step_ = DELETE_DATA_AND_ERROR_; } else step_ = DROP_AND_ERROR_; } break; case DROP_AND_ERROR_: { if ((ctaTdb().ctQuery_) && (NOT tableExists_)) { // this is an error case, drop the table char * dtQuery = new(getMyHeap()) char[strlen("DROP TABLE CASCADE; ") + strlen(ctaTdb().getTableName()) + 100]; strcpy(dtQuery, "DROP TABLE "); strcat(dtQuery, ctaTdb().getTableName()); strcat(dtQuery, " CASCADE;"); cliRC = cliInterface()->executeImmediate(dtQuery); // Delete new'd characters NADELETEBASIC(dtQuery, getHeap()); dtQuery = NULL; } else if (doSidetreeInsert_) { cliRC = changeAuditAttribute(ctaTdb().getTableName(), TRUE, ctaTdb().isVolatile()); } if (step_ == DROP_AND_ERROR_) step_ = ERROR_; else step_ = DONE_; } break; case DONE_: { if (qparent_.up->isFull()) return WORK_OK; // Return EOF. ex_queue_entry * up_entry = qparent_.up->getTailEntry(); up_entry->upState.parentIndex = pentry_down->downState.parentIndex; up_entry->upState.setMatchNo(0); up_entry->upState.status = ex_queue::Q_NO_DATA; // insert into parent qparent_.up->insert(); step_ = INITIAL_; qparent_.down->removeHead(); return WORK_OK; } break; case ERROR_: { if (qparent_.up->isFull()) return WORK_OK; // Return EOF. ex_queue_entry * up_entry = qparent_.up->getTailEntry(); up_entry->upState.parentIndex = pentry_down->downState.parentIndex; up_entry->upState.setMatchNo(0); up_entry->upState.status = ex_queue::Q_SQLERROR; ComDiagsArea *diagsArea = up_entry->getDiagsArea(); if (diagsArea == NULL) diagsArea = ComDiagsArea::allocate(this->getGlobals()->getDefaultHeap()); else diagsArea->incrRefCount (); // setDiagsArea call below will decr ref count if (getDiagsArea()) diagsArea->mergeAfter(*getDiagsArea()); up_entry->setDiagsArea (diagsArea); // insert into parent qparent_.up->insert(); pstate.matches_ = 0; step_ = DONE_; } break; } // switch } // while return WORK_OK; } //////////////////////////////////////////////////////////////////////// // Redefine virtual method allocatePstates, to be used by dynamic queue // resizing, as well as the initial queue construction. //////////////////////////////////////////////////////////////////////// ex_tcb_private_state * ExExeUtilCreateTableAsTcb::allocatePstates( Lng32 &numElems, // inout, desired/actual elements Lng32 &pstateLength) // out, length of one element { PstateAllocator<ExExeUtilCreateTableAsPrivateState> pa; return pa.allocatePstates(this, numElems, pstateLength); } ///////////////////////////////////////////////////////////////////////////// // Constructor and destructor for ExeUtil_private_state ///////////////////////////////////////////////////////////////////////////// ExExeUtilCreateTableAsPrivateState::ExExeUtilCreateTableAsPrivateState() { } ExExeUtilCreateTableAsPrivateState::~ExExeUtilCreateTableAsPrivateState() { }; #define SETSTEP(s) setStep(s, __LINE__) static THREAD_P bool sv_checked_yet = false; static THREAD_P bool sv_logStep = false; //////////////////////////////////////////////////////////////// // Methods for classes ExExeUtilAqrWnrInsertTdb and // ExExeUtilAqrWnrInsertTcb /////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////// ex_tcb * ExExeUtilAqrWnrInsertTdb::build(ex_globals * glob) { // build the child first ex_tcb * childTcb = child_->build(glob); ExExeUtilAqrWnrInsertTcb *exe_util_tcb; exe_util_tcb = new(glob->getSpace()) ExExeUtilAqrWnrInsertTcb(*this, childTcb, glob); exe_util_tcb->registerSubtasks(); return (exe_util_tcb); } ExExeUtilAqrWnrInsertTcb::ExExeUtilAqrWnrInsertTcb( const ComTdbExeUtilAqrWnrInsert & exe_util_tdb, const ex_tcb * child_tcb, ex_globals * glob) : ExExeUtilTcb( exe_util_tdb, child_tcb, glob) , step_(INITIAL_) , targetWasEmpty_(false) { } ExExeUtilAqrWnrInsertTcb::~ExExeUtilAqrWnrInsertTcb() { // mjh - tbd : // is base class dtor called? } Int32 ExExeUtilAqrWnrInsertTcb::fixup() { return ex_tcb::fixup(); } void ExExeUtilAqrWnrInsertTcb::setStep(Step newStep, int lineNum) { static bool sv_checked_yet = false; static bool sv_logStep = false; step_ = newStep; if (!sv_checked_yet) { sv_checked_yet = true; char *logST = getenv("LOG_AQR_WNR_INSERT"); if (logST && *logST == '1') sv_logStep = true; } if (!sv_logStep) return; if (NULL == getGlobals()->castToExExeStmtGlobals()->castToExMasterStmtGlobals()) return; char *stepStr = (char *) "UNKNOWN"; switch (step_) { case INITIAL_: stepStr = (char *) "INITIAL_"; break; case LOCK_TARGET_: stepStr = (char *) "LOCK_TARGET_"; break; case IS_TARGET_EMPTY_: stepStr = (char *) "IS_TARGET_EMPTY_"; break; case SEND_REQ_TO_CHILD_: stepStr = (char *) "SEND_REQ_TO_CHILD_"; break; case GET_REPLY_FROM_CHILD_: stepStr = (char *) "GET_REPLY_FROM_CHILD_"; break; case CLEANUP_CHILD_: stepStr = (char *) "CLEANUP_CHILD_"; break; case CLEANUP_TARGET_: stepStr = (char *) "CLEANUP_TARGET_"; break; case ERROR_: stepStr = (char *) "ERROR_"; break; case DONE_: stepStr = (char *) "DONE_"; break; } cout << stepStr << ", line " << lineNum << endl; } // Temporary. #define VERIFY_CLI_UTIL 1 ExWorkProcRetcode ExExeUtilAqrWnrInsertTcb::work() { ExWorkProcRetcode rc = WORK_OK; Lng32 cliRC = 0; // Get the globals stucture of the master executor. ExExeStmtGlobals *exeGlob = getGlobals()->castToExExeStmtGlobals(); ExMasterStmtGlobals *masterGlob = exeGlob->castToExMasterStmtGlobals(); ContextCli *currContext = masterGlob->getCliGlobals()->currContext(); while (! (qparent_.down->isEmpty() || qparent_.up->isFull()) ) { ex_queue_entry * pentry_down = qparent_.down->getHeadEntry(); ex_queue_entry * pentry_up = qparent_.up->getTailEntry(); switch (step_) { case INITIAL_: { targetWasEmpty_ = false; masterGlob->resetAqrWnrInsertCleanedup(); if (getDiagsArea()) getDiagsArea()->clear(); if (ulTdb().doLockTarget()) SETSTEP(LOCK_TARGET_); else SETSTEP(IS_TARGET_EMPTY_); break; } case LOCK_TARGET_: { SQL_EXEC_ClearDiagnostics(NULL); query_ = new(getGlobals()->getDefaultHeap()) char[1000]; str_sprintf(query_, "lock table %s in share mode;", ulTdb().getTableName()); Lng32 len = 0; char dummyArg[128]; #ifdef VERIFY_CLI_UTIL for (size_t i = 0; i < sizeof(dummyArg); i++) dummyArg[i] = i; #endif cliRC = cliInterface()->executeImmediate( query_, dummyArg, &len, NULL); #ifdef VERIFY_CLI_UTIL ex_assert (len == 0, "lock table returned data"); for (size_t i = 0; i < sizeof(dummyArg); i++) ex_assert( dummyArg[i] == i, "lock table returned data"); #endif NADELETEBASIC(query_, getMyHeap()); if (cliRC < 0) { cliInterface()->retrieveSQLDiagnostics(getDiagsArea()); SETSTEP(ERROR_); } else SETSTEP(IS_TARGET_EMPTY_); // Allow the query to be canceled. return WORK_CALL_AGAIN; } case IS_TARGET_EMPTY_: { SQL_EXEC_ClearDiagnostics(NULL); query_ = new(getGlobals()->getDefaultHeap()) char[1000]; str_sprintf(query_, "select row count from %s;", ulTdb().getTableName()); Lng32 len = 0; Int64 rowCount = 0; cliRC = cliInterface()->executeImmediate(query_, (char*)&rowCount, &len, NULL); NADELETEBASIC(query_, getMyHeap()); if (cliRC < 0) { cliInterface()->retrieveSQLDiagnostics(getDiagsArea()); SETSTEP(ERROR_); } else { targetWasEmpty_ = (rowCount == 0); SETSTEP(SEND_REQ_TO_CHILD_); } // Allow the query to be canceled. return WORK_CALL_AGAIN; } case SEND_REQ_TO_CHILD_: { if (qchild_.down->isFull()) return WORK_OK; ex_queue_entry * centry = qchild_.down->getTailEntry(); centry->downState.request = ex_queue::GET_ALL; centry->downState.requestValue = pentry_down->downState.requestValue; centry->downState.parentIndex = qparent_.down->getHeadIndex(); // set the child's input atp centry->passAtp(pentry_down->getAtp()); qchild_.down->insert(); SETSTEP(GET_REPLY_FROM_CHILD_); } break; case GET_REPLY_FROM_CHILD_: { // if nothing returned from child. Get outta here. if (qchild_.up->isEmpty()) return WORK_OK; ex_queue_entry * centry = qchild_.up->getHeadEntry(); // DA from child, if any, is copied to parent up entry. pentry_up->copyAtp(centry); switch(centry->upState.status) { case ex_queue::Q_NO_DATA: { SETSTEP(DONE_); break; } case ex_queue::Q_SQLERROR: { SETSTEP(CLEANUP_CHILD_); break; } default: { ex_assert(0, "Invalid child_status"); break; } } qchild_.up->removeHead(); break; } case CLEANUP_CHILD_: { bool lookingForQnoData = true; do { if (qchild_.up->isEmpty()) return WORK_OK; ex_queue_entry * centry = qchild_.up->getHeadEntry(); if (centry->upState.status == ex_queue::Q_NO_DATA) { lookingForQnoData = false; bool cleanupTarget = false; if (targetWasEmpty_ && (pentry_down->downState.request != ex_queue::GET_NOMORE)) { // Find out if any messages were sent to insert TSE sessions, // because we'd like to skip CLEANUP_TARGET_ if not. const ExStatisticsArea *constStatsArea = NULL; Lng32 cliRc = SQL_EXEC_GetStatisticsArea_Internal( SQLCLI_STATS_REQ_QID, masterGlob->getStatement()->getUniqueStmtId(), masterGlob->getStatement()->getUniqueStmtIdLen(), -1, SQLCLI_SAME_STATS, constStatsArea); ExStatisticsArea * statsArea = (ExStatisticsArea *) constStatsArea; if (cliRc < 0 || !statsArea) { // Error or some problem getting stats. cleanupTarget = true; } else if (!statsArea->getMasterStats() || statsArea->getMasterStats()->getStatsErrorCode() != 0) { // Partial success getting stats. Can't trust results. cleanupTarget = true; } else if (statsArea->anyHaveSentMsgIUD()) { // Stats shows that IUD started. Must cleanup. cleanupTarget = true; } } if (cleanupTarget) SETSTEP(CLEANUP_TARGET_); else SETSTEP(ERROR_); } qchild_.up->removeHead(); } while (lookingForQnoData); break; } case CLEANUP_TARGET_: { SQL_EXEC_ClearDiagnostics(NULL); query_ = new(getGlobals()->getDefaultHeap()) char[1000]; str_sprintf(query_, "delete with no rollback from %s;", ulTdb().getTableName()); Lng32 len = 0; char dummyArg[128]; cliRC = cliInterface()->executeImmediate( query_, dummyArg, &len, NULL); NADELETEBASIC(query_, getMyHeap()); if (cliRC < 0) { // mjh - tbd - warning or EMS message to give context to error on // delete after error on the insert? cliInterface()->retrieveSQLDiagnostics(getDiagsArea()); } else masterGlob->setAqrWnrInsertCleanedup(); SETSTEP(ERROR_); break; } case ERROR_: { if (pentry_down->downState.request != ex_queue::GET_NOMORE) { if (getDiagsArea()) { // Any error from child already put a DA into pentry_up. if (NULL == pentry_up->getDiagsArea()) { ComDiagsArea * da = ComDiagsArea::allocate( getGlobals()->getDefaultHeap()); pentry_up->setDiagsArea(da); } pentry_up->getDiagsArea()->mergeAfter(*getDiagsArea()); getDiagsArea()->clear(); SQL_EXEC_ClearDiagnostics(NULL); } pentry_up->upState.status = ex_queue::Q_SQLERROR; pentry_up->upState.parentIndex = pentry_down->downState.parentIndex; pentry_up->upState.downIndex = qparent_.down->getHeadIndex(); qparent_.up->insert(); } SETSTEP(DONE_); break; } case DONE_: { // Return EOF. pentry_up->upState.parentIndex = pentry_down->downState.parentIndex; pentry_up->upState.setMatchNo(0); pentry_up->upState.status = ex_queue::Q_NO_DATA; // insert into parent qparent_.up->insert(); SETSTEP(INITIAL_); qparent_.down->removeHead(); break; } } // switch } // while return WORK_OK; } ExWorkProcRetcode ExExeUtilAqrWnrInsertTcb::workCancel() { if (!(qparent_.down->isEmpty()) && (ex_queue::GET_NOMORE == qparent_.down->getHeadEntry()->downState.request)) { switch (step_) { case INITIAL_: SETSTEP(DONE_); break; case LOCK_TARGET_: ex_assert (0, "work method doesn't return with step_ set to LOCK_TARGET_."); break; case IS_TARGET_EMPTY_: ex_assert (0, "work method doesn't return with step_ set " "to IS_TARGET_EMPTY_."); break; case SEND_REQ_TO_CHILD_: SETSTEP(DONE_); break; case GET_REPLY_FROM_CHILD_: // Assuming that the entire query is canceled. Canceled queries // are not AQR'd. Will cleanup without purging target. qchild_.down->cancelRequest(); SETSTEP(CLEANUP_CHILD_); break; case CLEANUP_CHILD_: // CLEANUP_CHILD_ does the right thing when canceling. break; case ERROR_: // ERROR_ does the right thing when canceling. break; case CLEANUP_TARGET_: ex_assert (0, "work method doesn't return with step_ set to CLEANUP_TARGET_,."); break; case DONE_: ex_assert (0, "work method doesn't return with step_ set to DONE_."); break; } } return WORK_OK; } #define changeStep(x) changeAndTraceStep(x, __LINE__) //////////////////////////////////////////////////////////////// // build for class ExExeUtilHbaseLoadTdb /////////////////////////////////////////////////////////////// ex_tcb * ExExeUtilHBaseBulkLoadTdb::build(ex_globals * glob) { ExExeUtilHBaseBulkLoadTcb * exe_util_tcb; exe_util_tcb = new(glob->getSpace()) ExExeUtilHBaseBulkLoadTcb(*this, glob); exe_util_tcb->registerSubtasks(); return (exe_util_tcb); } //////////////////////////////////////////////////////////////// // Constructor for class ExExeUtilHbaseLoadTcb /////////////////////////////////////////////////////////////// ExExeUtilHBaseBulkLoadTcb::ExExeUtilHBaseBulkLoadTcb( const ComTdbExeUtil & exe_util_tdb, ex_globals * glob) : ExExeUtilTcb( exe_util_tdb, NULL, glob), step_(INITIAL_), nextStep_(INITIAL_), rowsAffected_(0), loggingLocation_(NULL) { ehi_ = NULL; qparent_.down->allocatePstate(this); } ExExeUtilHBaseBulkLoadTcb::~ExExeUtilHBaseBulkLoadTcb() { if (loggingLocation_ != NULL) { NADELETEBASIC(loggingLocation_, getHeap()); loggingLocation_ = NULL; } } ////////////////////////////////////////////////////// // work() for ExExeUtilHbaseLoadTcb ////////////////////////////////////////////////////// short ExExeUtilHBaseBulkLoadTcb::work() { Lng32 cliRC = 0; short retcode = 0; short rc; Lng32 errorRowCount = 0; int len; ComDiagsArea *diagsArea; // if no parent request, return if (qparent_.down->isEmpty()) return WORK_OK; // if no room in up queue, won't be able to return data/status. // Come back later. if (qparent_.up->isFull()) return WORK_OK; ex_queue_entry * pentry_down = qparent_.down->getHeadEntry(); ExExeUtilPrivateState & pstate = *((ExExeUtilPrivateState*) pentry_down->pstate); ContextCli *currContext = getGlobals()->castToExExeStmtGlobals()->castToExMasterStmtGlobals()-> getStatement()->getContext(); ExTransaction *ta = currContext->getTransaction(); NABoolean ustatNonEmptyTable = FALSE; while (1) { switch (step_) { case INITIAL_: { NABoolean xnAlreadyStarted = ta->xnInProgress(); if (xnAlreadyStarted && //a transaction is active when we load/populate an indexe table !hblTdb().getIndexTableOnly()) { //8111 - Transactions are not allowed with Bulk load. ComDiagsArea * da = getDiagsArea(); *da << DgSqlCode(-8111); step_ = LOAD_ERROR_; break; } if (setStartStatusMsgAndMoveToUpQueue(" LOAD", &rc)) return rc; if (hblTdb().getUpsertUsingLoad()) hblTdb().setPreloadCleanup(FALSE); if (hblTdb().getTruncateTable()) { step_ = TRUNCATE_TABLE_; break; } // Table will not be truncated, so make sure it is empty if Update // Stats has been requested. We obviously have to do this check before // the load, but if the table is determined to be non-empty, the // message is deferred until the UPDATE_STATS_ step. if (hblTdb().getUpdateStats()) { NAString selectFirstQuery = "select [first 1] 0 from "; selectFirstQuery.append(hblTdb().getTableName()).append(";"); cliRC = cliInterface()->executeImmediate(selectFirstQuery.data()); if (cliRC < 0) { step_ = LOAD_END_ERROR_; break; } else if (cliRC != 100) ustatNonEmptyTable = TRUE; // So we can display msg later } step_ = LOAD_START_; } break; case TRUNCATE_TABLE_: { if (setStartStatusMsgAndMoveToUpQueue(" PURGE DATA",&rc, 0, TRUE)) return rc; // Set the parserflag to prevent privilege checks in purgedata ExExeStmtGlobals *exeGlob = getGlobals()->castToExExeStmtGlobals(); ExMasterStmtGlobals *masterGlob = exeGlob->castToExMasterStmtGlobals(); NABoolean parserFlagSet = FALSE; if ((masterGlob->getStatement()->getContext()->getSqlParserFlags() & 0x20000) == 0) { parserFlagSet = TRUE; masterGlob->getStatement()->getContext()->setSqlParserFlags(0x20000); } //for now the purgedata statement does not keep the partitions char * ttQuery = new(getMyHeap()) char[strlen("PURGEDATA ; ") + strlen(hblTdb().getTableName()) + 100]; strcpy(ttQuery, "PURGEDATA "); strcat(ttQuery, hblTdb().getTableName()); strcat(ttQuery, ";"); Lng32 len = 0; Int64 rowCount = 0; cliRC = cliInterface()->executeImmediate(ttQuery, NULL,NULL,TRUE,NULL,TRUE); NADELETEBASIC(ttQuery, getHeap()); ttQuery = NULL; if (parserFlagSet) masterGlob->getStatement()->getContext()->resetSqlParserFlags(0x20000); if (cliRC < 0) { cliInterface()->retrieveSQLDiagnostics(getDiagsArea()); step_ = LOAD_ERROR_; break; } step_ = LOAD_START_; setEndStatusMsg(" PURGE DATA", 0, TRUE); } break; case LOAD_START_: { if (setCQDs() <0) { step_ = LOAD_END_ERROR_; break; } int jniDebugPort = 0; int jniDebugTimeout = 0; ehi_ = ExpHbaseInterface::newInstance(getGlobals()->getDefaultHeap(), (char*)"", //Later may need to change to hblTdb.server_, (char*)"", //Later may need to change to hblTdb.zkPort_, jniDebugPort, jniDebugTimeout); retcode = ehi_->initHBLC(); if (retcode == 0) retcode = ehi_->createCounterTable(hblTdb().getErrCountTable(), (char *)"ERRORS"); if (retcode != 0 ) { Lng32 cliError = 0; Lng32 intParam1 = -retcode; diagsArea = NULL; ExRaiseSqlError(getHeap(), &diagsArea, (ExeErrorCode)(8448), NULL, &intParam1, &cliError, NULL, " ", getHbaseErrStr(retcode), (char *)currContext->getJniErrorStr().data()); step_ = LOAD_END_ERROR_; break; } if (hblTdb().getPreloadCleanup()) step_ = PRE_LOAD_CLEANUP_; else { step_ = PREPARATION_; if (hblTdb().getRebuildIndexes() || hblTdb().getHasUniqueIndexes()) step_ = DISABLE_INDEXES_; } } break; case PRE_LOAD_CLEANUP_: { if (setStartStatusMsgAndMoveToUpQueue(" CLEANUP", &rc, 0, TRUE)) return rc; //Cleanup files char * clnpQuery = new(getMyHeap()) char[strlen("LOAD CLEANUP FOR TABLE ; ") + strlen(hblTdb().getTableName()) + 100]; strcpy(clnpQuery, "LOAD CLEANUP FOR TABLE "); if (hblTdb().getIndexTableOnly()) strcat(clnpQuery, "TABLE(INDEX_TABLE "); strcat(clnpQuery, hblTdb().getTableName()); if (hblTdb().getIndexTableOnly()) strcat(clnpQuery, ")"); strcat(clnpQuery, ";"); cliRC = cliInterface()->executeImmediate(clnpQuery, NULL,NULL,TRUE,NULL,TRUE); NADELETEBASIC(clnpQuery, getHeap()); clnpQuery = NULL; if (cliRC < 0) { cliInterface()->retrieveSQLDiagnostics(getDiagsArea()); step_ = LOAD_END_ERROR_; break; } step_ = PREPARATION_; if (hblTdb().getRebuildIndexes() || hblTdb().getHasUniqueIndexes()) step_ = DISABLE_INDEXES_; setEndStatusMsg(" CLEANUP", 0, TRUE); } break; case DISABLE_INDEXES_: { if (setStartStatusMsgAndMoveToUpQueue(" DISABLE INDEXES", &rc, 0, TRUE)) return rc; // disable indexes before starting the load preparation. load preparation phase will // give an error if indexes are not disabled // For constarints --disabling/enabling constarints is not supported yet. in this case the user // needs to disable or drop the constraints manually before starting load. If constarints // exist load preparation will give an error char * diQuery = new(getMyHeap()) char[strlen("ALTER TABLE DISABLE ALL INDEXES ; ") + strlen(hblTdb().getTableName()) + 100]; strcpy(diQuery, "ALTER TABLE "); strcat(diQuery, hblTdb().getTableName()); if (hblTdb().getRebuildIndexes()) strcat(diQuery, " DISABLE ALL INDEXES ;"); else strcat(diQuery, " DISABLE ALL UNIQUE INDEXES ;"); // has unique indexes and rebuild not specified cliRC = cliInterface()->executeImmediate(diQuery, NULL,NULL,TRUE,NULL,TRUE); NADELETEBASIC(diQuery, getMyHeap()); diQuery = NULL; if (cliRC < 0) { cliInterface()->retrieveSQLDiagnostics(getDiagsArea()); step_ = LOAD_END_ERROR_; break; } step_ = PREPARATION_; setEndStatusMsg(" DISABLE INDEXES", 0, TRUE); } break; case PREPARATION_: { short bufPos = 0; if (!hblTdb().getUpsertUsingLoad()) { setLoggingLocation(); bufPos = printLoggingLocation(0); if (setStartStatusMsgAndMoveToUpQueue(" LOADING DATA", &rc, bufPos, TRUE)) return rc; else { step_ = LOADING_DATA_; return WORK_CALL_AGAIN; } } else step_ = LOADING_DATA_; } break; case LOADING_DATA_: { if (!hblTdb().getUpsertUsingLoad()) { if (hblTdb().getNoDuplicates()) cliRC = holdAndSetCQD("TRAF_LOAD_PREP_SKIP_DUPLICATES", "OFF"); else cliRC = holdAndSetCQD("TRAF_LOAD_PREP_SKIP_DUPLICATES", "ON"); if (cliRC < 0) { step_ = LOAD_END_ERROR_; break; } if (loggingLocation_ != NULL) cliRC = holdAndSetCQD("TRAF_LOAD_ERROR_LOGGING_LOCATION", loggingLocation_); if (cliRC < 0) { step_ = LOAD_END_ERROR_; break; } rowsAffected_ = 0; char *loadQuery = hblTdb().ldQuery_; if (ustatNonEmptyTable) { // If the ustat option was specified, but the table to be loaded // is not empty, we have to retract the WITH SAMPLE option that // was added to the LOAD TRANSFORM statement when the original // bulk load statement was parsed. const char* sampleOpt = " WITH SAMPLE "; char* sampleOptPtr = strstr(loadQuery, sampleOpt); if (sampleOptPtr) memset(sampleOptPtr, ' ', strlen(sampleOpt)); } //printf("*** Load stmt is %s\n",loadQuery); // If the WITH SAMPLE clause is included, set the internal exe util // parser flag to allow it. ExExeStmtGlobals *exeGlob = getGlobals()->castToExExeStmtGlobals(); ExMasterStmtGlobals *masterGlob = exeGlob->castToExMasterStmtGlobals(); NABoolean parserFlagSet = FALSE; if (hblTdb().getUpdateStats() && !ustatNonEmptyTable) { if ((masterGlob->getStatement()->getContext()->getSqlParserFlags() & 0x20000) == 0) { parserFlagSet = TRUE; masterGlob->getStatement()->getContext()->setSqlParserFlags(0x20000); } } diagsArea = getDiagsArea(); cliRC = cliInterface()->executeImmediate(loadQuery, NULL, NULL, TRUE, &rowsAffected_, FALSE, diagsArea); if (parserFlagSet) masterGlob->getStatement()->getContext()->resetSqlParserFlags(0x20000); if (cliRC < 0) { rowsAffected_ = 0; cliInterface()->retrieveSQLDiagnostics(getDiagsArea()); step_ = LOAD_END_ERROR_; break; } else { step_ = COMPLETE_BULK_LOAD_; ComCondition *cond; Lng32 entryNumber; while ((cond = diagsArea->findCondition(EXE_ERROR_ROWS_FOUND, &entryNumber)) != NULL) { errorRowCount = cond->getOptionalInteger(0); diagsArea->deleteWarning(entryNumber); } diagsArea->setRowCount(0); } if (rowsAffected_ == 0) step_ = LOAD_END_; sprintf(statusMsgBuf_, " Rows Processed: %ld %c",rowsAffected_+errorRowCount, '\n' ); int len = strlen(statusMsgBuf_); sprintf(&statusMsgBuf_[len]," Error Rows: %d %c",errorRowCount, '\n' ); len = strlen(statusMsgBuf_); setEndStatusMsg(" LOADING DATA", len, TRUE); } else { if (setStartStatusMsgAndMoveToUpQueue(" UPSERT USING LOAD ", &rc, 0, TRUE)) return rc; rowsAffected_ = 0; char * upsQuery = hblTdb().ldQuery_; cliRC = cliInterface()->executeImmediate(upsQuery, NULL, NULL, TRUE, &rowsAffected_); upsQuery = NULL; if (cliRC < 0) { cliInterface()->retrieveSQLDiagnostics(getDiagsArea()); step_ = LOAD_ERROR_; break; } step_ = LOAD_END_; if (hblTdb().getRebuildIndexes() || hblTdb().getHasUniqueIndexes()) step_ = POPULATE_INDEXES_; sprintf(statusMsgBuf_," Rows Processed: %ld %c",rowsAffected_, '\n' ); int len = strlen(statusMsgBuf_); setEndStatusMsg(" UPSERT USING LOAD ", len, TRUE); } } break; case COMPLETE_BULK_LOAD_: { if (setStartStatusMsgAndMoveToUpQueue(" COMPLETION", &rc,0, TRUE)) return rc; //TRAF_LOAD_TAKE_SNAPSHOT if (hblTdb().getNoRollback() ) cliRC = holdAndSetCQD("TRAF_LOAD_TAKE_SNAPSHOT", "OFF"); else cliRC = holdAndSetCQD("TRAF_LOAD_TAKE_SNAPSHOT", "ON"); if (cliRC < 0) { step_ = LOAD_END_ERROR_; break; } //this case is mainly for debugging if (hblTdb().getKeepHFiles() && !hblTdb().getSecure() ) { if (holdAndSetCQD("COMPLETE_BULK_LOAD_N_KEEP_HFILES", "ON") < 0) { step_ = LOAD_END_ERROR_; break; } } //complete load query char * clQuery = new(getMyHeap()) char[strlen("LOAD COMPLETE FOR TABLE ; ") + strlen(hblTdb().getTableName()) + 100]; strcpy(clQuery, "LOAD COMPLETE FOR TABLE "); if (hblTdb().getIndexTableOnly()) strcat(clQuery, "TABLE(INDEX_TABLE "); strcat(clQuery, hblTdb().getTableName()); if (hblTdb().getIndexTableOnly()) strcat(clQuery, ")"); strcat(clQuery, ";"); cliRC = cliInterface()->executeImmediate(clQuery, NULL,NULL,TRUE,NULL,TRUE, getDiagsArea()); NADELETEBASIC(clQuery, getMyHeap()); clQuery = NULL; if (cliRC < 0) rowsAffected_ = 0; sprintf(statusMsgBuf_, " Rows Loaded: %ld %c",rowsAffected_, '\n' ); len = strlen(statusMsgBuf_); if (cliRC < 0) { rowsAffected_ = 0; cliInterface()->retrieveSQLDiagnostics(getDiagsArea()); setEndStatusMsg(" COMPLETION", len, TRUE); step_ = LOAD_END_ERROR_; break; } cliRC = restoreCQD("TRAF_LOAD_TAKE_SNAPSHOT"); if (hblTdb().getRebuildIndexes() || hblTdb().getHasUniqueIndexes()) step_ = POPULATE_INDEXES_; else if (hblTdb().getUpdateStats()) step_ = UPDATE_STATS_; else step_ = LOAD_END_; setEndStatusMsg(" COMPLETION", len, TRUE); } break; case POPULATE_INDEXES_: { if (setStartStatusMsgAndMoveToUpQueue(" POPULATE INDEXES", &rc, 0, TRUE)) return rc; else { step_ = POPULATE_INDEXES_EXECUTE_; return WORK_CALL_AGAIN; } } break; case POPULATE_INDEXES_EXECUTE_: { char * piQuery = new(getMyHeap()) char[strlen("POPULATE ALL INDEXES ON ; ") + strlen(hblTdb().getTableName()) + 100]; if (hblTdb().getRebuildIndexes()) strcpy(piQuery, "POPULATE ALL INDEXES ON "); else strcpy(piQuery, "POPULATE ALL UNIQUE INDEXES ON "); // has unique indexes and rebuild not used strcat(piQuery, hblTdb().getTableName()); strcat(piQuery, ";"); cliRC = cliInterface()->executeImmediate(piQuery, NULL,NULL,TRUE,NULL,TRUE); NADELETEBASIC(piQuery, getHeap()); piQuery = NULL; if (cliRC < 0) { cliInterface()->retrieveSQLDiagnostics(getDiagsArea()); step_ = LOAD_END_ERROR_; break; } if (hblTdb().getUpdateStats()) step_ = UPDATE_STATS_; else step_ = LOAD_END_; setEndStatusMsg(" POPULATE INDEXES", 0, TRUE); } break; case UPDATE_STATS_: { if (setStartStatusMsgAndMoveToUpQueue(" UPDATE STATISTICS", &rc, 0, TRUE)) return rc; else { step_ = UPDATE_STATS_EXECUTE_; return WORK_CALL_AGAIN; } } break; case UPDATE_STATS_EXECUTE_: { if (ustatNonEmptyTable) { // Table was not empty prior to the load. step_ = LOAD_END_; sprintf(statusMsgBuf_, " UPDATE STATISTICS not executed: table %s not empty before load. %c", hblTdb().getTableName(), '\n' ); int len = strlen(statusMsgBuf_); setEndStatusMsg(" UPDATE STATS", len, TRUE); break; } char * ustatStmt = new(getMyHeap()) char[strlen("UPDATE STATS FOR TABLE ON EVERY COLUMN; ") + strlen(hblTdb().getTableName()) + 100]; strcpy(ustatStmt, "UPDATE STATISTICS FOR TABLE "); strcat(ustatStmt, hblTdb().getTableName()); strcat(ustatStmt, " ON EVERY COLUMN;"); cliRC = holdAndSetCQD("USTAT_USE_BACKING_SAMPLE", "ON"); if (cliRC < 0) { step_ = LOAD_END_ERROR_; break; } cliRC = cliInterface()->executeImmediate(ustatStmt, NULL, NULL, TRUE, NULL, TRUE); NADELETEBASIC(ustatStmt, getMyHeap()); ustatStmt = NULL; if (cliRC < 0) { cliInterface()->retrieveSQLDiagnostics(getDiagsArea()); step_ = LOAD_END_ERROR_; } else step_ = LOAD_END_; cliRC = restoreCQD("USTAT_USE_BACKING_SAMPLE"); if (cliRC < 0) step_ = LOAD_END_ERROR_; setEndStatusMsg(" UPDATE STATS", 0, TRUE); } break; case RETURN_STATUS_MSG_: { if (moveRowToUpQueue(statusMsgBuf_,0,&rc)) return rc; step_ = nextStep_; } break; case LOAD_END_: case LOAD_END_ERROR_: { if (restoreCQDs() < 0) { step_ = LOAD_ERROR_; break; } if (hblTdb().getContinueOnError() && ehi_) { ehi_->close(); ehi_ = NULL; } if (step_ == LOAD_END_) step_ = DONE_; else step_ = LOAD_ERROR_; } break; case DONE_: { if (qparent_.up->isFull()) return WORK_OK; // Return EOF. ex_queue_entry * up_entry = qparent_.up->getTailEntry(); up_entry->upState.parentIndex = pentry_down->downState.parentIndex; up_entry->upState.setMatchNo(0); up_entry->upState.status = ex_queue::Q_NO_DATA; diagsArea = up_entry->getDiagsArea(); if (diagsArea == NULL) diagsArea = ComDiagsArea::allocate(getMyHeap()); else diagsArea->incrRefCount(); // setDiagsArea call below will decr ref count diagsArea->setRowCount(rowsAffected_); if (getDiagsArea()) diagsArea->mergeAfter(*getDiagsArea()); up_entry->setDiagsArea(diagsArea); // insert into parent qparent_.up->insert(); step_ = INITIAL_; qparent_.down->removeHead(); return WORK_OK; } break; case LOAD_ERROR_: { if (qparent_.up->isFull()) return WORK_OK; // Return EOF. ex_queue_entry * up_entry = qparent_.up->getTailEntry(); up_entry->upState.parentIndex = pentry_down->downState.parentIndex; up_entry->upState.setMatchNo(0); up_entry->upState.status = ex_queue::Q_SQLERROR; ComDiagsArea *diagsArea = up_entry->getDiagsArea(); if (diagsArea == NULL) diagsArea = ComDiagsArea::allocate(getMyHeap()); else diagsArea->incrRefCount(); // setDiagsArea call below will decr ref count if (getDiagsArea()) { diagsArea->mergeAfter(*getDiagsArea()); diagsArea->setRowCount(rowsAffected_); } up_entry->setDiagsArea(diagsArea); // insert into parent qparent_.up->insert(); pstate.matches_ = 0; step_ = DONE_; } break; } // switch } // while return WORK_OK; } short ExExeUtilHBaseBulkLoadTcb::setCQDs() { if (holdAndSetCQD("COMP_BOOL_226", "ON") < 0) { return -1;} // next cqd required to allow load into date/timestamp Traf columns from string Hive columns. // This is a common use case. Cqd can be removed when Traf hive access supports more Hive types. if (holdAndSetCQD("ALLOW_INCOMPATIBLE_OPERATIONS", "ON") < 0) { return -1;} if (hblTdb().getForceCIF()) { if (holdAndSetCQD("COMPRESSED_INTERNAL_FORMAT", "ON") < 0) {return -1; } if (holdAndSetCQD("COMPRESSED_INTERNAL_FORMAT_BMO", "ON") < 0){ return -1; } if (holdAndSetCQD("COMPRESSED_INTERNAL_FORMAT_DEFRAG_RATIO", "100") < 0) { return -1;} } if (holdAndSetCQD("TRAF_LOAD_LOG_ERROR_ROWS", (hblTdb().getLogErrorRows()) ? "ON" : "OFF") < 0) { return -1;} if (holdAndSetCQD("TRAF_LOAD_CONTINUE_ON_ERROR", (hblTdb().getContinueOnError()) ? "ON" : "OFF") < 0) { return -1; } char strMaxRR[10]; sprintf(strMaxRR,"%d", hblTdb().getMaxErrorRows()); if (holdAndSetCQD("TRAF_LOAD_MAX_ERROR_ROWS", strMaxRR) < 0) { return -1;} if (hblTdb().getContinueOnError()) { if (holdAndSetCQD("TRAF_LOAD_ERROR_COUNT_TABLE", hblTdb().getErrCountTable()) < 0) { return -1;} time_t t; time(&t); char pt[30]; struct tm * curgmtime = gmtime(&t); strftime(pt, 30, "%Y%m%d_%H%M%S", curgmtime); if (holdAndSetCQD("TRAF_LOAD_ERROR_COUNT_ID", pt) < 0) { return -1;} } return 0; } short ExExeUtilHBaseBulkLoadTcb::restoreCQDs() { if (restoreCQD("COMP_BOOL_226") < 0) { return -1;} if (restoreCQD("TRAF_LOAD_PREP_SKIP_DUPLICATES") < 0) { return -1;} if (restoreCQD("ALLOW_INCOMPATIBLE_OPERATIONS") < 0) { return -1;} if (hblTdb().getForceCIF()) { if (restoreCQD("COMPRESSED_INTERNAL_FORMAT") < 0) { return -1;} if (restoreCQD("COMPRESSED_INTERNAL_FORMAT_BMO") < 0) { return -1;} if (restoreCQD("COMPRESSED_INTERNAL_FORMAT_DEFRAG_RATIO") < 0) { return -1;} } if (restoreCQD("TRAF_LOAD_LOG_ERROR_ROWS") < 0) { return -1;} if (restoreCQD("TRAF_LOAD_CONTINUE_ON_ERROR") < 0) { return -1;} if (restoreCQD("TRAF_LOAD_MAX_ERROR_ROWS") < 0) { return -1;} if (restoreCQD("TRAF_LOAD_ERROR_COUNT_TABLE") < 0) { return -1;} if (restoreCQD("TRAF_LOAD_ERROR_COUNT_ID") < 0) { return -1; } if (restoreCQD("TRAF_LOAD_ERROR_LOGGING_LOCATION") < 0) { return -1; } return 0; } short ExExeUtilHBaseBulkLoadTcb::moveRowToUpQueue(const char * row, Lng32 len, short * rc, NABoolean isVarchar) { if (hblTdb().getNoOutput()) return 0; return ExExeUtilTcb::moveRowToUpQueue(row, len, rc, isVarchar); } short ExExeUtilHBaseBulkLoadTcb::printLoggingLocation(int bufPos) { short retBufPos = bufPos; if (hblTdb().getNoOutput()) return 0; if (loggingLocation_ != NULL) { str_sprintf(&statusMsgBuf_[bufPos], " Logging Location: %s", loggingLocation_); retBufPos = strlen(statusMsgBuf_); statusMsgBuf_[retBufPos] = '\n'; retBufPos++; } return retBufPos; } short ExExeUtilHBaseBulkLoadTcb::setStartStatusMsgAndMoveToUpQueue(const char * operation, short * rc, int bufPos, NABoolean withtime) { if (hblTdb().getNoOutput()) return 0; char timeBuf[200]; if (withtime) { startTime_ = NA_JulianTimestamp(); getTimestampAsString(startTime_, timeBuf); } getStatusString(operation, "Started",hblTdb().getTableName(), &statusMsgBuf_[bufPos], FALSE, (withtime ? timeBuf : NULL)); return moveRowToUpQueue(statusMsgBuf_,0,rc); } void ExExeUtilHBaseBulkLoadTcb::setEndStatusMsg(const char * operation, int bufPos, NABoolean withtime) { if (hblTdb().getNoOutput()) return ; char timeBuf[200]; nextStep_ = step_; step_ = RETURN_STATUS_MSG_; Int64 elapsedTime; if (withtime) { endTime_ = NA_JulianTimestamp(); elapsedTime = endTime_ - startTime_; getTimestampAsString(endTime_, timeBuf); getStatusString(operation, "Ended", hblTdb().getTableName(),&statusMsgBuf_[bufPos], FALSE, withtime ? timeBuf : NULL); bufPos = strlen(statusMsgBuf_); statusMsgBuf_[bufPos] = '\n'; bufPos++; getTimeAsString(elapsedTime, timeBuf); } getStatusString(operation, "Ended", hblTdb().getTableName(),&statusMsgBuf_[bufPos], TRUE, withtime ? timeBuf : NULL); } void ExExeUtilHBaseBulkLoadTcb::setLoggingLocation() { char * loggingLocation = hblTdb().getLoggingLocation(); if (loggingLocation_ != NULL) { NADELETEBASIC(loggingLocation_, getHeap()); loggingLocation_ = NULL; } if (loggingLocation != NULL) { short logLen = strlen(loggingLocation); char *tableName = hblTdb().getTableName(); short tableNameLen = strlen(tableName); loggingLocation_ = new (getHeap()) char[logLen+tableNameLen+100]; ExHbaseAccessTcb::buildLoggingPath(loggingLocation, NULL, tableName, loggingLocation_); } } //////////////////////////////////////////////////////////////////////// // Redefine virtual method allocatePstates, to be used by dynamic queue // resizing, as well as the initial queue construction. //////////////////////////////////////////////////////////////////////// ex_tcb_private_state * ExExeUtilHBaseBulkLoadTcb::allocatePstates( Lng32 &numElems, // inout, desired/actual elements Lng32 &pstateLength) // out, length of one element { PstateAllocator<ExExeUtilHbaseLoadPrivateState> pa; return pa.allocatePstates(this, numElems, pstateLength); } ///////////////////////////////////////////////////////////////////////////// // Constructor and destructor for ExeUtil_private_state ///////////////////////////////////////////////////////////////////////////// ExExeUtilHbaseLoadPrivateState::ExExeUtilHbaseLoadPrivateState() { } ExExeUtilHbaseLoadPrivateState::~ExExeUtilHbaseLoadPrivateState() { }; //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// // build for class ExExeUtilHbaseUnLoadTdb /////////////////////////////////////////////////////////////// ex_tcb * ExExeUtilHBaseBulkUnLoadTdb::build(ex_globals * glob) { ExExeUtilHBaseBulkUnLoadTcb * exe_util_tcb; exe_util_tcb = new(glob->getSpace()) ExExeUtilHBaseBulkUnLoadTcb(*this, glob); exe_util_tcb->registerSubtasks(); return (exe_util_tcb); } void ExExeUtilHBaseBulkUnLoadTcb::createHdfsFileError(Int32 sfwRetCode) { ComDiagsArea * diagsArea = NULL; char* errorMsg = sequenceFileWriter_->getErrorText((SFW_RetCode)sfwRetCode); ExRaiseSqlError(getHeap(), &diagsArea, (ExeErrorCode)(8447), NULL, NULL, NULL, NULL, errorMsg, (char *)GetCliGlobals()->currContext()->getJniErrorStr().data()); ex_queue_entry *pentry_up = qparent_.up->getTailEntry(); pentry_up->setDiagsArea(diagsArea); } //////////////////////////////////////////////////////////////// // Constructor for class ExExeUtilHbaseLoadTcb /////////////////////////////////////////////////////////////// ExExeUtilHBaseBulkUnLoadTcb::ExExeUtilHBaseBulkUnLoadTcb( const ComTdbExeUtil & exe_util_tdb, ex_globals * glob) : ExExeUtilTcb( exe_util_tdb, NULL, glob), step_(INITIAL_), nextStep_(INITIAL_), rowsAffected_(0), snapshotsList_(NULL), emptyTarget_(FALSE), oneFile_(FALSE) { sequenceFileWriter_ = NULL; int jniDebugPort = 0; int jniDebugTimeout = 0; ehi_ = ExpHbaseInterface::newInstance(getGlobals()->getDefaultHeap(), (char*)"", //Later may need to change to hblTdb.server_, (char*)"", //Later may need to change to hblTdb.zkPort_, jniDebugPort, jniDebugTimeout); qparent_.down->allocatePstate(this); } void ExExeUtilHBaseBulkUnLoadTcb::freeResources() { if (snapshotsList_) { for ( ; snapshotsList_->entries(); ) { snapshotStruct *snp = snapshotsList_->at(0); snapshotsList_->removeAt(0); NADELETEBASIC(snp->fullTableName, getMyHeap()); NADELETEBASIC(snp->snapshotName, getMyHeap()); NADELETEBASIC( snp, getMyHeap()); snp->fullTableName = NULL; snp->snapshotName = NULL; snp = NULL; } NADELETEBASIC (snapshotsList_, getMyHeap()); snapshotsList_ = NULL; } if (sequenceFileWriter_) { NADELETE(sequenceFileWriter_, SequenceFileWriter, getMyHeap()); sequenceFileWriter_ = NULL; } NADELETE(ehi_, ExpHbaseInterface, getGlobals()->getDefaultHeap()); ehi_ = NULL; } ExExeUtilHBaseBulkUnLoadTcb::~ExExeUtilHBaseBulkUnLoadTcb() { freeResources(); } short ExExeUtilHBaseBulkUnLoadTcb::resetExplainSettings() { if (cliInterface()->executeImmediate("control session reset 'EXPLAIN';") < 0) { cliInterface()->retrieveSQLDiagnostics(getDiagsArea()); return -1; } if (restoreCQD("generate_explain") < 0) { cliInterface()->retrieveSQLDiagnostics(getDiagsArea()); return -1; } return 0; } short ExExeUtilHBaseBulkUnLoadTcb::getTrafodionScanTables() { // Variables SQLMODULE_ID * module = NULL; SQLSTMT_ID * stmt = NULL; SQLDESC_ID * sql_src = NULL; SQLDESC_ID * input_desc = NULL; SQLDESC_ID * output_desc = NULL; char * outputBuf = NULL; assert (snapshotsList_ != NULL); Lng32 cliRC = 0; if (holdAndSetCQD("generate_explain", "ON") < 0) { cliInterface()->retrieveSQLDiagnostics(getDiagsArea()); resetExplainSettings(); return -1; } // tell mxcmp that this prepare is for explain. cliRC = cliInterface()->executeImmediate("control session 'EXPLAIN' 'ON';"); if (cliRC < 0) { cliInterface()->retrieveSQLDiagnostics(getDiagsArea()); resetExplainSettings(); return cliRC; } cliInterface()->clearGlobalDiags(); cliRC = cliInterface()->allocStuff(module, stmt, sql_src, input_desc, output_desc, "__EXPL_STMT_NAME__"); if (cliRC < 0) { cliInterface()->retrieveSQLDiagnostics(getDiagsArea()); resetExplainSettings(); return cliRC; } char * stmtStr = hblTdb().uldQuery_; cliRC = cliInterface()->prepare(stmtStr, module, stmt, sql_src, input_desc, output_desc, NULL); if (cliRC < 0) { cliInterface()->retrieveSQLDiagnostics(getDiagsArea()); cliInterface()->deallocStuff(module, stmt, sql_src, input_desc, output_desc); resetExplainSettings(); return cliRC; } resetExplainSettings(); NAString qry_str = ""; qry_str = qry_str + "SELECT DISTINCT "; qry_str = qry_str + "CASE "; qry_str = qry_str + "WHEN (POSITION('full_table_name:' IN description) = 0 ) OR (POSITION('snapshot_name:' IN description) = 0) "; qry_str = qry_str + "THEN NULL "; qry_str = qry_str + "ELSE "; qry_str = qry_str + "TRIM(SUBSTRING (description from POSITION('full_table_name:' IN description) + CHAR_LENGTH('full_table_name:') "; qry_str = qry_str + "FOR POSITION('snapshot_name:' IN description) - "; qry_str = qry_str + " POSITION('full_table_name:' IN description) - CHAR_LENGTH('full_table_name:'))) "; qry_str = qry_str + "END AS full_table_name, "; qry_str = qry_str + "CASE "; qry_str = qry_str + "WHEN (POSITION('snapshot_temp_location:' IN description) = 0 ) OR ( POSITION('snapshot_name:' IN description) = 0) "; qry_str = qry_str + "THEN NULL "; qry_str = qry_str + "ELSE "; qry_str = qry_str + "TRIM(SUBSTRING (description from POSITION('snapshot_name:' IN description) + CHAR_LENGTH('snapshot_name:') "; qry_str = qry_str + " FOR POSITION('snapshot_temp_location:' IN description) - "; qry_str = qry_str + " POSITION('snapshot_name:' IN description) - CHAR_LENGTH('snapshot_name:'))) "; qry_str = qry_str + "END AS snapshot_name "; qry_str = qry_str + "FROM TABLE (EXPLAIN (NULL,'__EXPL_STMT_NAME__')) WHERE TRIM(OPERATOR) LIKE 'TRAFODION%SCAN%' ; "; Queue * tbls = NULL; cliRC = cliInterface()->fetchAllRows(tbls, (char*)qry_str.data(), 0, FALSE, FALSE, TRUE); if (cliRC < 0) { cliInterface()->retrieveSQLDiagnostics(getDiagsArea()); cliInterface()->deallocStuff(module, stmt, sql_src, input_desc, output_desc); return cliRC; } if (tbls) { if (tbls->numEntries() == 0) { cliRC = cliInterface()->deallocStuff(module, stmt, sql_src, input_desc, output_desc); if (cliRC < 0) { cliInterface()->retrieveSQLDiagnostics(getDiagsArea()); return cliRC; } } tbls->position(); for (int idx = 0; idx < tbls->numEntries(); idx++) { OutputInfo * idx = (OutputInfo*) tbls->getNext(); snapshotStruct * snap = new (getMyHeap()) snapshotStruct(); snap->fullTableName = new (getMyHeap()) NAString(idx->get(0),getMyHeap()); snap->snapshotName = new (getMyHeap()) NAString(idx->get(1),getMyHeap()); //remove trailing spaces snap->fullTableName->strip(NAString::trailing, ' '); snap->snapshotName->strip(NAString::trailing, ' '); ex_assert(snap->fullTableName->length()>0 && snap->snapshotName->length()>0 , "full table name and snapshot name cannot be empty"); snapshotsList_->insert(snap); } } cliRC = cliInterface()->deallocStuff(module, stmt, sql_src, input_desc, output_desc); if (cliRC < 0) { cliInterface()->retrieveSQLDiagnostics(getDiagsArea()); return cliRC; } return snapshotsList_->entries(); } ////////////////////////////////////////////////////// // work() for ExExeUtilHbaseLoadTcb ////////////////////////////////////////////////////// short ExExeUtilHBaseBulkUnLoadTcb::work() { Lng32 cliRC = 0; Lng32 retcode = 0; short rc; SFW_RetCode sfwRetCode = SFW_OK; Lng32 hbcRetCode = HBC_OK; // if no parent request, return if (qparent_.down->isEmpty()) return WORK_OK; // if no room in up queue, won't be able to return data/status. // Come back later. if (qparent_.up->isFull()) return WORK_OK; ex_queue_entry * pentry_down = qparent_.down->getHeadEntry(); ExExeUtilPrivateState & pstate = *((ExExeUtilPrivateState*) pentry_down->pstate); ExTransaction *ta = getGlobals()->castToExExeStmtGlobals()-> castToExMasterStmtGlobals()->getStatement()->getContext()->getTransaction(); while (1) { switch (step_) { case INITIAL_: { NABoolean xnAlreadyStarted = ta->xnInProgress(); if (xnAlreadyStarted ) { //8111 - Transactions are not allowed with Bulk unload. ComDiagsArea * da = getDiagsArea(); *da << DgSqlCode(-8111); step_ = UNLOAD_ERROR_; break; } setEmptyTarget(hblTdb().getEmptyTarget()); setOneFile(hblTdb().getOneFile()); if (!sequenceFileWriter_) { sequenceFileWriter_ = new(getMyHeap()) SequenceFileWriter((NAHeap *)getMyHeap()); sfwRetCode = sequenceFileWriter_->init(); if (sfwRetCode != SFW_OK) { createHdfsFileError(sfwRetCode); step_ = UNLOAD_END_ERROR_; break; } } if ((retcode = ehi_->init(NULL)) != HBASE_ACCESS_SUCCESS) { ExHbaseAccessTcb::setupError((NAHeap *)getMyHeap(),qparent_, retcode, "ExpHbaseInterface_JNI::init"); handleError(); step_ = UNLOAD_END_ERROR_; break; } if (!hblTdb().getOverwriteMergeFile() && hblTdb().getMergePath() != NULL) { NABoolean exists = FALSE; sfwRetCode = sequenceFileWriter_->hdfsExists( hblTdb().getMergePath(), exists); if (sfwRetCode != SFW_OK) { createHdfsFileError(sfwRetCode); step_ = UNLOAD_END_ERROR_; break; } if (exists) { //EXE_UNLOAD_FILE_EXISTS ComDiagsArea * da = getDiagsArea(); *da << DgSqlCode(- EXE_UNLOAD_FILE_EXISTS) << DgString0(hblTdb().getMergePath()); step_ = UNLOAD_END_ERROR_; break; } } if (holdAndSetCQD("COMP_BOOL_226", "ON") < 0) { step_ = UNLOAD_END_ERROR_; break; } if (holdAndSetCQD("TRAF_UNLOAD_BYPASS_LIBHDFS", "ON") < 0) { step_ = UNLOAD_END_ERROR_; break; } if (hblTdb().getSkipWriteToFiles()) { setEmptyTarget(FALSE); setOneFile(FALSE); } if (setStartStatusMsgAndMoveToUpQueue("UNLOAD", &rc)) return rc; if (hblTdb().getCompressType() == 0) cliRC = holdAndSetCQD("TRAF_UNLOAD_HDFS_COMPRESS", "0"); else cliRC = holdAndSetCQD("TRAF_UNLOAD_HDFS_COMPRESS", "1"); if (cliRC < 0) { step_ = UNLOAD_END_ERROR_; break; } if (hblTdb().getScanType()== ComTdbExeUtilHBaseBulkUnLoad::REGULAR_SCAN) cliRC = holdAndSetCQD("TRAF_TABLE_SNAPSHOT_SCAN", "NONE"); else { cliRC = holdAndSetCQD("TRAF_TABLE_SNAPSHOT_SCAN", "SUFFIX"); if (cliRC < 0) { step_ = UNLOAD_END_ERROR_; break; } } cliRC = holdAndSetCQD("TRAF_TABLE_SNAPSHOT_SCAN_TABLE_SIZE_THRESHOLD", "0"); if (cliRC < 0) { step_ = UNLOAD_END_ERROR_; break; } if (hblTdb().getSnapshotSuffix() != NULL) { cliRC = holdAndSetCQD("TRAF_TABLE_SNAPSHOT_SCAN_SNAP_SUFFIX", hblTdb().getSnapshotSuffix()); if (cliRC < 0) { step_ = UNLOAD_END_ERROR_; break; } } step_ = UNLOAD_; if (hblTdb().getScanType() == ComTdbExeUtilHBaseBulkUnLoad::SNAPSHOT_SCAN_CREATE ) step_ = CREATE_SNAPSHOTS_; else if (hblTdb().getScanType() == ComTdbExeUtilHBaseBulkUnLoad::SNAPSHOT_SCAN_EXISTING ) step_ = VERIFY_SNAPSHOTS_; if (getEmptyTarget()) step_ = EMPTY_TARGET_; } break; case EMPTY_TARGET_: { if (setStartStatusMsgAndMoveToUpQueue(" EMPTY TARGET ", &rc, 0, TRUE)) return rc; NAString uldPath ( hblTdb().getExtractLocation()); sfwRetCode = sequenceFileWriter_->hdfsCleanUnloadPath( uldPath); if (sfwRetCode != SFW_OK) { createHdfsFileError(sfwRetCode); step_ = UNLOAD_END_ERROR_; break; } step_ = UNLOAD_; if (hblTdb().getScanType() == ComTdbExeUtilHBaseBulkUnLoad::SNAPSHOT_SCAN_CREATE) //SNAPSHOT_SCAN_CREATE_ = 1 step_ = CREATE_SNAPSHOTS_; else if (hblTdb().getScanType() == ComTdbExeUtilHBaseBulkUnLoad::SNAPSHOT_SCAN_EXISTING ) step_ = VERIFY_SNAPSHOTS_; setEndStatusMsg(" EMPTY TARGET ", 0, TRUE); } break; case CREATE_SNAPSHOTS_: case VERIFY_SNAPSHOTS_: { NABoolean createSnp = (step_ == CREATE_SNAPSHOTS_)? TRUE : FALSE; NAString msg(createSnp ? " CREATE SNAPSHOTS " : " VERIFY SNAPSHOTS "); NAString msg2 (createSnp ? "created" : "verified"); if (setStartStatusMsgAndMoveToUpQueue( msg.data() , &rc, 0, TRUE)) return rc; assert (snapshotsList_ == NULL); snapshotsList_ = new (getMyHeap()) NAList<struct snapshotStruct *> (getMyHeap()); Lng32 rc = getTrafodionScanTables(); if (rc < 0) { step_ = UNLOAD_END_ERROR_; break; } for ( int i = 0 ; i < snapshotsList_->entries(); i++) { if (createSnp) hbcRetCode = ehi_->createSnapshot( *snapshotsList_->at(i)->fullTableName, *snapshotsList_->at(i)->snapshotName); else { NABoolean exist = FALSE; hbcRetCode = ehi_->verifySnapshot(*snapshotsList_->at(i)->fullTableName, *snapshotsList_->at(i)->snapshotName, exist); if ( hbcRetCode == HBC_OK && !exist) { ComDiagsArea * da = getDiagsArea(); *da << DgSqlCode(-8112) << DgString0(snapshotsList_->at(i)->snapshotName->data()) << DgString1(snapshotsList_->at(i)->fullTableName->data()); step_ = UNLOAD_END_ERROR_; break; } } if (hbcRetCode != HBC_OK) { ExHbaseAccessTcb::setupError((NAHeap *)getMyHeap(),qparent_, hbcRetCode, "HBaseClient_JNI::createSnapshot/verifySnapshot", snapshotsList_->at(i)->snapshotName->data() ); handleError(); step_ = UNLOAD_END_ERROR_; break; } } if (step_ == UNLOAD_END_ERROR_) break; step_ = UNLOAD_; sprintf(statusMsgBuf_," Snapshots %s: %d %c",msg2.data(), (int)snapshotsList_->entries(), '\n' ); int len = strlen(statusMsgBuf_); setEndStatusMsg(msg.data(), len, TRUE); } break; case UNLOAD_: { if (setStartStatusMsgAndMoveToUpQueue(" EXTRACT ", &rc, 0, TRUE)) return rc; rowsAffected_ = 0; cliRC = cliInterface()->executeImmediate(hblTdb().uldQuery_, NULL, NULL, TRUE, &rowsAffected_); if (cliRC < 0) { rowsAffected_ = 0; cliInterface()->retrieveSQLDiagnostics(getDiagsArea()); step_ = UNLOAD_END_ERROR_; break; } step_ = UNLOAD_END_; if (getOneFile()) step_ = MERGE_FILES_; if (hblTdb().getScanType() == ComTdbExeUtilHBaseBulkUnLoad::SNAPSHOT_SCAN_CREATE ) step_ = DELETE_SNAPSHOTS_; if (hblTdb().getSkipWriteToFiles()) sprintf(statusMsgBuf_," Rows Processed but NOT Written to Disk: %ld %c",rowsAffected_, '\n' ); else sprintf(statusMsgBuf_," Rows Processed: %ld %c",rowsAffected_, '\n' ); int len = strlen(statusMsgBuf_); setEndStatusMsg(" EXTRACT ", len, TRUE); } break; case DELETE_SNAPSHOTS_: { if (setStartStatusMsgAndMoveToUpQueue(" DELETE SNAPSHOTS ", &rc, 0, TRUE)) return rc; for ( int i = 0 ; i < snapshotsList_->entries(); i++) { hbcRetCode = ehi_->deleteSnapshot( *snapshotsList_->at(i)->snapshotName); if (hbcRetCode != HBC_OK) { ExHbaseAccessTcb::setupError((NAHeap *)getMyHeap(),qparent_, hbcRetCode, "HBaseClient_JNI::createSnapshot/verifySnapshot", snapshotsList_->at(i)->snapshotName->data() ); handleError(); step_ = UNLOAD_END_ERROR_; break; } } if (step_ == UNLOAD_END_ERROR_) break; step_ = UNLOAD_END_; if (getOneFile()) step_ = MERGE_FILES_; sprintf(statusMsgBuf_," Snapshots deleted: %d %c",(int)snapshotsList_->entries(), '\n' ); int len = strlen(statusMsgBuf_); setEndStatusMsg(" DELETE SNAPSHOTS ", len, TRUE); } break; case MERGE_FILES_: { if (setStartStatusMsgAndMoveToUpQueue(" MERGE FILES ", &rc, 0, TRUE)) return rc; NAString srcPath ( hblTdb().getExtractLocation()); NAString dstPath ( hblTdb().getMergePath()); sfwRetCode = sequenceFileWriter_->hdfsMergeFiles( srcPath, dstPath); if (sfwRetCode != SFW_OK) { createHdfsFileError(sfwRetCode); step_ = UNLOAD_END_; break; } step_ = UNLOAD_END_; setEndStatusMsg(" MERGE FILES ", 0, TRUE); } break; case UNLOAD_END_: case UNLOAD_END_ERROR_: { ehi_->close(); if (restoreCQD("TRAF_TABLE_SNAPSHOT_SCAN") < 0) { step_ = UNLOAD_ERROR_; break; } if (restoreCQD("TRAF_TABLE_SNAPSHOT_SCAN_TABLE_SIZE_THRESHOLD") < 0) { step_ = UNLOAD_ERROR_; break; } if (hblTdb().getSnapshotSuffix() != NULL) { if (restoreCQD("TRAF_TABLE_SNAPSHOT_SCAN_SNAP_SUFFIX") < 0) { step_ = UNLOAD_ERROR_; break; } } if (restoreCQD("COMP_BOOL_226") < 0) { step_ = UNLOAD_ERROR_; break; } if (restoreCQD("TRAF_UNLOAD_BYPASS_LIBHDFS") < 0) { step_ = UNLOAD_ERROR_; break; } if ( restoreCQD("TRAF_UNLOAD_HDFS_COMPRESS") < 0) { step_ = UNLOAD_ERROR_; break; } if (step_ == UNLOAD_END_) step_ = DONE_; else step_ = UNLOAD_ERROR_; } break; case RETURN_STATUS_MSG_: { if (moveRowToUpQueue(statusMsgBuf_,0,&rc)) return rc; step_ = nextStep_; } break; case DONE_: { if (qparent_.up->isFull()) return WORK_OK; // Return EOF. ex_queue_entry * up_entry = qparent_.up->getTailEntry(); up_entry->upState.parentIndex = pentry_down->downState.parentIndex; up_entry->upState.setMatchNo(0); up_entry->upState.status = ex_queue::Q_NO_DATA; ComDiagsArea *diagsArea = up_entry->getDiagsArea(); if (diagsArea == NULL) diagsArea = ComDiagsArea::allocate(getMyHeap()); else diagsArea->incrRefCount(); // setDiagsArea call below will decr ref count diagsArea->setRowCount(rowsAffected_); if (getDiagsArea()) diagsArea->mergeAfter(*getDiagsArea()); up_entry->setDiagsArea(diagsArea); // insert into parent qparent_.up->insert(); step_ = INITIAL_; qparent_.down->removeHead(); freeResources(); return WORK_OK; } break; case UNLOAD_ERROR_: { if (qparent_.up->isFull()) return WORK_OK; // Return EOF. ex_queue_entry * up_entry = qparent_.up->getTailEntry(); up_entry->upState.parentIndex = pentry_down->downState.parentIndex; up_entry->upState.setMatchNo(0); up_entry->upState.status = ex_queue::Q_SQLERROR; ComDiagsArea *diagsArea = up_entry->getDiagsArea(); if (diagsArea == NULL) diagsArea = ComDiagsArea::allocate(getMyHeap()); else diagsArea->incrRefCount(); // setDiagsArea call below will decr ref count if (getDiagsArea()) diagsArea->mergeAfter(*getDiagsArea()); up_entry->setDiagsArea(diagsArea); // insert into parent qparent_.up->insert(); pstate.matches_ = 0; step_ = DONE_; } break; } // switch } // while return WORK_OK; } short ExExeUtilHBaseBulkUnLoadTcb::moveRowToUpQueue(const char * row, Lng32 len, short * rc, NABoolean isVarchar) { if (hblTdb().getNoOutput()) return 0; return ExExeUtilTcb::moveRowToUpQueue(row, len, rc, isVarchar); } short ExExeUtilHBaseBulkUnLoadTcb::setStartStatusMsgAndMoveToUpQueue(const char * operation, short * rc, int bufPos, NABoolean withtime) { if (hblTdb().getNoOutput()) return 0; char timeBuf[200]; if (withtime) { startTime_ = NA_JulianTimestamp(); getTimestampAsString(startTime_, timeBuf); } getStatusString(operation, "Started",NULL, &statusMsgBuf_[bufPos], FALSE, (withtime ? timeBuf : NULL)); return moveRowToUpQueue(statusMsgBuf_,0,rc); } void ExExeUtilHBaseBulkUnLoadTcb::setEndStatusMsg(const char * operation, int bufPos, NABoolean withtime) { if (hblTdb().getNoOutput()) return ; char timeBuf[200]; nextStep_ = step_; step_ = RETURN_STATUS_MSG_; if (withtime) { endTime_ = NA_JulianTimestamp(); Int64 elapsedTime = endTime_ - startTime_; getTimestampAsString(endTime_, timeBuf); getStatusString(operation, "Ended", hblTdb().getTableName(),&statusMsgBuf_[bufPos], FALSE, withtime ? timeBuf : NULL); bufPos = strlen(statusMsgBuf_); statusMsgBuf_[bufPos] = '\n'; bufPos++; getTimeAsString(elapsedTime, timeBuf); } getStatusString(operation, "Ended", NULL,&statusMsgBuf_[bufPos], TRUE, withtime ? timeBuf : NULL); } //////////////////////////////////////////////////////////////////////// // Redefine virtual method allocatePstates, to be used by dynamic queue // resizing, as well as the initial queue construction. //////////////////////////////////////////////////////////////////////// ex_tcb_private_state * ExExeUtilHBaseBulkUnLoadTcb::allocatePstates( Lng32 &numElems, // inout, desired/actual elements Lng32 &pstateLength) // out, length of one element { PstateAllocator<ExExeUtilHbaseUnLoadPrivateState> pa; return pa.allocatePstates(this, numElems, pstateLength); } ///////////////////////////////////////////////////////////////////////////// // Constructor and destructor for ExeUtil_private_state ///////////////////////////////////////////////////////////////////////////// ExExeUtilHbaseUnLoadPrivateState::ExExeUtilHbaseUnLoadPrivateState() { } ExExeUtilHbaseUnLoadPrivateState::~ExExeUtilHbaseUnLoadPrivateState() { }; /////////////////////////////////////////////////////////////////// // class ExExeUtilLobExtractTdb /////////////////////////////////////////////////////////////// ex_tcb * ExExeUtilLobExtractTdb::build(ex_globals * glob) { ExExeUtilLobExtractTcb * exe_util_tcb; ex_tcb * childTcb = NULL; if (child_) { // build the child first childTcb = child_->build(glob); } if ((getToType() == ComTdbExeUtilLobExtract::TO_EXTERNAL_FROM_STRING_) || (getToType() == ComTdbExeUtilLobExtract::TO_EXTERNAL_FROM_FILE_)) exe_util_tcb = new(glob->getSpace()) ExExeUtilFileLoadTcb(*this, childTcb, glob); else if (srcIsFile()) exe_util_tcb = new(glob->getSpace()) ExExeUtilFileExtractTcb(*this, childTcb, glob); else exe_util_tcb = new(glob->getSpace()) ExExeUtilLobExtractTcb(*this, childTcb, glob); exe_util_tcb->registerSubtasks(); return (exe_util_tcb); } ExExeUtilLobExtractTcb::ExExeUtilLobExtractTcb ( const ComTdbExeUtilLobExtract & exe_util_tdb, const ex_tcb * child_tcb, ex_globals * glob) : ExExeUtilTcb(exe_util_tdb, child_tcb, glob), step_(EMPTY_) { ContextCli *currContext = getGlobals()->castToExExeStmtGlobals()->castToExMasterStmtGlobals()-> getStatement()->getContext(); lobHandleLen_ = 2050; lobHandle_ = {0}; lobInputHandleBuf_={0}; lobNameBuf_= {0}; lobNameLen_ =1024; lobName_ = NULL; statusString_ = {0}; lobType_ = 0; lobData_= NULL; lobData2_= NULL; lobDataSpecifiedExtractLen_ = 0; // default. Actual value set from tdb below lobDataLen_= 0; remainingBytes_= 0; currPos_ = 0; numChildRows_ = 0; requestTag_ = -1; lobLoc_ = {0}; lobGlobals_ = new(currContext->exHeap()) LOBglobals(currContext->exHeap()); ExpLOBoper::initLOBglobal (lobGlobals_->lobAccessGlobals(), currContext->exHeap(),currContext,lobTdb().getLobHdfsServer(), lobTdb().getLobHdfsPort()); } short ExExeUtilLobExtractTcb::work() { Lng32 cliRC = 0; Lng32 retcode = 0; Int64 lobDataOutputLen = 0; Int64 requestTag = -1; LobsSubOper so; // if no parent request, return if (qparent_.down->isEmpty()) return WORK_OK; ex_queue_entry * pentry_down = qparent_.down->getHeadEntry(); ExExeUtilPrivateState & pstate = *((ExExeUtilPrivateState*) pentry_down->pstate); ContextCli *currContext = getGlobals()->castToExExeStmtGlobals()->castToExMasterStmtGlobals()-> getStatement()->getContext(); ComDiagsArea & diags = currContext->diags(); void * lobGlobs = getLobGlobals()->lobAccessGlobals(); ex_queue_entry * centry = NULL; while (1) { switch (step_) { case EMPTY_: { workAtp_->getTupp(lobTdb().workAtpIndex()) .setDataPointer(lobInputHandleBuf_); if (getChild(0)) step_ = SEND_REQ_TO_CHILD_; else step_ = GET_NO_CHILD_HANDLE_; } break; case GET_NO_CHILD_HANDLE_: { ex_expr::exp_return_type exprRetCode = lobTdb().inputExpr_->eval(NULL, workAtp_); if (exprRetCode == ex_expr::EXPR_ERROR) { step_ = CANCEL_; break; } step_ = GET_LOB_HANDLE_; } break; case SEND_REQ_TO_CHILD_: { if (qchild_.down->isFull()) return WORK_OK; ex_queue_entry * centry = qchild_.down->getTailEntry(); centry->downState.request = ex_queue::GET_ALL; centry->downState.requestValue = pentry_down->downState.requestValue; centry->downState.parentIndex = qparent_.down->getHeadIndex(); // set the child's input atp centry->passAtp(pentry_down->getAtp()); qchild_.down->insert(); numChildRows_ = 0; step_ = GET_REPLY_FROM_CHILD_; } break; case GET_REPLY_FROM_CHILD_: { // if nothing returned from child. Get outta here. if (qchild_.up->isEmpty()) return WORK_OK; // check if we've got room in the up queue if (qparent_.up->isFull()) return WORK_OK; // parent queue is full. Just return centry = qchild_.up->getHeadEntry(); ex_queue::up_status child_status = centry->upState.status; switch(child_status) { case ex_queue::Q_NO_DATA: { qchild_.up->removeHead(); if (numChildRows_ == 0) step_ = DONE_; else if (numChildRows_ == 1) step_ = GET_LOB_HANDLE_; else { Lng32 cliError = 0; Lng32 intParam1 = 0; ComDiagsArea * diagsArea = getDiagsArea(); ExRaiseSqlError(getHeap(), &diagsArea, (ExeErrorCode)(8444), NULL, &intParam1, &cliError, NULL, NULL); step_ = HANDLE_ERROR_; } } break; case ex_queue::Q_OK_MMORE: { if (numChildRows_ == 0) // first child row { ex_expr::exp_return_type exprRetCode = lobTdb().inputExpr_->eval(centry->getAtp(), workAtp_); if (exprRetCode == ex_expr::EXPR_ERROR) { step_ = CANCEL_; break; } } qchild_.up->removeHead(); numChildRows_++; // step_ = GET_LOB_HANDLE_; } break; case ex_queue::Q_INVALID: { ex_queue_entry * up_entry = qparent_.up->getTailEntry(); // invalid state, should not be reached. ComDiagsArea * da = up_entry->getDiagsArea(); ExRaiseSqlError(getMyHeap(), &da, (ExeErrorCode)(EXE_INTERNAL_ERROR)); step_ = CANCEL_; } break; case ex_queue::Q_SQLERROR: { step_ = ERROR_FROM_CHILD_; } break; } } break; case ERROR_FROM_CHILD_: { // check if we've got room in the up queue if (qparent_.up->isFull()) return WORK_OK; // parent queue is full. Just return ex_queue_entry *pentry_up = qparent_.up->getTailEntry(); ex_queue_entry * centry = qchild_.up->getHeadEntry(); qchild_.down->cancelRequestWithParentIndex(qparent_.down->getHeadIndex()); pentry_up->copyAtp(centry); pentry_up->upState.status = ex_queue::Q_SQLERROR; pentry_up->upState.parentIndex = pentry_down->downState.parentIndex; pentry_up->upState.downIndex = qparent_.down->getHeadIndex(); qparent_.up->insert(); qchild_.up->removeHead(); step_ = CANCEL_; } break; case CANCEL_: { // ignore all up rows from child. wait for Q_NO_DATA. if (qchild_.up->isEmpty()) return WORK_OK; ex_queue_entry * centry = qchild_.up->getHeadEntry(); switch(centry->upState.status) { case ex_queue::Q_OK_MMORE: case ex_queue::Q_SQLERROR: case ex_queue::Q_INVALID: { qchild_.up->removeHead(); } break; case ex_queue::Q_NO_DATA: { qchild_.up->removeHead(); step_ = HANDLE_ERROR_; } break; } } break; case GET_LOB_HANDLE_: { if (lobTdb().handleInStringFormat()) { if (ExpLOBoper::genLOBhandleFromHandleString (lobTdb().getHandle(), lobTdb().getHandleLen(), lobHandle_, lobHandleLen_)) { ComDiagsArea * da = getDiagsArea(); ExRaiseSqlError(getMyHeap(), &da, (ExeErrorCode)(EXE_INVALID_LOB_HANDLE)); step_ = HANDLE_ERROR_; break; } } else { lobHandleLen_ = *(short*)&lobInputHandleBuf_[sizeof(short)]; //lobTdb().getHandleLen(); str_cpy_all(lobHandle_, &lobInputHandleBuf_[sizeof(short)], lobHandleLen_); //lobTdb().getHandle(); if (*(short*)lobInputHandleBuf_ != 0) //null value { step_ = DONE_; break; } } if (lobTdb().getToType() == ComTdbExeUtilLobExtract::TO_BUFFER_) step_ = EXTRACT_LOB_DATA_; else if ((lobTdb().getToType() == ComTdbExeUtilLobExtract::RETRIEVE_LENGTH_) || (lobTdb().getToType() == ComTdbExeUtilLobExtract::TO_FILE_)) step_ = RETRIEVE_LOB_LENGTH_; else { // invalid "toType" ex_queue_entry * up_entry = qparent_.up->getTailEntry(); ComDiagsArea * da = up_entry->getDiagsArea(); ExRaiseSqlError(getMyHeap(), &da, (ExeErrorCode)(EXE_INTERNAL_ERROR)); step_ = CANCEL_; break; } break; } case RETRIEVE_LOB_LENGTH_ : { Int16 flags; Lng32 lobNum; Int64 uid, inDescSyskey, descPartnKey; short schNameLen; char schName[1024]; ExpLOBoper::extractFromLOBhandle(&flags, &lobType_, &lobNum, &uid, &inDescSyskey, &descPartnKey, &schNameLen, (char *)schName, (char *)lobHandle_, (Lng32)lobHandleLen_); //Retrieve the total length of this lob using the handle info and return to the caller Int64 dummy = 0; cliRC = SQL_EXEC_LOBcliInterface(lobHandle_, lobHandleLen_,NULL,NULL,NULL,NULL,LOB_CLI_SELECT_LOBLENGTH,LOB_CLI_ExecImmed, 0,&lobDataLen_, &dummy, &dummy,0,0,FALSE); if (cliRC < 0) { getDiagsArea()->mergeAfter(diags); step_ = HANDLE_ERROR_; break; } if (lobTdb().retrieveLength()) { if ((lobTdb().getBufAddr() != -1) && (lobTdb().getBufAddr() != 0)) str_cpy_all((char *)lobTdb().getBufAddr(), (char *)&lobDataLen_,sizeof(Int64)); str_sprintf(statusString_," LOB Length : %d", lobDataLen_); step_ = RETURN_STATUS_; break; } else step_ = EXTRACT_LOB_DATA_; break; } case EXTRACT_LOB_DATA_ : { Int16 flags; Lng32 lobNum; Int64 uid, inDescSyskey, descPartnKey; short schNameLen; char schName[1024]; ExpLOBoper::extractFromLOBhandle(&flags, &lobType_, &lobNum, &uid, &inDescSyskey, &descPartnKey, &schNameLen, (char *)schName, (char *)lobHandle_, (Lng32)lobHandleLen_); lobName_ = ExpLOBoper::ExpGetLOBname(uid, lobNum, lobNameBuf_, 1000); lobDataSpecifiedExtractLen_ = lobTdb().totalBufSize_; short *lobNumList = new (getHeap()) short[1]; short *lobTypList = new (getHeap()) short[1]; char **lobLocList = new (getHeap()) char*[1]; char **lobColNameList = new (getHeap()) char*[1]; lobLocList[0] = new (getHeap()) char[1024]; lobColNameList[0] = new (getHeap()) char[256]; Lng32 numLobs = lobNum; Lng32 cliRC = SQL_EXEC_LOBddlInterface ( schName, schNameLen, uid, numLobs, LOB_CLI_SELECT_UNIQUE, lobNumList, lobTypList, lobLocList,lobColNameList,lobTdb().getLobHdfsServer(), lobTdb().getLobHdfsPort(),0,FALSE); if (cliRC < 0) { getDiagsArea()->mergeAfter(diags); step_ = HANDLE_ERROR_; break; } strcpy(lobLoc_, lobLocList[0]); // Read the lob contents into target file if (lobTdb().getToType() == ComTdbExeUtilLobExtract::TO_FILE_) { so = Lob_File; LobTgtFileFlags tgtFlags = Lob_Error_Or_Create; if (lobTdb().errorIfNotExists() && !lobTdb().truncateExisting()) tgtFlags = Lob_Append_Or_Error; if (lobTdb().truncateExisting() &&lobTdb().errorIfNotExists() ) tgtFlags = Lob_Truncate_Or_Error; if (lobTdb().truncateExisting() && !lobTdb().errorIfNotExists()) tgtFlags = Lob_Truncate_Or_Create; if(lobTdb().appendOrCreate()) tgtFlags = Lob_Append_Or_Create; retcode = ExpLOBInterfaceSelect(lobGlobs, lobName_, lobLoc_, lobType_, lobTdb().getLobHdfsServer(), lobTdb().getLobHdfsPort(), lobHandleLen_, lobHandle_, requestTag, so, ((LOBglobals *)lobGlobs)->xnId(), 0,0, 0, lobDataLen_, lobDataOutputLen, lobTdb().getFileName(), lobDataSpecifiedExtractLen_, (Int32)tgtFlags ); if (retcode <0) { Lng32 intParam1 = -retcode; Lng32 cliError; ComDiagsArea * diagsArea = getDiagsArea(); ExRaiseSqlError(getHeap(), &diagsArea, (ExeErrorCode)(8442), NULL, &intParam1, &cliError, NULL, (char*)"ExpLOBInterfaceSelect", getLobErrStr(intParam1)); step_ = HANDLE_ERROR_; break; } str_sprintf(statusString_, "Success. Targetfile :%s Length : %Ld", lobTdb().getFileName(), lobDataOutputLen); step_ = RETURN_STATUS_; } else if (lobTdb().getToType() == ComTdbExeUtilLobExtract::TO_BUFFER_) { so = Lob_Buffer; lobData_ = (char *)lobTdb().getBufAddr(); lobDataSpecifiedExtractLen_ = *((Int64 *)(lobTdb().dataExtractSizeIOAddr())); step_ = OPEN_CURSOR_; } } break; case OPEN_CURSOR_: { retcode = ExpLOBInterfaceSelectCursor (lobGlobs, lobName_, lobLoc_, lobType_, lobTdb().getLobHdfsServer(), lobTdb().getLobHdfsPort(), lobHandleLen_, lobHandle_, 0, // cursor bytes NULL, //cursor id requestTag_, Lob_Buffer, 0, // not check status 1, // waited op 0, lobDataSpecifiedExtractLen_, lobDataOutputLen, lobData_, 1, // open 2); // must open if (retcode < 0) { Lng32 cliError = 0; Lng32 intParam1 = -retcode; ComDiagsArea * diagsArea = getDiagsArea(); ExRaiseSqlError(getHeap(), &diagsArea, (ExeErrorCode)(8442), NULL, &intParam1, &cliError, NULL, (char*)"ExpLOBInterfaceSelectCursor", getLobErrStr(intParam1)); step_ = HANDLE_ERROR_; break; } step_ = READ_CURSOR_; } break; case READ_CURSOR_: { if (lobTdb().getToType() == ComTdbExeUtilLobExtract::TO_BUFFER_) so = Lob_Buffer; lobDataSpecifiedExtractLen_ = *((Int64 *)(lobTdb().dataExtractSizeIOAddr())); retcode = ExpLOBInterfaceSelectCursor (lobGlobs, lobName_, lobLoc_, lobType_, lobTdb().getLobHdfsServer(), lobTdb().getLobHdfsPort(), lobHandleLen_, lobHandle_, 0 , //cursor bytes, NULL, //cursor id requestTag_, so, 0, // not check status 1, // waited op 0, lobDataSpecifiedExtractLen_, //lobDataLen_, lobData_, lobDataOutputLen, lobData_, 2, // read 0); // open type not applicable if (retcode < 0) { Lng32 cliError = 0; Lng32 intParam1 = -retcode; ComDiagsArea * diagsArea = getDiagsArea(); ExRaiseSqlError(getHeap(), &diagsArea, (ExeErrorCode)(8442), NULL, &intParam1, &cliError, NULL, (char*)"ExpLOBInterfaceSelectCursor", getLobErrStr(intParam1)); step_ = HANDLE_ERROR_; break; } if (lobDataOutputLen == 0) { step_ = CLOSE_CURSOR_; break; } remainingBytes_ = (Lng32)lobDataOutputLen; currPos_ = 0; if (lobTdb().getToType() == ComTdbExeUtilLobExtract::TO_BUFFER_) { str_sprintf(statusString_," Success: LOB data length returned : %d", lobDataOutputLen); //lobTdb().setExtractSizeIOAddr((Int64)(&lobDataOutputLen)); memcpy((char *)lobTdb().dataExtractSizeIOAddr(), (char *)&lobDataOutputLen,sizeof(Int64)); step_ = RETURN_STATUS_; } else { // No other "toType" shoudl reach here - i.e TO_FILE_ or TO_STRING ex_queue_entry * up_entry = qparent_.up->getTailEntry(); ComDiagsArea * da = up_entry->getDiagsArea(); ExRaiseSqlError(getMyHeap(), &da, (ExeErrorCode)(EXE_INTERNAL_ERROR)); step_ = CANCEL_; break; } } break; case CLOSE_CURSOR_: { retcode = ExpLOBInterfaceSelectCursor (lobGlobs, lobName_, lobLoc_, lobType_, lobTdb().getLobHdfsServer(), lobTdb().getLobHdfsPort(), lobHandleLen_, lobHandle_, 0, //cursor bytes NULL, //cursor id requestTag_, so, 0, // not check status 1, // waited op 0, lobDataSpecifiedExtractLen_, lobDataLen_, lobData_, 3, // close 0); // open type not applicable if (retcode < 0) { Lng32 cliError = 0; Lng32 intParam1 = -retcode; ComDiagsArea * diagsArea = getDiagsArea(); ExRaiseSqlError(getHeap(), &diagsArea, (ExeErrorCode)(8442), NULL, &intParam1, &cliError, NULL, (char*)"ExpLOBInterfaceSelectCursor", getLobErrStr(intParam1)); step_ = HANDLE_ERROR_; break; } step_ = DONE_; } break; case RETURN_STRING_: { if (qparent_.up->isFull()) return WORK_OK; Lng32 size = MINOF((Lng32)lobTdb().dataExtractSizeIOAddr(), (Lng32)remainingBytes_); moveRowToUpQueue(&lobData_[currPos_], size); remainingBytes_ -= size; currPos_ += size; if (remainingBytes_ <= 0) { step_ = READ_CURSOR_; qparent_.down->removeHead(); } return WORK_RESCHEDULE_AND_RETURN; } break; case RETURN_STATUS_: { if (qparent_.up->isFull()) return WORK_OK; //Return to upqueue whatever is in the lobStatusMsg_ data member short rc; moveRowToUpQueue(statusString_, 200, &rc); if ((so == Lob_Buffer) && (remainingBytes_ >= 0)) { step_ = READ_CURSOR_; qparent_.down->removeHead(); return WORK_RESCHEDULE_AND_RETURN; } else step_ = DONE_ ; } break; case HANDLE_ERROR_: { retcode = handleError(); if (retcode == 1) return WORK_OK; step_ = DONE_; } break; case DONE_: { retcode = handleDone(); if (retcode == 1) return WORK_OK; step_ = EMPTY_; return WORK_OK; } break; } // switch } return 0; } ExExeUtilFileExtractTcb::ExExeUtilFileExtractTcb ( const ComTdbExeUtilLobExtract & exe_util_tdb, const ex_tcb * child_tcb, ex_globals * glob) : ExExeUtilLobExtractTcb(exe_util_tdb, child_tcb, glob) { } /////////////////////////////////////////////////////////////////// // class ExExeUtilLobUpdateTdb /////////////////////////////////////////////////////////////// ex_tcb * ExExeUtilLobUpdateTdb::build(ex_globals * glob) { ExExeUtilLobUpdateTcb * exe_util_lobupdate_tcb; ex_tcb * childTcb = NULL; if (child_) { // build the child first childTcb = child_->build(glob); } if (getFromType() == ComTdbExeUtilLobUpdate::FROM_BUFFER_) exe_util_lobupdate_tcb = new(glob->getSpace()) ExExeUtilLobUpdateTcb(*this, childTcb, glob); else { ex_assert(TRUE,"Only buffer input supported"); } exe_util_lobupdate_tcb->registerSubtasks(); return (exe_util_lobupdate_tcb); } ExExeUtilLobUpdateTcb::ExExeUtilLobUpdateTcb ( const ComTdbExeUtilLobUpdate & exe_util_lobupdate_tdb, const ex_tcb * child_tcb, ex_globals * glob) : ExExeUtilTcb(exe_util_lobupdate_tdb, child_tcb, glob), step_(EMPTY_) { ContextCli *currContext = getGlobals()->castToExExeStmtGlobals()->castToExMasterStmtGlobals()-> getStatement()->getContext(); lobHandleLen_ = 2050; lobHandle_ = {0}; lobGlobals_ = new(currContext->exHeap()) LOBglobals(currContext->exHeap()); ExpLOBoper::initLOBglobal (lobGlobals_->lobAccessGlobals(), currContext->exHeap(),currContext,lobTdb().getLobHdfsServer(), lobTdb().getLobHdfsPort()); } short ExExeUtilLobUpdateTcb::work() { Lng32 cliRC = 0; Lng32 retcode = 0; // if no parent request, return if (qparent_.down->isEmpty()) return WORK_OK; ex_queue_entry * pentry_down = qparent_.down->getHeadEntry(); ExExeUtilPrivateState & pstate = *((ExExeUtilPrivateState*) pentry_down->pstate); ContextCli *currContext = getGlobals()->castToExExeStmtGlobals()->castToExMasterStmtGlobals()-> getStatement()->getContext(); ComDiagsArea & diags = currContext->diags(); LobsSubOper so = Lob_None; if (lobTdb().getFromType() == ComTdbExeUtilLobUpdate::FROM_STRING_) so = Lob_Memory; else if (lobTdb().getFromType() == ComTdbExeUtilLobUpdate::FROM_EXTERNAL_) so = Lob_External; else if (lobTdb().getFromType() == ComTdbExeUtilLobUpdate::FROM_BUFFER_) //Only this is supported so= Lob_Buffer; Int64 lobLen = lobTdb().updateSize(); char * data = (char *)(lobTdb().getBufAddr()); void * lobGlobs = getLobGlobals()->lobAccessGlobals(); while (1) { switch (step_) { case EMPTY_: { workAtp_->getTupp(lobTdb().workAtpIndex()) .setDataPointer(lobInputHandleBuf_); step_ = GET_HANDLE_; break; } break; case GET_HANDLE_: { ex_expr::exp_return_type exprRetCode = lobTdb().inputExpr_->eval(NULL, workAtp_); if (exprRetCode == ex_expr::EXPR_ERROR) { step_ = CANCEL_; break; } if (ExpLOBoper::genLOBhandleFromHandleString (lobTdb().getHandle(), lobTdb().getHandleLen(), lobHandle_, lobHandleLen_)) { ComDiagsArea * da = getDiagsArea(); ExRaiseSqlError(getMyHeap(), &da, (ExeErrorCode)(EXE_INVALID_LOB_HANDLE)); step_ = HANDLE_ERROR_; break; } if (lobTdb().getFromType() == ComTdbExeUtilLobUpdate::FROM_BUFFER_) { if (lobTdb().isTruncate()) step_ = EMPTY_LOB_DATA_; else if (lobTdb().isReplace()) step_ = UPDATE_LOB_DATA_; else if(lobTdb().isAppend()) step_ = APPEND_LOB_DATA_; } else { // invalid "fromType" ex_queue_entry * up_entry = qparent_.up->getTailEntry(); ComDiagsArea * da = up_entry->getDiagsArea(); ExRaiseSqlError(getMyHeap(), &da, (ExeErrorCode)(EXE_INTERNAL_ERROR)); step_ = CANCEL_; break; } } break; case UPDATE_LOB_DATA_: { Int32 retcode = 0; Int16 flags; Lng32 lobNum; Int64 uid, inDescSyskey, descPartnKey; short schNameLen; char schName[1024]; Int64 dummy = 0; ExpLOBoper::extractFromLOBhandle(&flags, &lobType_, &lobNum, &uid, &inDescSyskey, &descPartnKey, &schNameLen, (char *)schName, (char *)lobHandle_, (Lng32)lobHandleLen_); lobName_ = ExpLOBoper::ExpGetLOBname(uid, lobNum, lobNameBuf_, 1000); lobDataLen_ = lobTdb().totalBufSize_; short *lobNumList = new (getHeap()) short[1]; short *lobTypList = new (getHeap()) short[1]; char **lobLocList = new (getHeap()) char*[1]; char **lobColNameList = new (getHeap()) char*[1]; lobLocList[0] = new (getHeap()) char[1024]; lobColNameList[0] = new (getHeap()) char[256]; Lng32 numLobs = lobNum; Lng32 cliRC = SQL_EXEC_LOBddlInterface ( schName, schNameLen, uid, numLobs, LOB_CLI_SELECT_UNIQUE, lobNumList, lobTypList, lobLocList,lobColNameList,lobTdb().getLobHdfsServer(), lobTdb().getLobHdfsPort(),0,FALSE); if (cliRC < 0) { getDiagsArea()->mergeAfter(diags); step_ = HANDLE_ERROR_; break; } strcpy(lobLoc_, lobLocList[0]); char outLobHandle[LOB_HANDLE_LEN]; Int32 outHandleLen; Int64 requestTag = 0; retcode = ExpLOBInterfaceUpdate(lobGlobs, lobTdb().getLobHdfsServer(), lobTdb().getLobHdfsPort(), lobName_, lobLoc_, lobHandleLen_, lobHandle_, &outHandleLen, outLobHandle, requestTag, getLobGlobals()->xnId(), 0, 1, so, inDescSyskey, lobLen, data, lobName_, schNameLen, schName, dummy, dummy, lobTdb().getLobMaxSize(), lobTdb().getLobMaxChunkSize(), lobTdb().getLobGCLimit()); if (retcode < 0) { Lng32 cliError = 0; Lng32 intParam1 = -retcode; ComDiagsArea * diagsArea = getDiagsArea(); ExRaiseSqlError(getHeap(), &diagsArea, (ExeErrorCode)(8442), NULL, &intParam1, &cliError, NULL, (char*)"ExpLOBInterfaceUpdate", getLobErrStr(intParam1)); step_ = HANDLE_ERROR_; break; } if (so == Lob_Buffer) { str_sprintf(statusString_," Updated/Replaced %d bytes of LOB data ", lobLen); step_ = RETURN_STATUS_; } break; } break; case APPEND_LOB_DATA_: { Int32 retcode = 0; Int16 flags; Lng32 lobNum; Int64 uid, inDescSyskey, descPartnKey; short schNameLen; char schName[1024]; Int64 dummy = 0; ExpLOBoper::extractFromLOBhandle(&flags, &lobType_, &lobNum, &uid, &inDescSyskey, &descPartnKey, &schNameLen, (char *)schName, (char *)lobHandle_, (Lng32)lobHandleLen_); lobName_ = ExpLOBoper::ExpGetLOBname(uid, lobNum, lobNameBuf_, 1000); lobDataLen_ = lobTdb().totalBufSize_; short *lobNumList = new (getHeap()) short[1]; short *lobTypList = new (getHeap()) short[1]; char **lobLocList = new (getHeap()) char*[1]; char **lobColNameList = new (getHeap()) char*[1]; lobLocList[0] = new (getHeap()) char[1024]; lobColNameList[0] = new (getHeap()) char[256]; Lng32 numLobs = lobNum; Lng32 cliRC = SQL_EXEC_LOBddlInterface ( schName, schNameLen, uid, numLobs, LOB_CLI_SELECT_UNIQUE, lobNumList, lobTypList, lobLocList,lobColNameList,lobTdb().getLobHdfsServer(), lobTdb().getLobHdfsPort(),0,FALSE); if (cliRC < 0) { getDiagsArea()->mergeAfter(diags); step_ = HANDLE_ERROR_; break; } strcpy(lobLoc_, lobLocList[0]); char outLobHandle[LOB_HANDLE_LEN]; Int32 outHandleLen; Int64 requestTag = 0; retcode = ExpLOBInterfaceUpdateAppend(lobGlobs, lobTdb().getLobHdfsServer(), lobTdb().getLobHdfsPort(), lobName_, lobLoc_, lobHandleLen_, lobHandle_, &outHandleLen, outLobHandle, requestTag, getLobGlobals()->xnId(), 0, 1, so, inDescSyskey, lobLen, data, lobName_, schNameLen, schName, dummy, dummy, lobTdb().getLobMaxSize(), lobTdb().getLobMaxChunkSize(), lobTdb().getLobGCLimit()); if (retcode < 0) { Lng32 cliError = 0; Lng32 intParam1 = -retcode; ComDiagsArea * diagsArea = getDiagsArea(); ExRaiseSqlError(getHeap(), &diagsArea, (ExeErrorCode)(8442), NULL, &intParam1, &cliError, NULL, (char*)"ExpLOBInterfaceUpdate", getLobErrStr(intParam1)); step_ = HANDLE_ERROR_; break; } if (so == Lob_Buffer) { str_sprintf(statusString_," Updated/Appended %d bytes of LOB data ", lobLen); step_ = RETURN_STATUS_; } break; } break; case EMPTY_LOB_DATA_: { Int32 retcode = 0; Int16 flags; Lng32 lobNum; Int64 uid, inDescSyskey, descPartnKey; short schNameLen; char schName[1024]; Int64 dummy = 0; ExpLOBoper::extractFromLOBhandle(&flags, &lobType_, &lobNum, &uid, &inDescSyskey, &descPartnKey, &schNameLen, (char *)schName, (char *)lobHandle_, (Lng32)lobHandleLen_); lobName_ = ExpLOBoper::ExpGetLOBname(uid, lobNum, lobNameBuf_, 1000); lobDataLen_ = lobTdb().totalBufSize_; short *lobNumList = new (getHeap()) short[1]; short *lobTypList = new (getHeap()) short[1]; char **lobLocList = new (getHeap()) char*[1]; char **lobColNameList = new (getHeap()) char*[1]; lobLocList[0] = new (getHeap()) char[1024]; lobColNameList[0] = new (getHeap()) char[256]; Lng32 numLobs = lobNum; Lng32 cliRC = SQL_EXEC_LOBddlInterface ( schName, schNameLen, uid, numLobs, LOB_CLI_SELECT_UNIQUE, lobNumList, lobTypList, lobLocList,lobColNameList,lobTdb().getLobHdfsServer(), lobTdb().getLobHdfsPort(),0,FALSE); if (cliRC < 0) { getDiagsArea()->mergeAfter(diags); step_ = HANDLE_ERROR_; break; } strcpy(lobLoc_, lobLocList[0]); char outLobHandle[LOB_HANDLE_LEN]; Int32 outHandleLen; Int64 requestTag = 0; /* retcode = ExpLOBInterfaceDelete(lobGlobs, lobTdb().getLobHdfsServer(), lobTdb().getLobHdfsPort(), lobName_, lobLoc_, lobHandleLen_, lobHandle_, requestTag_, getLobGlobals()->xnId(), inDescSyskey, 0,1); if (retcode < 0) { Lng32 cliError = 0; Lng32 intParam1 = -retcode; ComDiagsArea * diagsArea = getDiagsArea(); ExRaiseSqlError(getHeap(), &diagsArea, (ExeErrorCode)(8442), NULL, &intParam1, &cliError, NULL, (char*)"ExpLOBInterfaceUpdate", getLobErrStr(intParam1)); step_ = HANDLE_ERROR_; break; } */ retcode = ExpLOBInterfaceUpdate(lobGlobs, lobTdb().getLobHdfsServer(), lobTdb().getLobHdfsPort(), lobName_, lobLoc_, lobHandleLen_, lobHandle_, &outHandleLen, outLobHandle, requestTag, getLobGlobals()->xnId(), 0, 1, so, inDescSyskey, 0, NULL, lobName_, schNameLen, schName, dummy, dummy, lobTdb().getLobMaxSize(), lobTdb().getLobMaxChunkSize(), lobTdb().getLobGCLimit()); if (retcode < 0) { Lng32 cliError = 0; Lng32 intParam1 = -retcode; ComDiagsArea * diagsArea = getDiagsArea(); ExRaiseSqlError(getHeap(), &diagsArea, (ExeErrorCode)(8442), NULL, &intParam1, &cliError, NULL, (char*)"ExpLOBInterfaceUpdate", getLobErrStr(intParam1)); step_ = HANDLE_ERROR_; break; } if (so == Lob_Buffer) { str_sprintf(statusString_," Updated with empty_blob/clob "); step_ = RETURN_STATUS_; } break; } break; case CANCEL_: { break; } break; case RETURN_STATUS_: { if (qparent_.up->isFull()) return WORK_OK; //Return to upqueue whatever is in the lobStatusMsg_ data member short rc; moveRowToUpQueue(statusString_, 200, &rc); step_ = DONE_ ; } break; case HANDLE_ERROR_: { retcode = handleError(); if (retcode == 1) return WORK_OK; step_ = DONE_; } break; case DONE_: { retcode = handleDone(); if (retcode == 1) return WORK_OK; step_ = EMPTY_; return WORK_OK; } break; } } return 0; } NABoolean ExExeUtilFileExtractTcb::needStatsEntry() { // stats are collected for ALL and OPERATOR options. if ((getGlobals()->getStatsArea()->getCollectStatsType() == ComTdb::ALL_STATS) || (getGlobals()->getStatsArea()->getCollectStatsType() == ComTdb::OPERATOR_STATS)) return TRUE; else return FALSE; } ExOperStats * ExExeUtilFileExtractTcb::doAllocateStatsEntry( CollHeap *heap, ComTdb *tdb) { ExEspStmtGlobals *espGlobals = getGlobals()->castToExExeStmtGlobals()->castToExEspStmtGlobals(); StmtStats *ss; if (espGlobals != NULL) ss = espGlobals->getStmtStats(); else ss = getGlobals()->castToExExeStmtGlobals()->castToExMasterStmtGlobals()->getStatement()->getStmtStats(); ExHdfsScanStats *hdfsScanStats = new(heap) ExHdfsScanStats(heap, this, tdb); if (ss != NULL) hdfsScanStats->setQueryId(ss->getQueryId(), ss->getQueryIdLen()); return hdfsScanStats; } short ExExeUtilFileExtractTcb::work() { Lng32 cliRC = 0; Lng32 retcode = 0; // if no parent request, return if (qparent_.down->isEmpty()) return WORK_OK; ex_queue_entry * pentry_down = qparent_.down->getHeadEntry(); ExExeUtilPrivateState & pstate = *((ExExeUtilPrivateState*) pentry_down->pstate); ContextCli *currContext = getGlobals()->castToExExeStmtGlobals()->castToExMasterStmtGlobals()-> getStatement()->getContext(); ComDiagsArea & diags = currContext->diags(); void * lobGlobs = getLobGlobals()->lobAccessGlobals(); while (1) { switch (step_) { case EMPTY_: { lobName_ = lobNameBuf_; strcpy(lobName_, lobTdb().getFileName()); strcpy(lobLoc_, lobTdb().getStringParam2()); lobType_ = lobTdb().lobStorageType_; //(Lng32)Lob_External_HDFS_File; lobDataSpecifiedExtractLen_ = lobTdb().totalBufSize_; // allocate 2 buffers for double buffering. lobData_ = new(getHeap()) char[(UInt32)lobDataSpecifiedExtractLen_]; lobData2_ = new(getHeap()) char[(UInt32)lobDataSpecifiedExtractLen_]; eodReturned_ = FALSE; step_ = OPEN_CURSOR_; } break; case OPEN_CURSOR_: { eodReturned_ = FALSE; retcode = ExpLOBInterfaceSelectCursor (lobGlobs, lobName_, lobLoc_, lobType_, lobTdb().getLobHdfsServer(), lobTdb().getLobHdfsPort(), 0, NULL, // handleLen, handle 0, NULL, //cursor bytes, cursor id requestTag_, Lob_File, 0, // not check status 1, // waited op 0, lobDataSpecifiedExtractLen_, lobDataLen_, lobData_, 1, // open 2); // must open if (retcode < 0) { Lng32 cliError = 0; Lng32 intParam1 = -retcode; ComDiagsArea * diagsArea = getDiagsArea(); ExRaiseSqlError(getHeap(), &diagsArea, (ExeErrorCode)(8442), NULL, &intParam1, &cliError, NULL, (char*)"ExpLOBInterfaceSelectCursor/open", getLobErrStr(intParam1)); step_ = HANDLE_ERROR_; break; } step_ = READ_CURSOR_; } break; case READ_CURSOR_: { if (eodReturned_) { // eod was previously returned. close the cursor. step_ = CLOSE_CURSOR_; break; } retcode = ExpLOBInterfaceSelectCursor (lobGlobs, lobName_, lobLoc_, lobType_, lobTdb().getLobHdfsServer(), lobTdb().getLobHdfsPort(), 0, NULL, 0, NULL ,//cursor bytes, cursor id requestTag_, Lob_File, 0, // not check status 1, // waited op 0, lobDataSpecifiedExtractLen_, lobDataLen_, lobData_, 2, // read 0); // open type not applicable if (retcode < 0) { Lng32 cliError = 0; Lng32 intParam1 = -retcode; ComDiagsArea * diagsArea = getDiagsArea(); ExRaiseSqlError(getHeap(), &diagsArea, (ExeErrorCode)(8442), NULL, &intParam1, &cliError, NULL, (char*)"ExpLOBInterfaceSelectCursor/read", getLobErrStr(intParam1)); step_ = HANDLE_ERROR_; break; } if (lobDataLen_ == 0) { // EOD with no data: close cursor eodReturned_ = TRUE; step_ = CLOSE_CURSOR_; break; } if (lobDataLen_ < lobDataSpecifiedExtractLen_) { // EOD with data: return data and then close cursor eodReturned_ = TRUE; } remainingBytes_ = (Lng32)lobDataLen_; currPos_ = 0; step_ = RETURN_STRING_; } break; case CLOSE_CURSOR_: { retcode = ExpLOBInterfaceSelectCursor (lobGlobs, lobName_, lobLoc_, lobType_, lobTdb().getLobHdfsServer(), lobTdb().getLobHdfsPort(), 0, NULL, 0, NULL, //cursor bytes, cursor id requestTag_, Lob_File, 0, // not check status 1, // waited op 0, lobDataSpecifiedExtractLen_, lobDataLen_, lobData_, 3, // close 0); // open type not applicable if (retcode < 0) { Lng32 cliError = 0; Lng32 intParam1 = -retcode; ComDiagsArea * diagsArea = getDiagsArea(); ExRaiseSqlError(getHeap(), &diagsArea, (ExeErrorCode)(8442), NULL, &intParam1, &cliError, NULL, (char*)"ExpLOBInterfaceSelectCursor/close", getLobErrStr(intParam1)); step_ = HANDLE_ERROR_; break; } step_ = COLLECT_STATS_; } break; case HANDLE_ERROR_: { retcode = handleError(); if (retcode == 1) return WORK_OK; step_ = DONE_; } break; case COLLECT_STATS_: { if (! getStatsEntry()) { step_ = DONE_; break; } ExHdfsScanStats * stats = getStatsEntry()->castToExHdfsScanStats(); retcode = ExpLOBinterfaceStats (lobGlobs, stats->lobStats(), lobName_, lobLoc_, lobType_, lobTdb().getLobHdfsServer(), lobTdb().getLobHdfsPort()); step_ = DONE_; } break; case DONE_: { retcode = handleDone(); if (retcode == 1) return WORK_OK; step_ = EMPTY_; return WORK_OK; } break; } // switch } return 0; } ExExeUtilFileLoadTcb::ExExeUtilFileLoadTcb ( const ComTdbExeUtilLobExtract & exe_util_tdb, const ex_tcb * child_tcb, ex_globals * glob) : ExExeUtilLobExtractTcb(exe_util_tdb, child_tcb, glob) { } short ExExeUtilFileLoadTcb::work() { Lng32 cliRC = 0; Lng32 retcode = 0; // if no parent request, return if (qparent_.down->isEmpty()) return WORK_OK; ex_queue_entry * pentry_down = qparent_.down->getHeadEntry(); ExExeUtilPrivateState & pstate = *((ExExeUtilPrivateState*) pentry_down->pstate); ContextCli *currContext = getGlobals()->castToExExeStmtGlobals()->castToExMasterStmtGlobals()-> getStatement()->getContext(); ComDiagsArea & diags = currContext->diags(); void * lobGlobs = getLobGlobals()->lobAccessGlobals(); while (1) { switch (step_) { case EMPTY_: { lobName_ = lobNameBuf_; strcpy(lobName_, lobTdb().getStringParam2()); strcpy(lobLoc_, lobTdb().getStringParam3()); lobType_ = lobTdb().lobStorageType_; //(Lng32)Lob_HDFS_File; lobDataSpecifiedExtractLen_ = lobTdb().totalBufSize_; lobData_ = new(getHeap()) char[(UInt32)lobDataSpecifiedExtractLen_]; srcFileRemainingBytes_ = 0; step_ = CREATE_TARGET_FILE_; } break; case CREATE_TARGET_FILE_: { if (lobTdb().withCreate()) { retcode = ExpLOBinterfaceCreate (lobGlobs, lobName_, lobLoc_, lobType_, lobTdb().getLobHdfsServer(), lobTdb().getLobHdfsPort()); if (retcode < 0) { Lng32 cliError = 0; Lng32 intParam1 = -retcode; ComDiagsArea * diagsArea = getDiagsArea(); ExRaiseSqlError(getHeap(), &diagsArea, (ExeErrorCode)(8442), NULL, &intParam1, &cliError, NULL, (char*)"ExpLOBInterfaceCreate", getLobErrStr(intParam1)); step_ = HANDLE_ERROR_; break; } } if (lobTdb().getToType() == ComTdbExeUtilLobExtract::TO_EXTERNAL_FROM_STRING_) { strcpy(lobData_, lobTdb().getStringParam1()); lobDataLen_ = strlen(lobData_); step_ = INSERT_FROM_STRING_; } else step_ = INSERT_FROM_SOURCE_FILE_; } break; case INSERT_FROM_SOURCE_FILE_: { char fname[400]; str_sprintf(fname, "%s", lobTdb().getStringParam1()); indata_.open(fname, fstream::in | fstream::binary); if (! indata_) { Lng32 cliError = 0; Lng32 intParam1 = -1; ComDiagsArea * diagsArea = getDiagsArea(); ExRaiseSqlError(getHeap(), &diagsArea, (ExeErrorCode)(8442), NULL, &intParam1, &cliError, NULL, (char*)"SourceFile open"); step_ = HANDLE_ERROR_; break; } indata_.seekg (0, indata_.end); srcFileRemainingBytes_ = indata_.tellg(); indata_.seekg (0, indata_.beg); step_ = READ_STRING_FROM_SOURCE_FILE_; } break; case READ_STRING_FROM_SOURCE_FILE_: { if (! indata_.good()) { indata_.close(); step_ = CLOSE_TARGET_FILE_; break; } if (srcFileRemainingBytes_ == 0) { indata_.close(); step_ = CLOSE_TARGET_FILE_; break; } Int64 length = MINOF(srcFileRemainingBytes_, lobDataSpecifiedExtractLen_); indata_.read (lobData_, (std::streamsize)length); if (indata_.fail()) { indata_.close(); Lng32 cliError = 0; Lng32 intParam1 = -1; ComDiagsArea * diagsArea = getDiagsArea(); ExRaiseSqlError(getHeap(), &diagsArea, (ExeErrorCode)(8442), NULL, &intParam1, &cliError, NULL, (char*)"SourceFile read"); step_ = HANDLE_ERROR_; break; } lobDataLen_ = length; srcFileRemainingBytes_ -= length; step_ = INSERT_FROM_STRING_; } break; case INSERT_FROM_STRING_: { Int64 requestTag; Int64 dummy; retcode = ExpLOBInterfaceInsert (lobGlobs, lobName_, lobLoc_, lobType_, lobTdb().getLobHdfsServer(), lobTdb().getLobHdfsPort(), 0, NULL, NULL, NULL, 0, NULL, requestTag, 0, // no xn id dummy,Lob_InsertDataSimple, NULL, Lob_Memory, 1, // waited lobData_, lobDataLen_ ); if (retcode < 0) { Lng32 cliError = 0; Lng32 intParam1 = -retcode; ComDiagsArea * diagsArea = getDiagsArea(); ExRaiseSqlError(getHeap(), &diagsArea, (ExeErrorCode)(8442), NULL, &intParam1, &cliError, NULL, (char*)"ExpLOBInterfaceInsert", getLobErrStr(intParam1)); step_ = HANDLE_ERROR_; break; } if (lobTdb().getToType() == ComTdbExeUtilLobExtract::TO_EXTERNAL_FROM_FILE_) step_ = READ_STRING_FROM_SOURCE_FILE_; else step_ = CLOSE_TARGET_FILE_; } break; case CLOSE_TARGET_FILE_: { retcode = ExpLOBinterfaceCloseFile (lobGlobs, lobName_, lobLoc_, lobType_, lobTdb().getLobHdfsServer(), lobTdb().getLobHdfsPort()); if (retcode < 0) { Lng32 cliError = 0; Lng32 intParam1 = -retcode; ComDiagsArea * diagsArea = getDiagsArea(); ExRaiseSqlError(getHeap(), &diagsArea, (ExeErrorCode)(8442), NULL, &intParam1, &cliError, NULL, (char*)"ExpLOBInterfaceCloseFile", getLobErrStr(intParam1)); step_ = HANDLE_ERROR_; break; } step_ = DONE_; } break; case HANDLE_ERROR_: { retcode = handleError(); if (retcode == 1) return WORK_OK; step_ = DONE_; } break; case DONE_: { retcode = handleDone(); if (retcode == 1) return WORK_OK; step_ = EMPTY_; return WORK_OK; } break; } // switch } return 0; }
1
15,819
Actually, I do have one question: You mention that each warning is for a different range. Should we add the rowcounts instead of using the max?
apache-trafodion
cpp
@@ -31,6 +31,7 @@ type Protocol interface { ReadState(context.Context, StateReader, []byte, ...[]byte) ([]byte, error) Register(*Registry) error ForceRegister(*Registry) error + Name() string } // GenesisStateCreator creates some genesis states
1
// Copyright (c) 2019 IoTeX Foundation // This is an alpha (internal) release and is not suitable for production. This source code is provided 'as is' and no // warranties are given as to title or non-infringement, merchantability or fitness for purpose and, to the extent // permitted by law, all liability for your use of the code is disclaimed. This source code is governed by Apache // License 2.0 that can be found in the LICENSE file. package protocol import ( "context" "github.com/pkg/errors" "github.com/iotexproject/iotex-core/action" ) var ( // ErrUnimplemented indicates a method is not implemented yet ErrUnimplemented = errors.New("method is unimplemented") ) const ( // SystemNamespace is the namespace to store system information such as candidates/probationList/unproductiveDelegates SystemNamespace = "System" ) // Protocol defines the protocol interfaces atop IoTeX blockchain type Protocol interface { ActionValidator ActionHandler ReadState(context.Context, StateReader, []byte, ...[]byte) ([]byte, error) Register(*Registry) error ForceRegister(*Registry) error } // GenesisStateCreator creates some genesis states type GenesisStateCreator interface { CreateGenesisStates(context.Context, StateManager) error } // PreStatesCreator creates state manager type PreStatesCreator interface { CreatePreStates(context.Context, StateManager) error } // PostSystemActionsCreator creates a list of system actions to be appended to block actions type PostSystemActionsCreator interface { CreatePostSystemActions(context.Context) ([]action.Envelope, error) } // ActionValidator is the interface of validating an action type ActionValidator interface { Validate(context.Context, action.Action) error } // ActionHandler is the interface for the action handlers. For each incoming action, the assembled actions will be // called one by one to process it. ActionHandler implementation is supposed to parse the sub-type of the action to // decide if it wants to handle this action or not. type ActionHandler interface { Handle(context.Context, action.Action, StateManager) (*action.Receipt, error) }
1
21,426
it is confusing to return ID as Name
iotexproject-iotex-core
go
@@ -380,8 +380,15 @@ class RemoteConnection(object): # Authorization header headers["Authorization"] = "Basic %s" % auth - self._conn.request(method, parsed_url.path, data, headers) - resp = self._conn.getresponse() + if body and method != 'POST' and method != 'PUT': + body = None + try: + self._conn.request(method, parsed_url.path, body, headers) + resp = self._conn.getresponse() + except httplib.HTTPException: + self._conn.close() + raise + statuscode = resp.status statusmessage = resp.msg LOGGER.debug('%s %s' % (statuscode, statusmessage))
1
# Copyright 2008-2009 WebDriver committers # Copyright 2008-2009 Google Inc. # Copyright 2013 BrowserStack # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import socket import string import base64 try: import http.client as httplib except ImportError: import httplib as httplib try: from urllib import request as url_request except ImportError: import urllib2 as url_request try: from urllib import parse except ImportError: import urlparse as parse from .command import Command from .errorhandler import ErrorCode from . import utils LOGGER = logging.getLogger(__name__) class Request(url_request.Request): """ Extends the url_request.Request to support all HTTP request types. """ def __init__(self, url, data=None, method=None): """ Initialise a new HTTP request. :Args: - url - String for the URL to send the request to. - data - Data to send with the request. """ if method is None: method = data is not None and 'POST' or 'GET' elif method != 'POST' and method != 'PUT': data = None self._method = method url_request.Request.__init__(self, url, data=data) def get_method(self): """ Returns the HTTP method used by this request. """ return self._method class Response(object): """ Represents an HTTP response. """ def __init__(self, fp, code, headers, url): """ Initialise a new Response. :Args: - fp - The response body file object. - code - The HTTP status code returned by the server. - headers - A dictionary of headers returned by the server. - url - URL of the retrieved resource represented by this Response. """ self.fp = fp self.read = fp.read self.code = code self.headers = headers self.url = url def close(self): """ Close the response body file object. """ self.read = None self.fp = None def info(self): """ Returns the response headers. """ return self.headers def geturl(self): """ Returns the URL for the resource returned in this response. """ return self.url class HttpErrorHandler(url_request.HTTPDefaultErrorHandler): """ A custom HTTP error handler. Used to return Response objects instead of raising an HTTPError exception. """ def http_error_default(self, req, fp, code, msg, headers): """ Default HTTP error handler. :Args: - req - The original Request object. - fp - The response body file object. - code - The HTTP status code returned by the server. - msg - The HTTP status message returned by the server. - headers - The response headers. :Returns: A new Response object. """ return Response(fp, code, headers, req.get_full_url()) class RemoteConnection(object): """ A connection with the Remote WebDriver server. Communicates with the server using the WebDriver wire protocol: http://code.google.com/p/selenium/wiki/JsonWireProtocol """ def __init__(self, remote_server_addr): # Attempt to resolve the hostname and get an IP address. parsed_url = parse.urlparse(remote_server_addr) addr = "" if parsed_url.hostname: try: netloc = socket.gethostbyname(parsed_url.hostname) addr = netloc if parsed_url.port: netloc += ':%d' % parsed_url.port if parsed_url.username: auth = parsed_url.username if parsed_url.password: auth += ':%s' % parsed_url.password netloc = '%s@%s' % (auth, netloc) remote_server_addr = parse.urlunparse( (parsed_url.scheme, netloc, parsed_url.path, parsed_url.params, parsed_url.query, parsed_url.fragment)) except socket.gaierror: LOGGER.info('Could not get IP address for host: %s' % parsed_url.hostname) self._url = remote_server_addr self._conn = httplib.HTTPConnection(str(addr), str(parsed_url.port)) self._commands = { Command.STATUS: ('GET', '/status'), Command.NEW_SESSION: ('POST', '/session'), Command.GET_ALL_SESSIONS: ('GET', '/sessions'), Command.QUIT: ('DELETE', '/session/$sessionId'), Command.GET_CURRENT_WINDOW_HANDLE: ('GET', '/session/$sessionId/window_handle'), Command.GET_WINDOW_HANDLES: ('GET', '/session/$sessionId/window_handles'), Command.GET: ('POST', '/session/$sessionId/url'), Command.GO_FORWARD: ('POST', '/session/$sessionId/forward'), Command.GO_BACK: ('POST', '/session/$sessionId/back'), Command.REFRESH: ('POST', '/session/$sessionId/refresh'), Command.EXECUTE_SCRIPT: ('POST', '/session/$sessionId/execute'), Command.GET_CURRENT_URL: ('GET', '/session/$sessionId/url'), Command.GET_TITLE: ('GET', '/session/$sessionId/title'), Command.GET_PAGE_SOURCE: ('GET', '/session/$sessionId/source'), Command.SCREENSHOT: ('GET', '/session/$sessionId/screenshot'), Command.SET_BROWSER_VISIBLE: ('POST', '/session/$sessionId/visible'), Command.IS_BROWSER_VISIBLE: ('GET', '/session/$sessionId/visible'), Command.FIND_ELEMENT: ('POST', '/session/$sessionId/element'), Command.FIND_ELEMENTS: ('POST', '/session/$sessionId/elements'), Command.GET_ACTIVE_ELEMENT: ('POST', '/session/$sessionId/element/active'), Command.FIND_CHILD_ELEMENT: ('POST', '/session/$sessionId/element/$id/element'), Command.FIND_CHILD_ELEMENTS: ('POST', '/session/$sessionId/element/$id/elements'), Command.CLICK_ELEMENT: ('POST', '/session/$sessionId/element/$id/click'), Command.CLEAR_ELEMENT: ('POST', '/session/$sessionId/element/$id/clear'), Command.SUBMIT_ELEMENT: ('POST', '/session/$sessionId/element/$id/submit'), Command.GET_ELEMENT_TEXT: ('GET', '/session/$sessionId/element/$id/text'), Command.SEND_KEYS_TO_ELEMENT: ('POST', '/session/$sessionId/element/$id/value'), Command.SEND_KEYS_TO_ACTIVE_ELEMENT: ('POST', '/session/$sessionId/keys'), Command.UPLOAD_FILE: ('POST', "/session/$sessionId/file"), Command.GET_ELEMENT_VALUE: ('GET', '/session/$sessionId/element/$id/value'), Command.GET_ELEMENT_TAG_NAME: ('GET', '/session/$sessionId/element/$id/name'), Command.IS_ELEMENT_SELECTED: ('GET', '/session/$sessionId/element/$id/selected'), Command.SET_ELEMENT_SELECTED: ('POST', '/session/$sessionId/element/$id/selected'), Command.IS_ELEMENT_ENABLED: ('GET', '/session/$sessionId/element/$id/enabled'), Command.IS_ELEMENT_DISPLAYED: ('GET', '/session/$sessionId/element/$id/displayed'), Command.GET_ELEMENT_LOCATION: ('GET', '/session/$sessionId/element/$id/location'), Command.GET_ELEMENT_LOCATION_ONCE_SCROLLED_INTO_VIEW: ('GET', '/session/$sessionId/element/$id/location_in_view'), Command.GET_ELEMENT_SIZE: ('GET', '/session/$sessionId/element/$id/size'), Command.GET_ELEMENT_ATTRIBUTE: ('GET', '/session/$sessionId/element/$id/attribute/$name'), Command.ELEMENT_EQUALS: ('GET', '/session/$sessionId/element/$id/equals/$other'), Command.GET_ALL_COOKIES: ('GET', '/session/$sessionId/cookie'), Command.ADD_COOKIE: ('POST', '/session/$sessionId/cookie'), Command.DELETE_ALL_COOKIES: ('DELETE', '/session/$sessionId/cookie'), Command.DELETE_COOKIE: ('DELETE', '/session/$sessionId/cookie/$name'), Command.SWITCH_TO_FRAME: ('POST', '/session/$sessionId/frame'), Command.SWITCH_TO_WINDOW: ('POST', '/session/$sessionId/window'), Command.CLOSE: ('DELETE', '/session/$sessionId/window'), Command.GET_ELEMENT_VALUE_OF_CSS_PROPERTY: ('GET', '/session/$sessionId/element/$id/css/$propertyName'), Command.IMPLICIT_WAIT: ('POST', '/session/$sessionId/timeouts/implicit_wait'), Command.EXECUTE_ASYNC_SCRIPT: ('POST', '/session/$sessionId/execute_async'), Command.SET_SCRIPT_TIMEOUT: ('POST', '/session/$sessionId/timeouts/async_script'), Command.SET_TIMEOUTS: ('POST', '/session/$sessionId/timeouts'), Command.DISMISS_ALERT: ('POST', '/session/$sessionId/dismiss_alert'), Command.ACCEPT_ALERT: ('POST', '/session/$sessionId/accept_alert'), Command.SET_ALERT_VALUE: ('POST', '/session/$sessionId/alert_text'), Command.GET_ALERT_TEXT: ('GET', '/session/$sessionId/alert_text'), Command.CLICK: ('POST', '/session/$sessionId/click'), Command.DOUBLE_CLICK: ('POST', '/session/$sessionId/doubleclick'), Command.MOUSE_DOWN: ('POST', '/session/$sessionId/buttondown'), Command.MOUSE_UP: ('POST', '/session/$sessionId/buttonup'), Command.MOVE_TO: ('POST', '/session/$sessionId/moveto'), Command.GET_WINDOW_SIZE: ('GET', '/session/$sessionId/window/$windowHandle/size'), Command.SET_WINDOW_SIZE: ('POST', '/session/$sessionId/window/$windowHandle/size'), Command.GET_WINDOW_POSITION: ('GET', '/session/$sessionId/window/$windowHandle/position'), Command.SET_WINDOW_POSITION: ('POST', '/session/$sessionId/window/$windowHandle/position'), Command.MAXIMIZE_WINDOW: ('POST', '/session/$sessionId/window/$windowHandle/maximize'), Command.SET_SCREEN_ORIENTATION: ('POST', '/session/$sessionId/orientation'), Command.GET_SCREEN_ORIENTATION: ('GET', '/session/$sessionId/orientation'), Command.SINGLE_TAP: ('POST', '/session/$sessionId/touch/click'), Command.TOUCH_DOWN: ('POST', '/session/$sessionId/touch/down'), Command.TOUCH_UP: ('POST', '/session/$sessionId/touch/up'), Command.TOUCH_MOVE: ('POST', '/session/$sessionId/touch/move'), Command.TOUCH_SCROLL: ('POST', '/session/$sessionId/touch/scroll'), Command.DOUBLE_TAP: ('POST', '/session/$sessionId/touch/doubleclick'), Command.LONG_PRESS: ('POST', '/session/$sessionId/touch/longclick'), Command.FLICK: ('POST', '/session/$sessionId/touch/flick'), Command.EXECUTE_SQL: ('POST', '/session/$sessionId/execute_sql'), Command.GET_LOCATION: ('GET', '/session/$sessionId/location'), Command.SET_LOCATION: ('POST', '/session/$sessionId/location'), Command.GET_APP_CACHE: ('GET', '/session/$sessionId/application_cache'), Command.GET_APP_CACHE_STATUS: ('GET', '/session/$sessionId/application_cache/status'), Command.CLEAR_APP_CACHE: ('DELETE', '/session/$sessionId/application_cache/clear'), Command.IS_BROWSER_ONLINE: ('GET', '/session/$sessionId/browser_connection'), Command.SET_BROWSER_ONLINE: ('POST', '/session/$sessionId/browser_connection'), Command.GET_LOCAL_STORAGE_ITEM: ('GET', '/session/$sessionId/local_storage/key/$key'), Command.REMOVE_LOCAL_STORAGE_ITEM: ('DELETE', '/session/$sessionId/local_storage/key/$key'), Command.GET_LOCAL_STORAGE_KEYS: ('GET', '/session/$sessionId/local_storage'), Command.SET_LOCAL_STORAGE_ITEM: ('POST', '/session/$sessionId/local_storage'), Command.CLEAR_LOCAL_STORAGE: ('DELETE', '/session/$sessionId/local_storage'), Command.GET_LOCAL_STORAGE_SIZE: ('GET', '/session/$sessionId/local_storage/size'), Command.GET_SESSION_STORAGE_ITEM: ('GET', '/session/$sessionId/session_storage/key/$key'), Command.REMOVE_SESSION_STORAGE_ITEM: ('DELETE', '/session/$sessionId/session_storage/key/$key'), Command.GET_SESSION_STORAGE_KEYS: ('GET', '/session/$sessionId/session_storage'), Command.SET_SESSION_STORAGE_ITEM: ('POST', '/session/$sessionId/session_storage'), Command.CLEAR_SESSION_STORAGE: ('DELETE', '/session/$sessionId/session_storage'), Command.GET_SESSION_STORAGE_SIZE: ('GET', '/session/$sessionId/session_storage/size'), Command.GET_LOG: ('POST', '/session/$sessionId/log'), Command.GET_AVAILABLE_LOG_TYPES: ('GET', '/session/$sessionId/log/types'), } def execute(self, command, params): """ Send a command to the remote server. Any path subtitutions required for the URL mapped to the command should be included in the command parameters. :Args: - command - A string specifying the command to execute. - params - A dictionary of named parameters to send with the command as its JSON payload. """ command_info = self._commands[command] assert command_info is not None, 'Unrecognised command %s' % command data = utils.dump_json(params) path = string.Template(command_info[1]).substitute(params) url = '%s%s' % (self._url, path) return self._request(url, method=command_info[0], data=data) def _request(self, url, data=None, method=None): """ Send an HTTP request to the remote server. :Args: - method - A string for the HTTP method to send the request with. - url - The URL to send the request to. - body - The message body to send. :Returns: A dictionary with the server's parsed JSON response. """ LOGGER.debug('%s %s %s' % (method, url, data)) parsed_url = parse.urlparse(url) headers = {"Connection": "keep-alive", method: parsed_url.path, "User-Agent": "Python http auth", "Content-type": "application/json;charset=\"UTF-8\"", "Accept": "application/json"} # for basic auth if parsed_url.username: auth = base64.standard_b64encode('%s:%s' % (parsed_url.username, parsed_url.password)).replace('\n', '') # Authorization header headers["Authorization"] = "Basic %s" % auth self._conn.request(method, parsed_url.path, data, headers) resp = self._conn.getresponse() statuscode = resp.status statusmessage = resp.msg LOGGER.debug('%s %s' % (statuscode, statusmessage)) data = resp.read() try: if 399 < statuscode < 500: return {'status': statuscode, 'value': data} if 300 <= statuscode < 304: return self._request(resp.getheader('location'), method='GET') body = data.decode('utf-8').replace('\x00', '').strip() content_type = [] if resp.getheader('Content-Type') is not None: content_type = resp.getheader('Content-Type').split(';') if not any([x.startswith('image/png') for x in content_type]): try: data = utils.load_json(body.strip()) except ValueError: if 199 < statuscode < 300: status = ErrorCode.SUCCESS else: status = ErrorCode.UNKNOWN_ERROR return {'status': status, 'value': body.strip()} assert type(data) is dict, ( 'Invalid server response body: %s' % body) assert 'status' in data, ( 'Invalid server response; no status: %s' % body) # Some of the drivers incorrectly return a response # with no 'value' field when they should return null. if 'value' not in data: data['value'] = None return data else: data = {'status': 0, 'value': body.strip()} return data finally: LOGGER.debug("Finished Request") resp.close()
1
10,707
body is being used here for the first time without every being populated. This will error. To run tests do `./go clean test_py` and that will run the Firefox tests
SeleniumHQ-selenium
java
@@ -48,7 +48,7 @@ class Bootstrap } $kernel = new AppKernel($this->environment, Environment::isEnvironmentDebug($this->environment)); - $kernel->loadClassCache(); + Request::setTrustedProxies(['127.0.0.1'], Request::HEADER_X_FORWARDED_ALL); if ($this->console) { $input = new ArgvInput(); $output = new ConsoleOutput();
1
<?php namespace Shopsys; use AppKernel; use Doctrine\Common\Annotations\AnnotationRegistry; use Shopsys\Environment; use Symfony\Bundle\FrameworkBundle\Console\Application; use Symfony\Component\Console\Input\ArgvInput; use Symfony\Component\Console\Output\ConsoleOutput; use Symfony\Component\Debug\Debug; use Symfony\Component\Debug\ErrorHandler; use Symfony\Component\HttpFoundation\Request; require_once __DIR__ . '/autoload.php'; setlocale(LC_CTYPE, 'en_US.utf8'); class Bootstrap { private $environment; private $console; public function __construct($console = false, $environment = null) { if ($environment === null) { $this->environment = Environment::getEnvironment($console); } else { $this->environment = $environment; } $this->console = (bool)$console; } public function run() { if ($this->environment !== Environment::ENVIRONMENT_DEVELOPMENT) { // Speed-up loading in production using bootstrap file that combines multiple PHP files to reduce disk IO. // See http://symfony.com/doc/3.0/performance.html#use-bootstrap-files include_once __DIR__ . '/../var/bootstrap.php.cache'; } $this->configurePhp(); if (Environment::isEnvironmentDebug($this->environment)) { Debug::enable(); } else { ErrorHandler::register(); } $kernel = new AppKernel($this->environment, Environment::isEnvironmentDebug($this->environment)); $kernel->loadClassCache(); if ($this->console) { $input = new ArgvInput(); $output = new ConsoleOutput(); $output->getErrorOutput()->setVerbosity(ConsoleOutput::VERBOSITY_VERBOSE); $application = new Application($kernel); $application->run($input, $output); } else { $this->initDoctrine(); $request = Request::createFromGlobals(); $response = $kernel->handle($request); $response->send(); $kernel->terminate($request, $response); } } private function configurePhp() { error_reporting(E_ALL); ini_set('display_errors', 0); } private function initDoctrine() { if ($this->environment === Environment::ENVIRONMENT_DEVELOPMENT) { $dirs = [__DIR__ . '/../vendor/doctrine/orm/lib/']; AnnotationRegistry::registerAutoloadNamespace('Doctrine\ORM', $dirs); } } }
1
8,764
commit mesasge: I would append "...Kernel::loadClassCache() method call"
shopsys-shopsys
php
@@ -76,8 +76,9 @@ public class Actions { * Note that the modifier key is <b>never</b> released implicitly - either * <i>keyUp(theKey)</i> or <i>sendKeys(Keys.NULL)</i> * must be called to release the modifier. - * @param theKey Either {@link Keys#SHIFT}, {@link Keys#ALT} or {@link Keys#CONTROL}. If the - * provided key is none of those, {@link IllegalArgumentException} is thrown. + * @param theKey Either {@link Keys#SHIFT}, {@link Keys#ALT}, {@link Keys#CONTROL} + * or {@link Keys#COMMAND}. If the provided key is none of those, + * {@link IllegalArgumentException} is thrown. * @return A self reference. */ public Actions keyDown(Keys theKey) {
1
/* Copyright 2007-2011 Selenium committers Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.openqa.selenium.interactions; import org.openqa.selenium.HasInputDevices; import org.openqa.selenium.Keyboard; import org.openqa.selenium.Keys; import org.openqa.selenium.Mouse; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.internal.Locatable; /** * The user-facing API for emulating complex user gestures. Use this class rather than using the * Keyboard or Mouse directly. * * Implements the builder pattern: Builds a CompositeAction containing all actions specified by the * method calls. */ public class Actions { protected Mouse mouse; protected Keyboard keyboard; protected CompositeAction action; /** * Default constructor - uses the default keyboard, mouse implemented by the driver. * @param driver the driver providing the implementations to use. */ public Actions(WebDriver driver) { this(((HasInputDevices) driver).getKeyboard(), ((HasInputDevices) driver).getMouse()); } /** * A constructor that should only be used when the keyboard or mouse were extended to provide * additional functionality (for example, dragging-and-dropping from the desktop). * @param keyboard the {@link Keyboard} implementation to delegate to. * @param mouse the {@link Mouse} implementation to delegate to. */ public Actions(Keyboard keyboard, Mouse mouse) { this.mouse = mouse; this.keyboard = keyboard; resetCompositeAction(); } /** * Only used by the TouchActions class. * @param keyboard implementation to delegate to. */ public Actions(Keyboard keyboard) { this.keyboard = keyboard; resetCompositeAction(); } private void resetCompositeAction() { action = new CompositeAction(); } /** * Performs a modifier key press. Does not release the modifier key - subsequent interactions * may assume it's kept pressed. * Note that the modifier key is <b>never</b> released implicitly - either * <i>keyUp(theKey)</i> or <i>sendKeys(Keys.NULL)</i> * must be called to release the modifier. * @param theKey Either {@link Keys#SHIFT}, {@link Keys#ALT} or {@link Keys#CONTROL}. If the * provided key is none of those, {@link IllegalArgumentException} is thrown. * @return A self reference. */ public Actions keyDown(Keys theKey) { return this.keyDown(null, theKey); } /** * Performs a modifier key press after focusing on an element. Equivalent to: * <i>Actions.click(element).sendKeys(theKey);</i> * @see #keyDown(org.openqa.selenium.Keys) * * @param theKey Either {@link Keys#SHIFT}, {@link Keys#ALT} or {@link Keys#CONTROL}. If the * provided key is none of those, {@link IllegalArgumentException} is thrown. * @return A self reference. */ public Actions keyDown(WebElement element, Keys theKey) { action.addAction(new KeyDownAction(keyboard, mouse, (Locatable) element, theKey)); return this; } /** * Performs a modifier key release. Releasing a non-depressed modifier key will yield undefined * behaviour. * * @param theKey Either {@link Keys#SHIFT}, {@link Keys#ALT} or {@link Keys#CONTROL}. * @return A self reference. */ public Actions keyUp(Keys theKey) { return this.keyUp(null, theKey); } /** * Performs a modifier key release after focusing on an element. Equivalent to: * <i>Actions.click(element).sendKeys(theKey);</i> * @see #keyUp(org.openqa.selenium.Keys) on behaviour regarding non-depressed modifier keys. * * @param theKey Either {@link Keys#SHIFT}, {@link Keys#ALT} or {@link Keys#CONTROL}. * @return A self reference. */ public Actions keyUp(WebElement element, Keys theKey) { action.addAction(new KeyUpAction(keyboard, mouse, (Locatable) element, theKey)); return this; } /** * Sends keys to the active element. This differs from calling * {@link WebElement#sendKeys(CharSequence...)} on the active element in two ways: * <ul> * <li>The modifier keys included in this call are not released.</li> * <li>There is no attempt to re-focus the element - so sendKeys(Keys.TAB) for switching * elements should work. </li> * </ul> * * @see WebElement#sendKeys(CharSequence...) * * @param keysToSend The keys. * @return A self reference. */ public Actions sendKeys(CharSequence... keysToSend) { return this.sendKeys(null, keysToSend); } /** * Equivalent to calling: * <i>Actions.click(element).sendKeys(keysToSend).</i> * This method is different from {@link org.openqa.selenium.WebElement#sendKeys(CharSequence...)} - see * {@link Actions#sendKeys(CharSequence...)} for details how. * * @see #sendKeys(java.lang.CharSequence[]) * * @param element element to focus on. * @param keysToSend The keys. * @return A self reference. */ public Actions sendKeys(WebElement element, CharSequence... keysToSend) { action.addAction(new SendKeysAction(keyboard, mouse, (Locatable) element, keysToSend)); return this; } /** * Clicks (without releasing) in the middle of the given element. This is equivalent to: * <i>Actions.moveToElement(onElement).clickAndHold()</i> * * @param onElement Element to move to and click. * @return A self reference. */ public Actions clickAndHold(WebElement onElement) { action.addAction(new ClickAndHoldAction(mouse, (Locatable) onElement)); return this; } /** * Clicks (without releasing) at the current mouse location. * @return A self reference. */ public Actions clickAndHold() { return this.clickAndHold(null); } /** * Releases the depressed left mouse button, in the middle of the given element. * This is equivalent to: * <i>Actions.moveToElement(onElement).release()</i> * * Invoking this action without invoking {@link #clickAndHold()} first will result in * undefined behaviour. * * @param onElement Element to release the mouse button above. * @return A self reference. */ public Actions release(WebElement onElement) { action.addAction(new ButtonReleaseAction(mouse, (Locatable) onElement)); return this; } /** * Releases the depressed left mouse button at the current mouse location. * @see #release(org.openqa.selenium.WebElement) * @return A self reference. */ public Actions release() { return this.release(null); } /** * Clicks in the middle of the given element. Equivalent to: * <i>Actions.moveToElement(onElement).click()</i> * * @param onElement Element to click. * @return A self reference. */ public Actions click(WebElement onElement) { action.addAction(new ClickAction(mouse, (Locatable) onElement)); return this; } /** * Clicks at the current mouse location. Useful when combined with * {@link #moveToElement(org.openqa.selenium.WebElement, int, int)} or * {@link #moveByOffset(int, int)}. * @return A self reference. */ public Actions click() { return this.click(null); } /** * Performs a double-click at middle of the given element. Equivalent to: * <i>Actions.moveToElement(element).doubleClick()</i> * * @param onElement Element to move to. * @return A self reference. */ public Actions doubleClick(WebElement onElement) { action.addAction(new DoubleClickAction(mouse, (Locatable) onElement)); return this; } /** * Performs a double-click at the current mouse location. * @return A self reference. */ public Actions doubleClick() { return this.doubleClick(null); } /** * Moves the mouse to the middle of the element. The element is scrolled into view and its * location is calculated using getBoundingClientRect. * @param toElement element to move to. * @return A self reference. */ public Actions moveToElement(WebElement toElement) { action.addAction(new MoveMouseAction(mouse, (Locatable) toElement)); return this; } /** * Moves the mouse to an offset from the top-left corner of the element. * The element is scrolled into view and its location is calculated using getBoundingClientRect. * @param toElement element to move to. * @param xOffset Offset from the top-left corner. A negative value means coordinates right from * the element. * @param yOffset Offset from the top-left corner. A negative value means coordinates above * the element. * @return A self reference. */ public Actions moveToElement(WebElement toElement, int xOffset, int yOffset) { action.addAction(new MoveToOffsetAction(mouse, (Locatable) toElement, xOffset, yOffset)); return this; } /** * Moves the mouse from its current position (or 0,0) by the given offset. If the coordinates * provided are outside the viewport (the mouse will end up outside the browser window) then * the viewport is scrolled to match. * @param xOffset horizontal offset. A negative value means moving the mouse left. * @param yOffset vertical offset. A negative value means moving the mouse up. * @return A self reference. * @throws MoveTargetOutOfBoundsException if the provided offset is outside the document's * boundaries. */ public Actions moveByOffset(int xOffset, int yOffset) { action.addAction(new MoveToOffsetAction(mouse, null, xOffset, yOffset)); return this; } /** * Performs a context-click at middle of the given element. First performs a mouseMove * to the location of the element. * * @param onElement Element to move to. * @return A self reference. */ public Actions contextClick(WebElement onElement) { action.addAction(new ContextClickAction(mouse, (Locatable) onElement)); return this; } /** * Performs a context-click at the current mouse location. * @return A self reference. */ public Actions contextClick() { return this.contextClick(null); } /** * A convenience method that performs click-and-hold at the location of the source element, * moves to the location of the target element, then releases the mouse. * * @param source element to emulate button down at. * @param target element to move to and release the mouse at. * @return A self reference. */ public Actions dragAndDrop(WebElement source, WebElement target) { action.addAction(new ClickAndHoldAction(mouse, (Locatable) source)); action.addAction(new MoveMouseAction(mouse, (Locatable) target)); action.addAction(new ButtonReleaseAction(mouse, (Locatable) target)); return this; } /** * A convenience method that performs click-and-hold at the location of the source element, * moves by a given offset, then releases the mouse. * * @param source element to emulate button down at. * @param xOffset horizontal move offset. * @param yOffset vertical move offset. * @return A self reference. */ public Actions dragAndDropBy(WebElement source, int xOffset, int yOffset) { action.addAction(new ClickAndHoldAction(mouse, (Locatable) source)); action.addAction(new MoveToOffsetAction(mouse, null, xOffset, yOffset)); action.addAction(new ButtonReleaseAction(mouse, null)); return this; } /** * Generates a composite action containinig all actions so far, ready to be performed (and * resets the internal builder state, so subsequent calls to build() will contain fresh * sequences). * * @return the composite action */ public Action build() { CompositeAction toReturn = action; resetCompositeAction(); return toReturn; } /** * A convenience method for performing the actions without calling build() first. */ public void perform() { build().perform(); } }
1
10,429
Keys.COMMAND seems to be an alias to Keys.META. That isn't mentioned?
SeleniumHQ-selenium
py
@@ -2,7 +2,7 @@ package azkaban.test.utils; import java.io.File; -import junit.framework.Assert; +import org.junit.Assert; import org.apache.log4j.Logger; import org.junit.Test;
1
package azkaban.test.utils; import java.io.File; import junit.framework.Assert; import org.apache.log4j.Logger; import org.junit.Test; import azkaban.utils.DirectoryFlowLoader; public class DirectoryFlowLoaderTest { @Test public void testDirectoryLoad() { Logger logger = Logger.getLogger(this.getClass()); DirectoryFlowLoader loader = new DirectoryFlowLoader(logger); loader.loadProjectFlow(new File("unit/executions/exectest1")); logger.info(loader.getFlowMap().size()); } @Test public void testLoadEmbeddedFlow() { Logger logger = Logger.getLogger(this.getClass()); DirectoryFlowLoader loader = new DirectoryFlowLoader(logger); loader.loadProjectFlow(new File("unit/executions/embedded")); Assert.assertEquals(0, loader.getErrors().size()); } @Test public void testRecursiveLoadEmbeddedFlow() { Logger logger = Logger.getLogger(this.getClass()); DirectoryFlowLoader loader = new DirectoryFlowLoader(logger); loader.loadProjectFlow(new File("unit/executions/embeddedBad")); for (String error: loader.getErrors()) { System.out.println(error); } // Should be 3 errors: jobe->innerFlow, innerFlow->jobe, innerFlow Assert.assertEquals(3, loader.getErrors().size()); } }
1
9,510
You can move this import down to before line 8 (import org.junit.Test;).
azkaban-azkaban
java
@@ -52,7 +52,7 @@ class Findingsnotifier(object): 'resource_type': violation.get('resource_type'), 'resource_id': violation.get('resource_id'), 'rule_index': violation.get('rule_index'), - 'inventory_index_id': violation.get('inventory_index_id'), + 'scanner_index_id': violation.get('scanner_index_id'), 'resource_data': violation.get('resource_data') } }
1
# Copyright 2017 The Forseti Security 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. """Upload violations to GCS bucket as Findings.""" import tempfile from google.cloud.forseti.common.gcp_api import storage from google.cloud.forseti.common.util import logger from google.cloud.forseti.common.util import parser from google.cloud.forseti.common.util import date_time from google.cloud.forseti.common.util import string_formats LOGGER = logger.get_logger(__name__) class Findingsnotifier(object): """Upload violations to GCS bucket as findings.""" @staticmethod def _transform_to_findings(violations): """Transform forseti violations to findings format. Args: violations (dict): Violations to be uploaded as findings. Returns: list: violations in findings format; each violation is a dict. """ findings = [] for violation in violations: finding = { 'finding_id': violation.get('violation_hash'), 'finding_summary': violation.get('rule_name'), 'finding_source_id': 'FORSETI', 'finding_category': violation.get('violation_type'), 'finding_asset_ids': violation.get('full_name'), 'finding_time_event': violation.get('created_at_datetime'), 'finding_callback_url': None, 'finding_properties': { 'violation_data': violation.get('violation_data'), 'resource_type': violation.get('resource_type'), 'resource_id': violation.get('resource_id'), 'rule_index': violation.get('rule_index'), 'inventory_index_id': violation.get('inventory_index_id'), 'resource_data': violation.get('resource_data') } } findings.append(finding) return findings @staticmethod def _get_output_filename(): """Create the output filename. Returns: str: The output filename for the violations json. """ now_utc = date_time.get_utc_now_datetime() output_timestamp = now_utc.strftime( string_formats.TIMESTAMP_TIMEZONE) return string_formats.FINDINGS_FILENAME.format(output_timestamp) def run(self, violations, gcs_path): """Generate the temporary json file and upload to GCS. Args: violations (dict): Violations to be uploaded as findings. gcs_path (str): The GCS bucket to upload the findings. """ LOGGER.info('Running findings notification.') findings = self._transform_to_findings(violations) with tempfile.NamedTemporaryFile() as tmp_violations: tmp_violations.write(parser.json_stringify(findings)) tmp_violations.flush() gcs_upload_path = '{}/{}'.format( gcs_path, self._get_output_filename()) if gcs_upload_path.startswith('gs://'): storage_client = storage.StorageClient() storage_client.put_text_file( tmp_violations.name, gcs_upload_path)
1
29,616
It's okay to add the `scanner_index_id` here. But we still should keep the `inventory_index_id` reference because it will help the user to know right away, which inventory the violation is coming from, without having to do another lookup.
forseti-security-forseti-security
py
@@ -349,7 +349,9 @@ public class EventFiringWebDriver implements WebDriver, JavascriptExecutor, Take } public void submit() { + dispatcher.beforeClickOn(element, driver); element.submit(); + dispatcher.afterClickOn(element, driver); } public void sendKeys(CharSequence... keysToSend) {
1
// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package org.openqa.selenium.support.events; import org.openqa.selenium.Alert; import org.openqa.selenium.Beta; import org.openqa.selenium.By; import org.openqa.selenium.Cookie; import org.openqa.selenium.Dimension; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.OutputType; import org.openqa.selenium.Point; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebDriverException; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.HasInputDevices; import org.openqa.selenium.interactions.HasTouchScreen; import org.openqa.selenium.interactions.Keyboard; import org.openqa.selenium.interactions.Mouse; import org.openqa.selenium.interactions.TouchScreen; import org.openqa.selenium.interactions.internal.Coordinates; import org.openqa.selenium.internal.Locatable; import org.openqa.selenium.internal.WrapsDriver; import org.openqa.selenium.internal.WrapsElement; import org.openqa.selenium.logging.Logs; import org.openqa.selenium.support.events.internal.EventFiringKeyboard; import org.openqa.selenium.support.events.internal.EventFiringMouse; import org.openqa.selenium.support.events.internal.EventFiringTouch; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; /** * A wrapper around an arbitrary {@link WebDriver} instance which supports registering of a * {@link WebDriverEventListener}, e&#46;g&#46; for logging purposes. */ public class EventFiringWebDriver implements WebDriver, JavascriptExecutor, TakesScreenshot, WrapsDriver, HasInputDevices, HasTouchScreen { private final WebDriver driver; private final List<WebDriverEventListener> eventListeners = new ArrayList<>(); private final WebDriverEventListener dispatcher = (WebDriverEventListener) Proxy .newProxyInstance( WebDriverEventListener.class.getClassLoader(), new Class[] {WebDriverEventListener.class}, new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try { for (WebDriverEventListener eventListener : eventListeners) { method.invoke(eventListener, args); } return null; } catch (InvocationTargetException e){ throw e.getTargetException(); } } } ); public EventFiringWebDriver(final WebDriver driver) { Class<?>[] allInterfaces = extractInterfaces(driver); this.driver = (WebDriver) Proxy.newProxyInstance( WebDriverEventListener.class.getClassLoader(), allInterfaces, new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if ("getWrappedDriver".equals(method.getName())) { return driver; } try { return method.invoke(driver, args); } catch (InvocationTargetException e) { dispatcher.onException(e.getTargetException(), driver); throw e.getTargetException(); } } } ); } private Class<?>[] extractInterfaces(Object object) { Set<Class<?>> allInterfaces = new HashSet<>(); allInterfaces.add(WrapsDriver.class); if (object instanceof WebElement) { allInterfaces.add(WrapsElement.class); } extractInterfaces(allInterfaces, object.getClass()); return allInterfaces.toArray(new Class<?>[allInterfaces.size()]); } private void extractInterfaces(Set<Class<?>> addTo, Class<?> clazz) { if (Object.class.equals(clazz)) { return; // Done } Class<?>[] classes = clazz.getInterfaces(); addTo.addAll(Arrays.asList(classes)); extractInterfaces(addTo, clazz.getSuperclass()); } /** * @param eventListener the event listener to register * @return this for method chaining. */ public EventFiringWebDriver register(WebDriverEventListener eventListener) { eventListeners.add(eventListener); return this; } /** * @param eventListener the event listener to unregister * @return this for method chaining. */ public EventFiringWebDriver unregister(WebDriverEventListener eventListener) { eventListeners.remove(eventListener); return this; } public WebDriver getWrappedDriver() { if (driver instanceof WrapsDriver) { return ((WrapsDriver) driver).getWrappedDriver(); } else { return driver; } } public void get(String url) { dispatcher.beforeNavigateTo(url, driver); driver.get(url); dispatcher.afterNavigateTo(url, driver); } public String getCurrentUrl() { return driver.getCurrentUrl(); } public String getTitle() { return driver.getTitle(); } public List<WebElement> findElements(By by) { dispatcher.beforeFindBy(by, null, driver); List<WebElement> temp = driver.findElements(by); dispatcher.afterFindBy(by, null, driver); List<WebElement> result = new ArrayList<>(temp.size()); for (WebElement element : temp) { result.add(createWebElement(element)); } return result; } public WebElement findElement(By by) { dispatcher.beforeFindBy(by, null, driver); WebElement temp = driver.findElement(by); dispatcher.afterFindBy(by, null, driver); return createWebElement(temp); } public String getPageSource() { return driver.getPageSource(); } public void close() { driver.close(); } public void quit() { driver.quit(); } public Set<String> getWindowHandles() { return driver.getWindowHandles(); } public String getWindowHandle() { return driver.getWindowHandle(); } public Object executeScript(String script, Object... args) { if (driver instanceof JavascriptExecutor) { dispatcher.beforeScript(script, driver); Object[] usedArgs = unpackWrappedArgs(args); Object result = ((JavascriptExecutor) driver).executeScript(script, usedArgs); dispatcher.afterScript(script, driver); return result; } throw new UnsupportedOperationException( "Underlying driver instance does not support executing javascript"); } public Object executeAsyncScript(String script, Object... args) { if (driver instanceof JavascriptExecutor) { dispatcher.beforeScript(script, driver); Object[] usedArgs = unpackWrappedArgs(args); Object result = ((JavascriptExecutor) driver).executeAsyncScript(script, usedArgs); dispatcher.afterScript(script, driver); return result; } throw new UnsupportedOperationException( "Underlying driver instance does not support executing javascript"); } private Object[] unpackWrappedArgs(Object... args) { // Walk the args: the various drivers expect unpacked versions of the elements Object[] usedArgs = new Object[args.length]; for (int i = 0; i < args.length; i++) { usedArgs[i] = unpackWrappedElement(args[i]); } return usedArgs; } private Object unpackWrappedElement(Object arg) { if (arg instanceof List<?>) { List<?> aList = (List<?>) arg; List<Object> toReturn = new ArrayList<>(); for (Object anAList : aList) { toReturn.add(unpackWrappedElement(anAList)); } return toReturn; } else if (arg instanceof Map<?, ?>) { Map<?, ?> aMap = (Map<?, ?>) arg; Map<Object, Object> toReturn = new HashMap<>(); for (Object key : aMap.keySet()) { toReturn.put(key, unpackWrappedElement(aMap.get(key))); } return toReturn; } else if (arg instanceof EventFiringWebElement) { return ((EventFiringWebElement) arg).getWrappedElement(); } else { return arg; } } public <X> X getScreenshotAs(OutputType<X> target) throws WebDriverException { if (driver instanceof TakesScreenshot) { return ((TakesScreenshot) driver).getScreenshotAs(target); } throw new UnsupportedOperationException( "Underlying driver instance does not support taking screenshots"); } public TargetLocator switchTo() { return new EventFiringTargetLocator(driver.switchTo()); } public Navigation navigate() { return new EventFiringNavigation(driver.navigate()); } public Options manage() { return new EventFiringOptions(driver.manage()); } private WebElement createWebElement(WebElement from) { return new EventFiringWebElement(from); } public Keyboard getKeyboard() { if (driver instanceof HasInputDevices) { return new EventFiringKeyboard(driver, dispatcher); } else { throw new UnsupportedOperationException("Underlying driver does not implement advanced" + " user interactions yet."); } } public Mouse getMouse() { if (driver instanceof HasInputDevices) { return new EventFiringMouse(driver, dispatcher); } else { throw new UnsupportedOperationException("Underlying driver does not implement advanced" + " user interactions yet."); } } public TouchScreen getTouch() { if (driver instanceof HasTouchScreen) { return new EventFiringTouch(driver, dispatcher); } else { throw new UnsupportedOperationException("Underlying driver does not implement advanced" + " user interactions yet."); } } private class EventFiringWebElement implements WebElement, WrapsElement, WrapsDriver, Locatable { private final WebElement element; private final WebElement underlyingElement; private EventFiringWebElement(final WebElement element) { this.element = (WebElement) Proxy.newProxyInstance( WebDriverEventListener.class.getClassLoader(), extractInterfaces(element), new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getName().equals("getWrappedElement")) { return element; } try { return method.invoke(element, args); } catch (InvocationTargetException e) { dispatcher.onException(e.getTargetException(), driver); throw e.getTargetException(); } } } ); this.underlyingElement = element; } public void click() { dispatcher.beforeClickOn(element, driver); element.click(); dispatcher.afterClickOn(element, driver); } public void submit() { element.submit(); } public void sendKeys(CharSequence... keysToSend) { dispatcher.beforeChangeValueOf(element, driver); element.sendKeys(keysToSend); dispatcher.afterChangeValueOf(element, driver); } public void clear() { dispatcher.beforeChangeValueOf(element, driver); element.clear(); dispatcher.afterChangeValueOf(element, driver); } public String getTagName() { return element.getTagName(); } public String getAttribute(String name) { return element.getAttribute(name); } public boolean isSelected() { return element.isSelected(); } public boolean isEnabled() { return element.isEnabled(); } public String getText() { return element.getText(); } public boolean isDisplayed() { return element.isDisplayed(); } public Point getLocation() { return element.getLocation(); } public Dimension getSize() { return element.getSize(); } public String getCssValue(String propertyName) { return element.getCssValue(propertyName); } public WebElement findElement(By by) { dispatcher.beforeFindBy(by, element, driver); WebElement temp = element.findElement(by); dispatcher.afterFindBy(by, element, driver); return createWebElement(temp); } public List<WebElement> findElements(By by) { dispatcher.beforeFindBy(by, element, driver); List<WebElement> temp = element.findElements(by); dispatcher.afterFindBy(by, element, driver); List<WebElement> result = new ArrayList<>(temp.size()); for (WebElement element : temp) { result.add(createWebElement(element)); } return result; } public WebElement getWrappedElement() { return underlyingElement; } @Override public boolean equals(Object obj) { if (!(obj instanceof WebElement)) { return false; } WebElement other = (WebElement) obj; if (other instanceof WrapsElement) { other = ((WrapsElement) other).getWrappedElement(); } return underlyingElement.equals(other); } @Override public int hashCode() { return underlyingElement.hashCode(); } @Override public String toString() { return underlyingElement.toString(); } public WebDriver getWrappedDriver() { return driver; } public Coordinates getCoordinates() { return ((Locatable) underlyingElement).getCoordinates(); } public <X> X getScreenshotAs(OutputType<X> outputType) throws WebDriverException { return element.getScreenshotAs(outputType); } } private class EventFiringNavigation implements Navigation { private final WebDriver.Navigation navigation; EventFiringNavigation(Navigation navigation) { this.navigation = navigation; } public void to(String url) { dispatcher.beforeNavigateTo(url, driver); navigation.to(url); dispatcher.afterNavigateTo(url, driver); } public void to(URL url) { to(String.valueOf(url)); } public void back() { dispatcher.beforeNavigateBack(driver); navigation.back(); dispatcher.afterNavigateBack(driver); } public void forward() { dispatcher.beforeNavigateForward(driver); navigation.forward(); dispatcher.afterNavigateForward(driver); } public void refresh() { navigation.refresh(); } } private class EventFiringOptions implements Options { private Options options; private EventFiringOptions(Options options) { this.options = options; } public Logs logs() { return options.logs(); } public void addCookie(Cookie cookie) { options.addCookie(cookie); } public void deleteCookieNamed(String name) { options.deleteCookieNamed(name); } public void deleteCookie(Cookie cookie) { options.deleteCookie(cookie); } public void deleteAllCookies() { options.deleteAllCookies(); } public Set<Cookie> getCookies() { return options.getCookies(); } public Cookie getCookieNamed(String name) { return options.getCookieNamed(name); } public Timeouts timeouts() { return new EventFiringTimeouts(options.timeouts()); } public ImeHandler ime() { throw new UnsupportedOperationException("Driver does not support IME interactions"); } @Beta public Window window() { return new EventFiringWindow(options.window()); } } private class EventFiringTimeouts implements Timeouts { private final Timeouts timeouts; EventFiringTimeouts(Timeouts timeouts) { this.timeouts = timeouts; } public Timeouts implicitlyWait(long time, TimeUnit unit) { timeouts.implicitlyWait(time, unit); return this; } public Timeouts setScriptTimeout(long time, TimeUnit unit) { timeouts.setScriptTimeout(time, unit); return this; } public Timeouts pageLoadTimeout(long time, TimeUnit unit) { timeouts.pageLoadTimeout(time, unit); return this; } } private class EventFiringTargetLocator implements TargetLocator { private TargetLocator targetLocator; private EventFiringTargetLocator(TargetLocator targetLocator) { this.targetLocator = targetLocator; } public WebDriver frame(int frameIndex) { return targetLocator.frame(frameIndex); } public WebDriver frame(String frameName) { return targetLocator.frame(frameName); } public WebDriver frame(WebElement frameElement) { return targetLocator.frame(frameElement); } public WebDriver parentFrame() { return targetLocator.parentFrame(); } public WebDriver window(String windowName) { return targetLocator.window(windowName); } public WebDriver defaultContent() { return targetLocator.defaultContent(); } public WebElement activeElement() { return targetLocator.activeElement(); } public Alert alert() { return targetLocator.alert(); } } @Beta private class EventFiringWindow implements Window { private final Window window; EventFiringWindow(Window window) { this.window = window; } public void setSize(Dimension targetSize) { window.setSize(targetSize); } public void setPosition(Point targetLocation) { window.setPosition(targetLocation); } public Dimension getSize() { return window.getSize(); } public Point getPosition() { return window.getPosition(); } public void maximize() { window.maximize(); } } }
1
12,685
this shouldn't be beforeClickOn, but rather beforeSubmit? and added to WebDriverEventListener. Since submit does not synthesize the 'click' events, this isn't accurate.
SeleniumHQ-selenium
py
@@ -1,5 +1,7 @@ <h2> - Single + <% unless current_user_has_active_subscription? %> + Single + <% end %> <% if pricing_scheme == "primary" %> <%= render 'price', product: product, price: product.individual_price,
1
<h2> Single <% if pricing_scheme == "primary" %> <%= render 'price', product: product, price: product.individual_price, original_price: product.original_individual_price %> <% else %> <%= render 'price', product: product, price: product.alternate_individual_price, original_price: product.original_alternate_individual_price %> <% end %> </h2> <div class="license"> <% if pricing_scheme == "primary" %> <%= link_to new_product_purchase_path(product, variant: :individual), class: 'license-button button', id: "#{product.sku}-purchase-individual" do %> Purchase for Yourself <% end %> <% else %> <%= link_to new_product_purchase_path(product, variant: :alternate_individual), class: 'license-button button', id: "#{product.sku}-purchase-individual" do %> Purchase for Yourself <% end %> <% end %> </div>
1
6,905
Should this be I18n'd?
thoughtbot-upcase
rb
@@ -93,7 +93,7 @@ public class CheckCompatibility extends TypeUtil.CustomOrderSchemaVisitor<List<S } @Override - public List<String> struct(Types.StructType readStruct, Iterable<List<String>> fieldErrorLists) { + public ImmutableList<String> struct(Types.StructType readStruct, Iterable<List<String>> fieldErrorLists) { Preconditions.checkNotNull(readStruct, "Evaluation must start with a schema."); if (!currentType.isStructType()) {
1
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.iceberg.types; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.function.Supplier; import org.apache.iceberg.Schema; public class CheckCompatibility extends TypeUtil.CustomOrderSchemaVisitor<List<String>> { /** * Returns a list of compatibility errors for writing with the given write schema. * This includes nullability: writing optional (nullable) values to a required field is an error. * * @param readSchema a read schema * @param writeSchema a write schema * @return a list of error details, or an empty list if there are no compatibility problems */ public static List<String> writeCompatibilityErrors(Schema readSchema, Schema writeSchema) { return TypeUtil.visit(readSchema, new CheckCompatibility(writeSchema, true, true)); } /** * Returns a list of compatibility errors for writing with the given write schema. * This checks type compatibility and not nullability: writing optional (nullable) values * to a required field is not an error. To check nullability as well as types, * use {@link #writeCompatibilityErrors(Schema, Schema)}. * * @param readSchema a read schema * @param writeSchema a write schema * @return a list of error details, or an empty list if there are no compatibility problems */ public static List<String> typeCompatibilityErrors(Schema readSchema, Schema writeSchema) { return TypeUtil.visit(readSchema, new CheckCompatibility(writeSchema, true, false)); } /** * Returns a list of compatibility errors for reading with the given read schema. * * @param readSchema a read schema * @param writeSchema a write schema * @return a list of error details, or an empty list if there are no compatibility problems */ public static List<String> readCompatibilityErrors(Schema readSchema, Schema writeSchema) { return TypeUtil.visit(readSchema, new CheckCompatibility(writeSchema, false, true)); } private static final ImmutableList<String> NO_ERRORS = ImmutableList.of(); private final Schema schema; private final boolean checkOrdering; private final boolean checkNullability; // the current file schema, maintained while traversing a write schema private Type currentType; private CheckCompatibility(Schema schema, boolean checkOrdering, boolean checkNullability) { this.schema = schema; this.checkOrdering = checkOrdering; this.checkNullability = checkNullability; } @Override public List<String> schema(Schema readSchema, Supplier<List<String>> structErrors) { this.currentType = this.schema.asStruct(); try { return structErrors.get(); } finally { this.currentType = null; } } @Override public List<String> struct(Types.StructType readStruct, Iterable<List<String>> fieldErrorLists) { Preconditions.checkNotNull(readStruct, "Evaluation must start with a schema."); if (!currentType.isStructType()) { return ImmutableList.of(String.format(": %s cannot be read as a struct", currentType)); } List<String> errors = Lists.newArrayList(); for (List<String> fieldErrors : fieldErrorLists) { errors.addAll(fieldErrors); } // detect reordered fields if (checkOrdering) { Types.StructType struct = currentType.asStructType(); List<Types.NestedField> fields = struct.fields(); Map<Integer, Integer> idToOrdinal = Maps.newHashMap(); for (int i = 0; i < fields.size(); i += 1) { idToOrdinal.put(fields.get(i).fieldId(), i); } int lastOrdinal = -1; for (Types.NestedField readField : readStruct.fields()) { int id = readField.fieldId(); Types.NestedField field = struct.field(id); if (field != null) { int ordinal = idToOrdinal.get(id); if (lastOrdinal >= ordinal) { errors.add( readField.name() + " is out of order, before " + fields.get(lastOrdinal).name()); } lastOrdinal = ordinal; } } } return errors; } @Override public List<String> field(Types.NestedField readField, Supplier<List<String>> fieldErrors) { Types.StructType struct = currentType.asStructType(); Types.NestedField field = struct.field(readField.fieldId()); List<String> errors = Lists.newArrayList(); if (field == null) { if (readField.isRequired()) { return ImmutableList.of(readField.name() + " is required, but is missing"); } // if the field is optional, it will be read as nulls return NO_ERRORS; } this.currentType = field.type(); try { if (checkNullability && readField.isRequired() && field.isOptional()) { errors.add(readField.name() + " should be required, but is optional"); } for (String error : fieldErrors.get()) { if (error.startsWith(":")) { // this is the last field name before the error message errors.add(readField.name() + error); } else { // this has a nested field, add '.' for nesting errors.add(readField.name() + "." + error); } } return errors; } finally { this.currentType = struct; } } @Override public List<String> list(Types.ListType readList, Supplier<List<String>> elementErrors) { if (!currentType.isListType()) { return ImmutableList.of(String.format(": %s cannot be read as a list", currentType)); } Types.ListType list = currentType.asNestedType().asListType(); List<String> errors = Lists.newArrayList(); this.currentType = list.elementType(); try { if (readList.isElementRequired() && list.isElementOptional()) { errors.add(": elements should be required, but are optional"); } errors.addAll(elementErrors.get()); return errors; } finally { this.currentType = list; } } @Override public List<String> map(Types.MapType readMap, Supplier<List<String>> keyErrors, Supplier<List<String>> valueErrors) { if (!currentType.isMapType()) { return ImmutableList.of(String.format(": %s cannot be read as a map", currentType)); } Types.MapType map = currentType.asNestedType().asMapType(); List<String> errors = Lists.newArrayList(); try { if (readMap.isValueRequired() && map.isValueOptional()) { errors.add(": values should be required, but are optional"); } this.currentType = map.keyType(); errors.addAll(keyErrors.get()); this.currentType = map.valueType(); errors.addAll(valueErrors.get()); return errors; } finally { this.currentType = map; } } @Override public List<String> primitive(Type.PrimitiveType readPrimitive) { if (currentType.equals(readPrimitive)) { return NO_ERRORS; } if (!currentType.isPrimitiveType()) { return ImmutableList.of(String.format(": %s cannot be read as a %s", currentType.typeId().toString().toLowerCase(Locale.ENGLISH), readPrimitive)); } if (!TypeUtil.isPromotionAllowed(currentType.asPrimitiveType(), readPrimitive)) { return ImmutableList.of(String.format(": %s cannot be promoted to %s", currentType, readPrimitive)); } // both are primitives and promotion is allowed to the read type return NO_ERRORS; } }
1
17,353
We don't typically use `ImmutableList` to avoid leaking it in methods that are accidentally public or purposely part of the API. I'm +1 for returning `ImmutableList.copyOf(errors)` below, but I don't think we should guarantee the list will be an `ImmutableList`.
apache-iceberg
java
@@ -441,10 +441,18 @@ class TestCase(unittest.TestCase): m = Chem.MolFromSmiles('C1=CN=CC=C1') pkl = cPickle.dumps(m) m2 = cPickle.loads(pkl) + self.assertTrue(type(m2) == Chem.Mol) smi1 = Chem.MolToSmiles(m) smi2 = Chem.MolToSmiles(m2) self.assertTrue(smi1 == smi2) + pkl = cPickle.dumps(Chem.RWMol(m)) + m2 = cPickle.loads(pkl) + self.assertTrue(type(m2) == Chem.RWMol) + smi1 = Chem.MolToSmiles(m) + smi2 = Chem.MolToSmiles(m2) + self.assertTrue(smi1 == smi2) + def test16Props(self): m = Chem.MolFromSmiles('C1=CN=CC=C1') self.assertTrue(not m.HasProp('prop1'))
1
# # Copyright (C) 2003-2017 Greg Landrum and Rational Discovery LLC # All Rights Reserved # """ This is a rough coverage test of the python wrapper it's intended to be shallow, but broad """ from __future__ import print_function import os, sys, tempfile, gzip, gc import unittest, doctest from rdkit import RDConfig, rdBase from rdkit import DataStructs from rdkit import Chem from rdkit import six from rdkit.six import exec_ from rdkit import __version__ # Boost functions are NOT found by doctest, this "fixes" them # by adding the doctests to a fake module import imp TestReplaceCore = imp.new_module("TestReplaceCore") code = """ from rdkit.Chem import ReplaceCore def ReplaceCore(*a, **kw): '''%s ''' return Chem.ReplaceCore(*a, **kw) """ % "\n".join([x.lstrip() for x in Chem.ReplaceCore.__doc__.split("\n")]) exec_(code, TestReplaceCore.__dict__) def load_tests(loader, tests, ignore): tests.addTests(doctest.DocTestSuite(TestReplaceCore)) return tests def feq(v1, v2, tol2=1e-4): return abs(v1 - v2) <= tol2 def getTotalFormalCharge(mol): totalFormalCharge = 0 for atom in mol.GetAtoms(): totalFormalCharge += atom.GetFormalCharge() return totalFormalCharge def cmpFormalChargeBondOrder(self, mol1, mol2): self.assertEqual(mol1.GetNumAtoms(), mol2.GetNumAtoms()) self.assertEqual(mol1.GetNumBonds(), mol2.GetNumBonds()) for i in range(mol1.GetNumAtoms()): self.assertEqual( mol1.GetAtomWithIdx(i).GetFormalCharge(), mol2.GetAtomWithIdx(i).GetFormalCharge()) for i in range(mol1.GetNumBonds()): self.assertEqual(mol1.GetBondWithIdx(i).GetBondType(), mol2.GetBondWithIdx(i).GetBondType()) def setResidueFormalCharge(mol, res, fc): for query in res: matches = mol.GetSubstructMatches(query) for match in matches: mol.GetAtomWithIdx(match[-1]).SetFormalCharge(fc) def getBtList2(resMolSuppl): btList2 = [] while (not resMolSuppl.atEnd()): resMol = next(resMolSuppl) bt = [] for bond in resMol.GetBonds(): bt.append(int(bond.GetBondTypeAsDouble())) btList2.append(bt) for i in range(len(btList2)): same = True for j in range(len(btList2[i])): if (not i): continue if (same): same = (btList2[i][j] == btList2[i - 1][j]) if (i and same): return None return btList2 class TestCase(unittest.TestCase): def test0Except(self): with self.assertRaises(IndexError): Chem.tossit() def test1Table(self): tbl = Chem.GetPeriodicTable() self.assertTrue(tbl) self.assertTrue(feq(tbl.GetAtomicWeight(6), 12.011)) self.assertTrue(feq(tbl.GetAtomicWeight("C"), 12.011)) self.assertTrue(tbl.GetAtomicNumber('C') == 6) self.assertTrue(feq(tbl.GetRvdw(6), 1.950)) self.assertTrue(feq(tbl.GetRvdw("C"), 1.950)) self.assertTrue(feq(tbl.GetRcovalent(6), 0.680)) self.assertTrue(feq(tbl.GetRcovalent("C"), 0.680)) self.assertTrue(tbl.GetDefaultValence(6) == 4) self.assertTrue(tbl.GetDefaultValence("C") == 4) self.assertTrue(tuple(tbl.GetValenceList(6)) == (4, )) self.assertTrue(tuple(tbl.GetValenceList("C")) == (4, )) self.assertTrue(tuple(tbl.GetValenceList(16)) == (2, 4, 6)) self.assertTrue(tuple(tbl.GetValenceList("S")) == (2, 4, 6)) self.assertTrue(tbl.GetNOuterElecs(6) == 4) self.assertTrue(tbl.GetNOuterElecs("C") == 4) self.assertTrue(tbl.GetMostCommonIsotope(6) == 12) self.assertTrue(tbl.GetMostCommonIsotope('C') == 12) self.assertTrue(tbl.GetMostCommonIsotopeMass(6) == 12.0) self.assertTrue(tbl.GetMostCommonIsotopeMass('C') == 12.0) self.assertTrue(tbl.GetAbundanceForIsotope(6, 12) == 98.93) self.assertTrue(tbl.GetAbundanceForIsotope('C', 12) == 98.93) self.assertTrue(feq(tbl.GetRb0(6), 0.77)) self.assertTrue(feq(tbl.GetRb0("C"), 0.77)) self.assertTrue(tbl.GetElementSymbol(6) == 'C') def test2Atom(self): atom = Chem.Atom(6) self.assertTrue(atom) self.assertTrue(atom.GetAtomicNum() == 6) atom.SetAtomicNum(8) self.assertTrue(atom.GetAtomicNum() == 8) atom = Chem.Atom("C") self.assertTrue(atom) self.assertTrue(atom.GetAtomicNum() == 6) def test3Bond(self): # No longer relevant, bonds are not constructible from Python pass def test4Mol(self): mol = Chem.Mol() self.assertTrue(mol) def test5Smiles(self): mol = Chem.MolFromSmiles('n1ccccc1') self.assertTrue(mol) self.assertTrue(mol.GetNumAtoms() == 6) self.assertTrue(mol.GetNumAtoms(1) == 6) self.assertTrue(mol.GetNumAtoms(0) == 11) at = mol.GetAtomWithIdx(2) self.assertTrue(at.GetAtomicNum() == 6) at = mol.GetAtomWithIdx(0) self.assertTrue(at.GetAtomicNum() == 7) def _test6Bookmarks(self): mol = Chem.MolFromSmiles('n1ccccc1') self.assertTrue(mol) self.assertTrue(not mol.HasAtomBookmark(0)) mol.SetAtomBookmark(mol.GetAtomWithIdx(0), 0) mol.SetAtomBookmark(mol.GetAtomWithIdx(1), 1) self.assertTrue(mol.HasAtomBookmark(0)) self.assertTrue(mol.HasAtomBookmark(1)) if 1: self.assertTrue(not mol.HasBondBookmark(0)) self.assertTrue(not mol.HasBondBookmark(1)) mol.SetBondBookmark(mol.GetBondWithIdx(0), 0) mol.SetBondBookmark(mol.GetBondWithIdx(1), 1) self.assertTrue(mol.HasBondBookmark(0)) self.assertTrue(mol.HasBondBookmark(1)) at = mol.GetAtomWithBookmark(0) self.assertTrue(at) self.assertTrue(at.GetAtomicNum() == 7) mol.ClearAtomBookmark(0) self.assertTrue(not mol.HasAtomBookmark(0)) self.assertTrue(mol.HasAtomBookmark(1)) mol.ClearAllAtomBookmarks() self.assertTrue(not mol.HasAtomBookmark(0)) self.assertTrue(not mol.HasAtomBookmark(1)) mol.SetAtomBookmark(mol.GetAtomWithIdx(1), 1) if 1: self.assertTrue(mol.HasBondBookmark(0)) self.assertTrue(mol.HasBondBookmark(1)) bond = mol.GetBondWithBookmark(0) self.assertTrue(bond) mol.ClearBondBookmark(0) self.assertTrue(not mol.HasBondBookmark(0)) self.assertTrue(mol.HasBondBookmark(1)) mol.ClearAllBondBookmarks() self.assertTrue(not mol.HasBondBookmark(0)) self.assertTrue(not mol.HasBondBookmark(1)) self.assertTrue(mol.HasAtomBookmark(1)) def test7Atom(self): mol = Chem.MolFromSmiles('n1ccccc1C[CH2-]') self.assertTrue(mol) Chem.SanitizeMol(mol) a0 = mol.GetAtomWithIdx(0) a1 = mol.GetAtomWithIdx(1) a6 = mol.GetAtomWithIdx(6) a7 = mol.GetAtomWithIdx(7) self.assertTrue(a0.GetAtomicNum() == 7) self.assertTrue(a0.GetSymbol() == 'N') self.assertTrue(a0.GetIdx() == 0) aList = [a0, a1, a6, a7] self.assertTrue(a0.GetDegree() == 2) self.assertTrue(a1.GetDegree() == 2) self.assertTrue(a6.GetDegree() == 2) self.assertTrue(a7.GetDegree() == 1) self.assertTrue([x.GetDegree() for x in aList] == [2, 2, 2, 1]) self.assertTrue([x.GetTotalNumHs() for x in aList] == [0, 1, 2, 2]) self.assertTrue([x.GetNumImplicitHs() for x in aList] == [0, 1, 2, 0]) self.assertTrue([x.GetExplicitValence() for x in aList] == [3, 3, 2, 3]) self.assertTrue([x.GetImplicitValence() for x in aList] == [0, 1, 2, 0]) self.assertTrue([x.GetFormalCharge() for x in aList] == [0, 0, 0, -1]) self.assertTrue([x.GetNoImplicit() for x in aList] == [0, 0, 0, 1]) self.assertTrue([x.GetNumExplicitHs() for x in aList] == [0, 0, 0, 2]) self.assertTrue([x.GetIsAromatic() for x in aList] == [1, 1, 0, 0]) self.assertTrue([x.GetHybridization() for x in aList]==[Chem.HybridizationType.SP2,Chem.HybridizationType.SP2, Chem.HybridizationType.SP3,Chem.HybridizationType.SP3],\ [x.GetHybridization() for x in aList]) def test8Bond(self): mol = Chem.MolFromSmiles('n1ccccc1CC(=O)O') self.assertTrue(mol) Chem.SanitizeMol(mol) # note bond numbering is funny because of ring closure b0 = mol.GetBondWithIdx(0) b6 = mol.GetBondWithIdx(6) b7 = mol.GetBondWithIdx(7) b8 = mol.GetBondWithIdx(8) bList = [b0, b6, b7, b8] self.assertTrue( [x.GetBondType() for x in bList] == [Chem.BondType.AROMATIC, Chem.BondType.SINGLE, Chem.BondType.DOUBLE, Chem.BondType.SINGLE]) self.assertTrue([x.GetIsAromatic() for x in bList] == [1, 0, 0, 0]) self.assertEqual(bList[0].GetBondTypeAsDouble(), 1.5) self.assertEqual(bList[1].GetBondTypeAsDouble(), 1.0) self.assertEqual(bList[2].GetBondTypeAsDouble(), 2.0) self.assertTrue([x.GetIsConjugated() != 0 for x in bList] == [1, 0, 1, 1], [x.GetIsConjugated() != 0 for x in bList]) self.assertTrue([x.GetBeginAtomIdx() for x in bList] == [0, 6, 7, 7], [x.GetBeginAtomIdx() for x in bList]) self.assertTrue([x.GetBeginAtom().GetIdx() for x in bList] == [0, 6, 7, 7]) self.assertTrue([x.GetEndAtomIdx() for x in bList] == [1, 7, 8, 9]) self.assertTrue([x.GetEndAtom().GetIdx() for x in bList] == [1, 7, 8, 9]) def test9Smarts(self): query1 = Chem.MolFromSmarts('C(=O)O') self.assertTrue(query1) query2 = Chem.MolFromSmarts('C(=O)[O,N]') self.assertTrue(query2) query3 = Chem.MolFromSmarts('[$(C(=O)O)]') self.assertTrue(query3) mol = Chem.MolFromSmiles('CCC(=O)O') self.assertTrue(mol) self.assertTrue(mol.HasSubstructMatch(query1)) self.assertTrue(mol.HasSubstructMatch(query2)) self.assertTrue(mol.HasSubstructMatch(query3)) mol = Chem.MolFromSmiles('CCC(=O)N') self.assertTrue(mol) self.assertTrue(not mol.HasSubstructMatch(query1)) self.assertTrue(mol.HasSubstructMatch(query2)) self.assertTrue(not mol.HasSubstructMatch(query3)) def test10Iterators(self): mol = Chem.MolFromSmiles('CCOC') self.assertTrue(mol) for atom in mol.GetAtoms(): self.assertTrue(atom) ats = mol.GetAtoms() ats[1] with self.assertRaisesRegexp(IndexError, ""): ats[12] for bond in mol.GetBonds(): self.assertTrue(bond) bonds = mol.GetBonds() bonds[1] with self.assertRaisesRegexp(IndexError, ""): bonds[12] def test11MolOps(self): mol = Chem.MolFromSmiles('C1=CC=C(C=C1)P(C2=CC=CC=C2)C3=CC=CC=C3') self.assertTrue(mol) smi = Chem.MolToSmiles(mol) Chem.SanitizeMol(mol) nr = Chem.GetSymmSSSR(mol) self.assertTrue((len(nr) == 3)) def test12Smarts(self): query1 = Chem.MolFromSmarts('C(=O)O') self.assertTrue(query1) query2 = Chem.MolFromSmarts('C(=O)[O,N]') self.assertTrue(query2) query3 = Chem.MolFromSmarts('[$(C(=O)O)]') self.assertTrue(query3) mol = Chem.MolFromSmiles('CCC(=O)O') self.assertTrue(mol) self.assertTrue(mol.HasSubstructMatch(query1)) self.assertTrue(mol.GetSubstructMatch(query1) == (2, 3, 4)) self.assertTrue(mol.HasSubstructMatch(query2)) self.assertTrue(mol.GetSubstructMatch(query2) == (2, 3, 4)) self.assertTrue(mol.HasSubstructMatch(query3)) self.assertTrue(mol.GetSubstructMatch(query3) == (2, )) mol = Chem.MolFromSmiles('CCC(=O)N') self.assertTrue(mol) self.assertTrue(not mol.HasSubstructMatch(query1)) self.assertTrue(not mol.GetSubstructMatch(query1)) self.assertTrue(mol.HasSubstructMatch(query2)) self.assertTrue(mol.GetSubstructMatch(query2) == (2, 3, 4)) self.assertTrue(not mol.HasSubstructMatch(query3)) mol = Chem.MolFromSmiles('OC(=O)CC(=O)O') self.assertTrue(mol) self.assertTrue(mol.HasSubstructMatch(query1)) self.assertTrue(mol.GetSubstructMatch(query1) == (1, 2, 0)) self.assertTrue(mol.GetSubstructMatches(query1) == ((1, 2, 0), (4, 5, 6))) self.assertTrue(mol.HasSubstructMatch(query2)) self.assertTrue(mol.GetSubstructMatch(query2) == (1, 2, 0)) self.assertTrue(mol.GetSubstructMatches(query2) == ((1, 2, 0), (4, 5, 6))) self.assertTrue(mol.HasSubstructMatch(query3)) self.assertTrue(mol.GetSubstructMatches(query3) == ((1, ), (4, ))) def test13Smarts(self): # previous smarts problems: query = Chem.MolFromSmarts('N(=,-C)') self.assertTrue(query) mol = Chem.MolFromSmiles('N#C') self.assertTrue(not mol.HasSubstructMatch(query)) mol = Chem.MolFromSmiles('N=C') self.assertTrue(mol.HasSubstructMatch(query)) mol = Chem.MolFromSmiles('NC') self.assertTrue(mol.HasSubstructMatch(query)) query = Chem.MolFromSmarts('[Cl,$(O)]') mol = Chem.MolFromSmiles('C(=O)O') self.assertTrue(len(mol.GetSubstructMatches(query)) == 2) mol = Chem.MolFromSmiles('C(=N)N') self.assertTrue(len(mol.GetSubstructMatches(query)) == 0) query = Chem.MolFromSmarts('[$([O,S]-[!$(*=O)])]') mol = Chem.MolFromSmiles('CC(S)C(=O)O') self.assertTrue(len(mol.GetSubstructMatches(query)) == 1) mol = Chem.MolFromSmiles('C(=O)O') self.assertTrue(len(mol.GetSubstructMatches(query)) == 0) def test14Hs(self): m = Chem.MolFromSmiles('CC(=O)[OH]') self.assertEqual(m.GetNumAtoms(), 4) m2 = Chem.AddHs(m) self.assertEqual(m2.GetNumAtoms(), 8) m2 = Chem.RemoveHs(m2) self.assertEqual(m2.GetNumAtoms(), 4) m = Chem.MolFromSmiles('CC[H]', False) self.assertEqual(m.GetNumAtoms(), 3) m2 = Chem.MergeQueryHs(m) self.assertEqual(m2.GetNumAtoms(), 2) self.assertTrue(m2.GetAtomWithIdx(1).HasQuery()) m = Chem.MolFromSmiles('CC[H]', False) self.assertEqual(m.GetNumAtoms(), 3) m1 = Chem.RemoveHs(m) self.assertEqual(m1.GetNumAtoms(), 2) self.assertEqual(m1.GetAtomWithIdx(1).GetNumExplicitHs(), 0) m1 = Chem.RemoveHs(m, updateExplicitCount=True) self.assertEqual(m1.GetNumAtoms(), 2) self.assertEqual(m1.GetAtomWithIdx(1).GetNumExplicitHs(), 1) # test merging of mapped hydrogens m = Chem.MolFromSmiles('CC[H]', False) m.GetAtomWithIdx(2).SetProp("molAtomMapNumber", "1") self.assertEqual(m.GetNumAtoms(), 3) m2 = Chem.MergeQueryHs(m, mergeUnmappedOnly=True) self.assertTrue(m2 is not None) self.assertEqual(m2.GetNumAtoms(), 3) self.assertFalse(m2.GetAtomWithIdx(1).HasQuery()) # here the hydrogen is unmapped # should be the same as merging all hydrogens m = Chem.MolFromSmiles('CC[H]', False) m.GetAtomWithIdx(1).SetProp("molAtomMapNumber", "1") self.assertEqual(m.GetNumAtoms(), 3) m2 = Chem.MergeQueryHs(m, mergeUnmappedOnly=True) self.assertTrue(m2 is not None) self.assertEqual(m2.GetNumAtoms(), 2) self.assertTrue(m2.GetAtomWithIdx(1).HasQuery()) # test github758 m = Chem.MolFromSmiles('CCC') self.assertEqual(m.GetNumAtoms(), 3) m = Chem.AddHs(m, onlyOnAtoms=(0, 2)) self.assertEqual(m.GetNumAtoms(), 9) self.assertEqual(m.GetAtomWithIdx(0).GetDegree(), 4) self.assertEqual(m.GetAtomWithIdx(2).GetDegree(), 4) self.assertEqual(m.GetAtomWithIdx(1).GetDegree(), 2) def test15Neighbors(self): m = Chem.MolFromSmiles('CC(=O)[OH]') self.assertTrue(m.GetNumAtoms() == 4) a = m.GetAtomWithIdx(1) ns = a.GetNeighbors() self.assertTrue(len(ns) == 3) bs = a.GetBonds() self.assertTrue(len(bs) == 3) for b in bs: try: a2 = b.GetOtherAtom(a) except Exception: a2 = None self.assertTrue(a2) self.assertTrue(len(bs) == 3) def test16Pickle(self): from rdkit.six.moves import cPickle m = Chem.MolFromSmiles('C1=CN=CC=C1') pkl = cPickle.dumps(m) m2 = cPickle.loads(pkl) smi1 = Chem.MolToSmiles(m) smi2 = Chem.MolToSmiles(m2) self.assertTrue(smi1 == smi2) def test16Props(self): m = Chem.MolFromSmiles('C1=CN=CC=C1') self.assertTrue(not m.HasProp('prop1')) self.assertTrue(not m.HasProp('prop2')) self.assertTrue(not m.HasProp('prop2')) m.SetProp('prop1', 'foob') self.assertTrue(not m.HasProp('prop2')) self.assertTrue(m.HasProp('prop1')) self.assertTrue(m.GetProp('prop1') == 'foob') self.assertTrue(not m.HasProp('propo')) try: m.GetProp('prop2') except KeyError: ok = 1 else: ok = 0 self.assertTrue(ok) # test computed properties m.SetProp('cprop1', 'foo', 1) m.SetProp('cprop2', 'foo2', 1) m.ClearComputedProps() self.assertTrue(not m.HasProp('cprop1')) self.assertTrue(not m.HasProp('cprop2')) m.SetDoubleProp("a", 2.0) self.assertTrue(m.GetDoubleProp("a") == 2.0) try: self.assertTrue(m.GetIntProp("a") == 2.0) raise Exception("Expected runtime exception") except ValueError: pass try: self.assertTrue(m.GetUnsignedProp("a") == 2.0) raise Exception("Expected runtime exception") except ValueError: pass m.SetDoubleProp("a", -2) self.assertTrue(m.GetDoubleProp("a") == -2.0) m.SetIntProp("a", -2) self.assertTrue(m.GetIntProp("a") == -2) try: m.SetUnsignedProp("a", -2) raise Exception("Expected failure with negative unsigned number") except OverflowError: pass m.SetBoolProp("a", False) self.assertTrue(m.GetBoolProp("a") == False) self.assertEquals(m.GetPropsAsDict(), {'a': False, 'prop1': 'foob'}) m.SetDoubleProp("b", 1000.0) m.SetUnsignedProp("c", 2000) m.SetIntProp("d", -2) m.SetUnsignedProp("e", 2, True) self.assertEquals( m.GetPropsAsDict(False, True), { 'a': False, 'c': 2000, 'b': 1000.0, 'e': 2, 'd': -2, 'prop1': 'foob' }) m = Chem.MolFromSmiles('C1=CN=CC=C1') m.SetProp("int", "1000") m.SetProp("double", "10000.123") print(m.GetPropsAsDict()) self.assertEquals(m.GetPropsAsDict(), {"int": 1000, "double": 10000.123}) self.assertEquals(type(m.GetPropsAsDict()['int']), int) self.assertEquals(type(m.GetPropsAsDict()['double']), float) def test17Kekulize(self): m = Chem.MolFromSmiles('c1ccccc1') smi = Chem.MolToSmiles(m) self.assertTrue(smi == 'c1ccccc1') Chem.Kekulize(m) smi = Chem.MolToSmiles(m) self.assertTrue(smi == 'c1ccccc1') m = Chem.MolFromSmiles('c1ccccc1') smi = Chem.MolToSmiles(m) self.assertTrue(smi == 'c1ccccc1') Chem.Kekulize(m, 1) smi = Chem.MolToSmiles(m) self.assertTrue(smi == 'C1=CC=CC=C1', smi) def test18Paths(self): m = Chem.MolFromSmiles("C1CC2C1CC2") #self.assertTrue(len(Chem.FindAllPathsOfLengthN(m,1,useBonds=1))==7) #print(Chem.FindAllPathsOfLengthN(m,3,useBonds=0)) self.assertTrue( len(Chem.FindAllPathsOfLengthN(m, 2, useBonds=1)) == 10, Chem.FindAllPathsOfLengthN(m, 2, useBonds=1)) self.assertTrue(len(Chem.FindAllPathsOfLengthN(m, 3, useBonds=1)) == 14) m = Chem.MolFromSmiles('C1CC1C') self.assertTrue(m) self.assertTrue(len(Chem.FindAllPathsOfLengthN(m, 1, useBonds=1)) == 4) self.assertTrue(len(Chem.FindAllPathsOfLengthN(m, 2, useBonds=1)) == 5) self.assertTrue( len(Chem.FindAllPathsOfLengthN(m, 3, useBonds=1)) == 3, Chem.FindAllPathsOfLengthN(m, 3, useBonds=1)) self.assertTrue( len(Chem.FindAllPathsOfLengthN(m, 4, useBonds=1)) == 1, Chem.FindAllPathsOfLengthN(m, 4, useBonds=1)) self.assertTrue( len(Chem.FindAllPathsOfLengthN(m, 5, useBonds=1)) == 0, Chem.FindAllPathsOfLengthN(m, 5, useBonds=1)) # # Hexane example from Hall-Kier Rev.Comp.Chem. paper # Rev. Comp. Chem. vol 2, 367-422, (1991) # m = Chem.MolFromSmiles("CCCCCC") self.assertTrue(len(Chem.FindAllPathsOfLengthN(m, 1, useBonds=1)) == 5) self.assertTrue(len(Chem.FindAllPathsOfLengthN(m, 2, useBonds=1)) == 4) self.assertTrue(len(Chem.FindAllPathsOfLengthN(m, 3, useBonds=1)) == 3) m = Chem.MolFromSmiles("CCC(C)CC") self.assertTrue(len(Chem.FindAllPathsOfLengthN(m, 1, useBonds=1)) == 5) self.assertTrue(len(Chem.FindAllPathsOfLengthN(m, 2, useBonds=1)) == 5) self.assertTrue( len(Chem.FindAllPathsOfLengthN(m, 3, useBonds=1)) == 4, Chem.FindAllPathsOfLengthN(m, 3, useBonds=1)) m = Chem.MolFromSmiles("CCCC(C)C") self.assertTrue(len(Chem.FindAllPathsOfLengthN(m, 1, useBonds=1)) == 5) self.assertTrue(len(Chem.FindAllPathsOfLengthN(m, 2, useBonds=1)) == 5) self.assertTrue(len(Chem.FindAllPathsOfLengthN(m, 3, useBonds=1)) == 3) m = Chem.MolFromSmiles("CC(C)C(C)C") self.assertTrue(len(Chem.FindAllPathsOfLengthN(m, 1, useBonds=1)) == 5) self.assertTrue(len(Chem.FindAllPathsOfLengthN(m, 2, useBonds=1)) == 6) self.assertTrue(len(Chem.FindAllPathsOfLengthN(m, 3, useBonds=1)) == 4) m = Chem.MolFromSmiles("CC(C)(C)CC") self.assertTrue(len(Chem.FindAllPathsOfLengthN(m, 1, useBonds=1)) == 5) self.assertTrue(len(Chem.FindAllPathsOfLengthN(m, 2, useBonds=1)) == 7) self.assertTrue( len(Chem.FindAllPathsOfLengthN(m, 3, useBonds=1)) == 3, Chem.FindAllPathsOfLengthN(m, 3, useBonds=1)) m = Chem.MolFromSmiles("C1CCCCC1") self.assertTrue(len(Chem.FindAllPathsOfLengthN(m, 1, useBonds=1)) == 6) self.assertTrue(len(Chem.FindAllPathsOfLengthN(m, 2, useBonds=1)) == 6) self.assertTrue(len(Chem.FindAllPathsOfLengthN(m, 3, useBonds=1)) == 6) m = Chem.MolFromSmiles("C1CC2C1CC2") self.assertTrue(len(Chem.FindAllPathsOfLengthN(m, 1, useBonds=1)) == 7) self.assertTrue( len(Chem.FindAllPathsOfLengthN(m, 2, useBonds=1)) == 10, Chem.FindAllPathsOfLengthN(m, 2, useBonds=1)) self.assertTrue(len(Chem.FindAllPathsOfLengthN(m, 3, useBonds=1)) == 14) m = Chem.MolFromSmiles("CC2C1CCC12") self.assertTrue(len(Chem.FindAllPathsOfLengthN(m, 1, useBonds=1)) == 7) self.assertTrue(len(Chem.FindAllPathsOfLengthN(m, 2, useBonds=1)) == 11) # FIX: this result disagrees with the paper (which says 13), # but it seems right self.assertTrue( len(Chem.FindAllPathsOfLengthN(m, 3, useBonds=1)) == 15, Chem.FindAllPathsOfLengthN(m, 3, useBonds=1)) def test19Subgraphs(self): m = Chem.MolFromSmiles('C1CC1C') self.assertTrue(m) self.assertTrue(len(Chem.FindAllSubgraphsOfLengthN(m, 1, 0)) == 4) self.assertTrue(len(Chem.FindAllSubgraphsOfLengthN(m, 2)) == 5) self.assertTrue(len(Chem.FindAllSubgraphsOfLengthN(m, 3)) == 4) self.assertTrue(len(Chem.FindAllSubgraphsOfLengthN(m, 4)) == 1) self.assertTrue(len(Chem.FindAllSubgraphsOfLengthN(m, 5)) == 0) # # Hexane example from Hall-Kier Rev.Comp.Chem. paper # Rev. Comp. Chem. vol 2, 367-422, (1991) # m = Chem.MolFromSmiles("CCCCCC") self.assertTrue(len(Chem.FindAllSubgraphsOfLengthN(m, 1)) == 5) self.assertTrue(len(Chem.FindAllSubgraphsOfLengthN(m, 2)) == 4) self.assertTrue(len(Chem.FindAllSubgraphsOfLengthN(m, 3)) == 3) l = Chem.FindAllSubgraphsOfLengthMToN(m, 1, 3) self.assertEqual(len(l), 3) self.assertEqual(len(l[0]), 5) self.assertEqual(len(l[1]), 4) self.assertEqual(len(l[2]), 3) self.assertRaises(ValueError, lambda: Chem.FindAllSubgraphsOfLengthMToN(m, 4, 3)) m = Chem.MolFromSmiles("CCC(C)CC") self.assertTrue(len(Chem.FindAllSubgraphsOfLengthN(m, 1)) == 5) self.assertTrue(len(Chem.FindAllSubgraphsOfLengthN(m, 2)) == 5) self.assertTrue(len(Chem.FindAllSubgraphsOfLengthN(m, 3)) == 5) m = Chem.MolFromSmiles("CCCC(C)C") self.assertTrue(len(Chem.FindAllSubgraphsOfLengthN(m, 1)) == 5) self.assertTrue(len(Chem.FindAllSubgraphsOfLengthN(m, 2)) == 5) self.assertTrue(len(Chem.FindAllSubgraphsOfLengthN(m, 3)) == 4) m = Chem.MolFromSmiles("CC(C)C(C)C") self.assertTrue(len(Chem.FindAllSubgraphsOfLengthN(m, 1)) == 5) self.assertTrue(len(Chem.FindAllSubgraphsOfLengthN(m, 2)) == 6) self.assertTrue(len(Chem.FindAllSubgraphsOfLengthN(m, 3)) == 6) m = Chem.MolFromSmiles("CC(C)(C)CC") self.assertTrue(len(Chem.FindAllSubgraphsOfLengthN(m, 1)) == 5) self.assertTrue(len(Chem.FindAllSubgraphsOfLengthN(m, 2)) == 7) self.assertTrue( len(Chem.FindAllSubgraphsOfLengthN(m, 3)) == 7, Chem.FindAllSubgraphsOfLengthN(m, 3)) m = Chem.MolFromSmiles("C1CCCCC1") self.assertTrue(len(Chem.FindAllSubgraphsOfLengthN(m, 1)) == 6) self.assertTrue(len(Chem.FindAllSubgraphsOfLengthN(m, 2)) == 6) self.assertTrue(len(Chem.FindAllSubgraphsOfLengthN(m, 3)) == 6) #self.assertTrue(len(Chem.FindUniqueSubgraphsOfLengthN(m,1))==1) self.assertTrue(len(Chem.FindUniqueSubgraphsOfLengthN(m, 2)) == 1) self.assertTrue(len(Chem.FindUniqueSubgraphsOfLengthN(m, 3)) == 1) m = Chem.MolFromSmiles("C1CC2C1CC2") self.assertTrue(len(Chem.FindAllSubgraphsOfLengthN(m, 1)) == 7) self.assertTrue(len(Chem.FindAllSubgraphsOfLengthN(m, 2)) == 10) self.assertTrue(len(Chem.FindAllSubgraphsOfLengthN(m, 3)) == 16) m = Chem.MolFromSmiles("CC2C1CCC12") self.assertTrue(len(Chem.FindAllSubgraphsOfLengthN(m, 1)) == 7) self.assertTrue(len(Chem.FindAllSubgraphsOfLengthN(m, 2)) == 11) self.assertTrue( len(Chem.FindAllSubgraphsOfLengthN(m, 3)) == 18, len(Chem.FindAllSubgraphsOfLengthN(m, 3))) def test20IsInRing(self): m = Chem.MolFromSmiles('C1CCC1C') self.assertTrue(m) self.assertTrue(m.GetAtomWithIdx(0).IsInRingSize(4)) self.assertTrue(m.GetAtomWithIdx(1).IsInRingSize(4)) self.assertTrue(m.GetAtomWithIdx(2).IsInRingSize(4)) self.assertTrue(m.GetAtomWithIdx(3).IsInRingSize(4)) self.assertTrue(not m.GetAtomWithIdx(4).IsInRingSize(4)) self.assertTrue(not m.GetAtomWithIdx(0).IsInRingSize(3)) self.assertTrue(not m.GetAtomWithIdx(1).IsInRingSize(3)) self.assertTrue(not m.GetAtomWithIdx(2).IsInRingSize(3)) self.assertTrue(not m.GetAtomWithIdx(3).IsInRingSize(3)) self.assertTrue(not m.GetAtomWithIdx(4).IsInRingSize(3)) self.assertTrue(m.GetBondWithIdx(0).IsInRingSize(4)) self.assertTrue(not m.GetBondWithIdx(3).IsInRingSize(4)) self.assertTrue(not m.GetBondWithIdx(0).IsInRingSize(3)) self.assertTrue(not m.GetBondWithIdx(3).IsInRingSize(3)) def test21Robustification(self): ok = False # FIX: at the moment I can't figure out how to catch the # actual exception that BPL is throwinng when it gets # invalid arguments (Boost.Python.ArgumentError) try: Chem.MolFromSmiles('C=O').HasSubstructMatch(Chem.MolFromSmarts('fiib')) #except ValueError: # ok=True except Exception: ok = True self.assertTrue(ok) def test22DeleteSubstruct(self): query = Chem.MolFromSmarts('C(=O)O') mol = Chem.MolFromSmiles('CCC(=O)O') nmol = Chem.DeleteSubstructs(mol, query) self.assertTrue(Chem.MolToSmiles(nmol) == 'CC') mol = Chem.MolFromSmiles('CCC(=O)O.O=CO') # now delete only fragments nmol = Chem.DeleteSubstructs(mol, query, 1) self.assertTrue(Chem.MolToSmiles(nmol) == 'CCC(=O)O', Chem.MolToSmiles(nmol)) mol = Chem.MolFromSmiles('CCC(=O)O.O=CO') nmol = Chem.DeleteSubstructs(mol, query, 0) self.assertTrue(Chem.MolToSmiles(nmol) == 'CC') mol = Chem.MolFromSmiles('CCCO') nmol = Chem.DeleteSubstructs(mol, query, 0) self.assertTrue(Chem.MolToSmiles(nmol) == 'CCCO') # Issue 96 prevented this from working: mol = Chem.MolFromSmiles('CCC(=O)O.O=CO') nmol = Chem.DeleteSubstructs(mol, query, 1) self.assertTrue(Chem.MolToSmiles(nmol) == 'CCC(=O)O') nmol = Chem.DeleteSubstructs(nmol, query, 1) self.assertTrue(Chem.MolToSmiles(nmol) == 'CCC(=O)O') nmol = Chem.DeleteSubstructs(nmol, query, 0) self.assertTrue(Chem.MolToSmiles(nmol) == 'CC') def test23MolFileParsing(self): fileN = os.path.join(RDConfig.RDBaseDir, 'Code', 'GraphMol', 'FileParsers', 'test_data', 'triazine.mol') #fileN = "../FileParsers/test_data/triazine.mol" with open(fileN, 'r') as inF: inD = inF.read() m1 = Chem.MolFromMolBlock(inD) self.assertTrue(m1 is not None) self.assertTrue(m1.GetNumAtoms() == 9) m1 = Chem.MolFromMolFile(fileN) self.assertTrue(m1 is not None) self.assertTrue(m1.GetNumAtoms() == 9) fileN = os.path.join(RDConfig.RDBaseDir, 'Code', 'GraphMol', 'FileParsers', 'test_data', 'triazine.mof') self.assertRaises(IOError, lambda: Chem.MolFromMolFile(fileN)) fileN = os.path.join(RDConfig.RDBaseDir, 'Code', 'GraphMol', 'FileParsers', 'test_data', 'list-query.mol') query = Chem.MolFromMolFile(fileN) smi = Chem.MolToSmiles(query) self.assertEqual(smi, 'c1ccccc1') smi = Chem.MolToSmarts(query) self.assertEqual(smi, '[#6]1:[#6]:[#6]:[#6]:[#6]:[#6,#7,#15]:1', smi) query = Chem.MolFromMolFile(fileN, sanitize=False) smi = Chem.MolToSmiles(query) self.assertEqual(smi, 'C1=CC=CC=C1') query.UpdatePropertyCache() smi = Chem.MolToSmarts(query) self.assertEqual(smi, '[#6]1=[#6]-[#6]=[#6]-[#6]=[#6,#7,#15]-1') smi = "C1=CC=CC=C1" mol = Chem.MolFromSmiles(smi, 0) self.assertTrue(mol.HasSubstructMatch(query)) Chem.SanitizeMol(mol) self.assertTrue(not mol.HasSubstructMatch(query)) mol = Chem.MolFromSmiles('N1=CC=CC=C1', 0) self.assertTrue(mol.HasSubstructMatch(query)) mol = Chem.MolFromSmiles('S1=CC=CC=C1', 0) self.assertTrue(not mol.HasSubstructMatch(query)) mol = Chem.MolFromSmiles('P1=CC=CC=C1', 0) self.assertTrue(mol.HasSubstructMatch(query)) fileN = os.path.join(RDConfig.RDBaseDir, 'Code', 'GraphMol', 'FileParsers', 'test_data', 'issue123.mol') mol = Chem.MolFromMolFile(fileN) self.assertTrue(mol) self.assertEqual(mol.GetNumAtoms(), 23) mol = Chem.MolFromMolFile(fileN, removeHs=False) self.assertTrue(mol) self.assertEqual(mol.GetNumAtoms(), 39) # test23 was for Chem.DaylightFingerprint, which is deprecated def test24RDKFingerprint(self): from rdkit import DataStructs m1 = Chem.MolFromSmiles('C1=CC=CC=C1') fp1 = Chem.RDKFingerprint(m1) self.assertTrue(len(fp1) == 2048) m2 = Chem.MolFromSmiles('C1=CC=CC=C1') fp2 = Chem.RDKFingerprint(m2) tmp = DataStructs.TanimotoSimilarity(fp1, fp2) self.assertTrue(tmp == 1.0, tmp) m2 = Chem.MolFromSmiles('C1=CC=CC=N1') fp2 = Chem.RDKFingerprint(m2) self.assertTrue(len(fp2) == 2048) tmp = DataStructs.TanimotoSimilarity(fp1, fp2) self.assertTrue(tmp < 1.0, tmp) self.assertTrue(tmp > 0.0, tmp) fp3 = Chem.RDKFingerprint(m1, tgtDensity=0.3) self.assertTrue(len(fp3) < 2048) m1 = Chem.MolFromSmiles('C1=CC=CC=C1') fp1 = Chem.RDKFingerprint(m1) m2 = Chem.MolFromSmiles('C1=CC=CC=N1') fp2 = Chem.RDKFingerprint(m2) self.assertNotEqual(fp1, fp2) atomInvariants = [1] * 6 fp1 = Chem.RDKFingerprint(m1, atomInvariants=atomInvariants) fp2 = Chem.RDKFingerprint(m2, atomInvariants=atomInvariants) self.assertEqual(fp1, fp2) m2 = Chem.MolFromSmiles('C1CCCCN1') fp1 = Chem.RDKFingerprint(m1, atomInvariants=atomInvariants, useBondOrder=False) fp2 = Chem.RDKFingerprint(m2, atomInvariants=atomInvariants, useBondOrder=False) self.assertEqual(fp1, fp2) # rooted at atom m1 = Chem.MolFromSmiles('CCCCCO') fp1 = Chem.RDKFingerprint(m1, 1, 4, nBitsPerHash=1, fromAtoms=[0]) self.assertEqual(fp1.GetNumOnBits(), 4) m1 = Chem.MolFromSmiles('CCCCCO') fp1 = Chem.RDKFingerprint(m1, 1, 4, nBitsPerHash=1, fromAtoms=[0, 5]) self.assertEqual(fp1.GetNumOnBits(), 8) # test sf.net issue 270: fp1 = Chem.RDKFingerprint(m1, atomInvariants=[x.GetAtomicNum() + 10 for x in m1.GetAtoms()]) # atomBits m1 = Chem.MolFromSmiles('CCCO') l = [] fp1 = Chem.RDKFingerprint(m1, minPath=1, maxPath=2, nBitsPerHash=1, atomBits=l) self.assertEqual(fp1.GetNumOnBits(), 4) self.assertEqual(len(l), m1.GetNumAtoms()) self.assertEqual(len(l[0]), 2) self.assertEqual(len(l[1]), 3) self.assertEqual(len(l[2]), 4) self.assertEqual(len(l[3]), 2) def test25SDMolSupplier(self): fileN = os.path.join(RDConfig.RDBaseDir, 'Code', 'GraphMol', 'FileParsers', 'test_data', 'NCI_aids_few.sdf') #fileN = "../FileParsers/test_data/NCI_aids_few.sdf" sdSup = Chem.SDMolSupplier(fileN) molNames = [ "48", "78", "128", "163", "164", "170", "180", "186", "192", "203", "210", "211", "213", "220", "229", "256" ] chgs192 = {8: 1, 11: 1, 15: -1, 18: -1, 20: 1, 21: 1, 23: -1, 25: -1} i = 0 for mol in sdSup: self.assertTrue(mol) self.assertTrue(mol.GetProp("_Name") == molNames[i]) i += 1 if (mol.GetProp("_Name") == "192"): # test parsed charges on one of the molecules for id in chgs192.keys(): self.assertTrue(mol.GetAtomWithIdx(id).GetFormalCharge() == chgs192[id]) self.assertRaises(StopIteration, lambda: six.next(sdSup)) sdSup.reset() ns = [mol.GetProp("_Name") for mol in sdSup] self.assertTrue(ns == molNames) sdSup = Chem.SDMolSupplier(fileN, 0) for mol in sdSup: self.assertTrue(not mol.HasProp("numArom")) sdSup = Chem.SDMolSupplier(fileN) self.assertTrue(len(sdSup) == 16) mol = sdSup[5] self.assertTrue(mol.GetProp("_Name") == "170") # test handling of H removal: fileN = os.path.join(RDConfig.RDBaseDir, 'Code', 'GraphMol', 'FileParsers', 'test_data', 'withHs.sdf') sdSup = Chem.SDMolSupplier(fileN) m = six.next(sdSup) self.assertTrue(m) self.assertTrue(m.GetNumAtoms() == 23) m = six.next(sdSup) self.assertTrue(m) self.assertTrue(m.GetNumAtoms() == 28) sdSup = Chem.SDMolSupplier(fileN, removeHs=False) m = six.next(sdSup) self.assertTrue(m) self.assertTrue(m.GetNumAtoms() == 39) m = six.next(sdSup) self.assertTrue(m) self.assertTrue(m.GetNumAtoms() == 30) with open(fileN, 'rb') as dFile: d = dFile.read() sdSup.SetData(d) m = six.next(sdSup) self.assertTrue(m) self.assertTrue(m.GetNumAtoms() == 23) m = six.next(sdSup) self.assertTrue(m) self.assertTrue(m.GetNumAtoms() == 28) sdSup.SetData(d, removeHs=False) m = six.next(sdSup) self.assertTrue(m) self.assertTrue(m.GetNumAtoms() == 39) m = six.next(sdSup) self.assertTrue(m) self.assertTrue(m.GetNumAtoms() == 30) # test strictParsing1: fileN = os.path.join(RDConfig.RDBaseDir, 'Code', 'GraphMol', 'FileParsers', 'test_data', 'strictLax1.sdf') #strict from file sdSup = Chem.SDMolSupplier(fileN, strictParsing=True) i = 0 for mol in sdSup: self.assertTrue(mol.HasProp("_Name")) if (i == 0): self.assertTrue(not mol.HasProp("ID")) self.assertTrue(not mol.HasProp("ANOTHER_PROPERTY")) i += 1 self.assertTrue(i == 2) #lax from file sdSup = Chem.SDMolSupplier(fileN, strictParsing=False) i = 0 for mol in sdSup: self.assertTrue(mol.HasProp("_Name")) self.assertTrue(mol.HasProp("ID")) self.assertTrue(mol.HasProp("ANOTHER_PROPERTY")) i += 1 self.assertTrue(i == 2) #strict from text with open(fileN, 'rb') as dFile: d = dFile.read() sdSup = Chem.SDMolSupplier() sdSup.SetData(d, strictParsing=True) i = 0 for mol in sdSup: self.assertTrue(mol.HasProp("_Name")) if (i == 0): self.assertTrue(not mol.HasProp("ID")) self.assertTrue(not mol.HasProp("ANOTHER_PROPERTY")) i += 1 self.assertTrue(i == 2) #lax from text sdSup = Chem.SDMolSupplier() sdSup.SetData(d, strictParsing=False) i = 0 for mol in sdSup: self.assertTrue(mol.HasProp("_Name")) self.assertTrue(mol.HasProp("ID")) self.assertTrue(mol.HasProp("ANOTHER_PROPERTY")) i += 1 self.assertTrue(i == 2) # test strictParsing2: fileN = os.path.join(RDConfig.RDBaseDir, 'Code', 'GraphMol', 'FileParsers', 'test_data', 'strictLax2.sdf') #strict from file sdSup = Chem.SDMolSupplier(fileN, strictParsing=True) i = 0 for mol in sdSup: self.assertTrue(mol.HasProp("_Name")) self.assertTrue(mol.HasProp("ID")) self.assertTrue(mol.GetProp("ID") == "Lig1") self.assertTrue(mol.HasProp("ANOTHER_PROPERTY")) self.assertTrue(mol.GetProp("ANOTHER_PROPERTY") == \ "No blank line before dollars\n" \ "$$$$\n" \ "Structure1\n" \ "csChFnd70/05230312262D") i += 1 self.assertTrue(i == 1) #lax from file sdSup = Chem.SDMolSupplier(fileN, strictParsing=False) i = 0 for mol in sdSup: self.assertTrue(mol.HasProp("_Name")) self.assertTrue(mol.HasProp("ID")) self.assertTrue(mol.GetProp("ID") == "Lig2") self.assertTrue(mol.HasProp("ANOTHER_PROPERTY")) self.assertTrue(mol.GetProp("ANOTHER_PROPERTY") == "Value2") i += 1 self.assertTrue(i == 1) #strict from text with open(fileN, 'rb') as dFile: d = dFile.read() sdSup = Chem.SDMolSupplier() sdSup.SetData(d, strictParsing=True) i = 0 for mol in sdSup: self.assertTrue(mol.HasProp("_Name")) self.assertTrue(mol.HasProp("ID")) self.assertTrue(mol.GetProp("ID") == "Lig1") self.assertTrue(mol.HasProp("ANOTHER_PROPERTY")) self.assertTrue(mol.GetProp("ANOTHER_PROPERTY") == \ "No blank line before dollars\n" \ "$$$$\n" \ "Structure1\n" \ "csChFnd70/05230312262D") i += 1 self.assertTrue(i == 1) #lax from text sdSup = Chem.SDMolSupplier() sdSup.SetData(d, strictParsing=False) i = 0 for mol in sdSup: self.assertTrue(mol.HasProp("_Name")) self.assertTrue(mol.HasProp("ID")) self.assertTrue(mol.GetProp("ID") == "Lig2") self.assertTrue(mol.HasProp("ANOTHER_PROPERTY")) self.assertTrue(mol.GetProp("ANOTHER_PROPERTY") == "Value2") i += 1 self.assertTrue(i == 1) def test26SmiMolSupplier(self): fileN = os.path.join(RDConfig.RDBaseDir, 'Code', 'GraphMol', 'FileParsers', 'test_data', 'first_200.tpsa.csv') #fileN = "../FileParsers/test_data/first_200.tpsa.csv" smiSup = Chem.SmilesMolSupplier(fileN, ",", 0, -1) mol = smiSup[16] self.assertTrue(mol.GetProp("TPSA") == "46.25") mol = smiSup[8] self.assertTrue(mol.GetProp("TPSA") == "65.18") self.assertTrue(len(smiSup) == 200) fileN = os.path.join(RDConfig.RDBaseDir, 'Code', 'GraphMol', 'FileParsers', 'test_data', 'fewSmi.csv') #fileN = "../FileParsers/test_data/fewSmi.csv" smiSup = Chem.SmilesMolSupplier(fileN, delimiter=",", smilesColumn=1, nameColumn=0, titleLine=0) names = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"] i = 0 for mol in smiSup: self.assertTrue(mol.GetProp("_Name") == names[i]) i += 1 mol = smiSup[3] self.assertTrue(mol.GetProp("_Name") == "4") self.assertTrue(mol.GetProp("Column_2") == "82.78") # and test doing a supplier from text: with open(fileN, 'r') as inF: inD = inF.read() smiSup.SetData(inD, delimiter=",", smilesColumn=1, nameColumn=0, titleLine=0) names = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"] i = 0 # iteration interface: for mol in smiSup: self.assertTrue(mol.GetProp("_Name") == names[i]) i += 1 self.assertTrue(i == 10) # random access: mol = smiSup[3] self.assertTrue(len(smiSup) == 10) self.assertTrue(mol.GetProp("_Name") == "4") self.assertTrue(mol.GetProp("Column_2") == "82.78") # issue 113: smiSup.SetData(inD, delimiter=",", smilesColumn=1, nameColumn=0, titleLine=0) self.assertTrue(len(smiSup) == 10) # and test failure handling: inD = """mol-1,CCC mol-2,CCCC mol-3,fail mol-4,CCOC """ smiSup.SetData(inD, delimiter=",", smilesColumn=1, nameColumn=0, titleLine=0) # there are 4 entries in the supplier: self.assertTrue(len(smiSup) == 4) # but the 3rd is a None: self.assertTrue(smiSup[2] is None) text="Id SMILES Column_2\n"+\ "mol-1 C 1.0\n"+\ "mol-2 CC 4.0\n"+\ "mol-4 CCCC 16.0" smiSup.SetData(text, delimiter=" ", smilesColumn=1, nameColumn=0, titleLine=1) self.assertTrue(len(smiSup) == 3) self.assertTrue(smiSup[0]) self.assertTrue(smiSup[1]) self.assertTrue(smiSup[2]) m = [x for x in smiSup] self.assertTrue(smiSup[2]) self.assertTrue(len(m) == 3) self.assertTrue(m[0].GetProp("Column_2") == "1.0") # test simple parsing and Issue 114: smis = ['CC', 'CCC', 'CCOC', 'CCCOCC', 'CCCOCCC'] inD = '\n'.join(smis) smiSup.SetData(inD, delimiter=",", smilesColumn=0, nameColumn=-1, titleLine=0) self.assertTrue(len(smiSup) == 5) m = [x for x in smiSup] self.assertTrue(smiSup[4]) self.assertTrue(len(m) == 5) # order dependance: smiSup.SetData(inD, delimiter=",", smilesColumn=0, nameColumn=-1, titleLine=0) self.assertTrue(smiSup[4]) self.assertTrue(len(smiSup) == 5) # this was a nasty BC: # asking for a particular entry with a higher index than what we've # already seen resulted in a duplicate: smis = ['CC', 'CCC', 'CCOC', 'CCCCOC'] inD = '\n'.join(smis) smiSup.SetData(inD, delimiter=",", smilesColumn=0, nameColumn=-1, titleLine=0) m = six.next(smiSup) m = smiSup[3] self.assertTrue(len(smiSup) == 4) with self.assertRaisesRegexp(Exception, ""): smiSup[4] smiSup.SetData(inD, delimiter=",", smilesColumn=0, nameColumn=-1, titleLine=0) with self.assertRaisesRegexp(Exception, ""): smiSup[4] sys.stderr.write( '>>> This may result in an infinite loop. It should finish almost instantly\n') self.assertEqual(len(smiSup), 4) sys.stderr.write('<<< OK, it finished.\n') def test27SmilesWriter(self): fileN = os.path.join(RDConfig.RDBaseDir, 'Code', 'GraphMol', 'FileParsers', 'test_data', 'fewSmi.csv') #fileN = "../FileParsers/test_data/fewSmi.csv" smiSup = Chem.SmilesMolSupplier(fileN, delimiter=",", smilesColumn=1, nameColumn=0, titleLine=0) propNames = [] propNames.append("Column_2") ofile = os.path.join(RDConfig.RDBaseDir, 'Code', 'GraphMol', 'Wrap', 'test_data', 'outSmiles.txt') writer = Chem.SmilesWriter(ofile) writer.SetProps(propNames) for mol in smiSup: writer.write(mol) writer.flush() def test28SmilesReverse(self): names = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"] props = [ "34.14", "25.78", "106.51", "82.78", "60.16", "87.74", "37.38", "77.28", "65.18", "0.00" ] ofile = os.path.join(RDConfig.RDBaseDir, 'Code', 'GraphMol', 'Wrap', 'test_data', 'outSmiles.txt') #ofile = "test_data/outSmiles.csv" smiSup = Chem.SmilesMolSupplier(ofile) i = 0 for mol in smiSup: #print([repr(x) for x in mol.GetPropNames()]) self.assertTrue(mol.GetProp("_Name") == names[i]) self.assertTrue(mol.GetProp("Column_2") == props[i]) i += 1 def writerSDFile(self): fileN = os.path.join(RDConfig.RDBaseDir, 'Code', 'GraphMol', 'FileParsers', 'test_data', 'NCI_aids_few.sdf') #fileN = "../FileParsers/test_data/NCI_aids_few.sdf" ofile = os.path.join(RDConfig.RDBaseDir, 'Code', 'GraphMol', 'Wrap', 'test_data', 'outNCI_few.sdf') writer = Chem.SDWriter(ofile) sdSup = Chem.SDMolSupplier(fileN) for mol in sdSup: writer.write(mol) writer.flush() def test29SDWriterLoop(self): self.writerSDFile() fileN = os.path.join(RDConfig.RDBaseDir, 'Code', 'GraphMol', 'Wrap', 'test_data', 'outNCI_few.sdf') sdSup = Chem.SDMolSupplier(fileN) molNames = [ "48", "78", "128", "163", "164", "170", "180", "186", "192", "203", "210", "211", "213", "220", "229", "256" ] chgs192 = {8: 1, 11: 1, 15: -1, 18: -1, 20: 1, 21: 1, 23: -1, 25: -1} i = 0 for mol in sdSup: #print('mol:',mol) #print('\t',molNames[i]) self.assertTrue(mol.GetProp("_Name") == molNames[i]) i += 1 if (mol.GetProp("_Name") == "192"): # test parsed charges on one of the molecules for id in chgs192.keys(): self.assertTrue(mol.GetAtomWithIdx(id).GetFormalCharge() == chgs192[id]) def test30Issues109and110(self): """ issues 110 and 109 were both related to handling of explicit Hs in SMILES input. """ m1 = Chem.MolFromSmiles('N12[CH](SC(C)(C)[CH]1C(O)=O)[CH](C2=O)NC(=O)[CH](N)c3ccccc3') self.assertTrue(m1.GetNumAtoms() == 24) m2 = Chem.MolFromSmiles( 'C1C=C([CH](N)C(=O)N[C]2([H])[C]3([H])SC(C)(C)[CH](C(=O)O)N3C(=O)2)C=CC=1') self.assertTrue(m2.GetNumAtoms() == 24) smi1 = Chem.MolToSmiles(m1) smi2 = Chem.MolToSmiles(m2) self.assertTrue(smi1 == smi2) m1 = Chem.MolFromSmiles('[H]CCl') self.assertTrue(m1.GetNumAtoms() == 2) self.assertTrue(m1.GetAtomWithIdx(0).GetNumExplicitHs() == 1) m1 = Chem.MolFromSmiles('[H][CH2]Cl') self.assertTrue(m1.GetNumAtoms() == 2) self.assertTrue(m1.GetAtomWithIdx(0).GetNumExplicitHs() == 3) m2 = Chem.AddHs(m1) self.assertTrue(m2.GetNumAtoms() == 5) m2 = Chem.RemoveHs(m2) self.assertTrue(m2.GetNumAtoms() == 2) def test31ChiralitySmiles(self): m1 = Chem.MolFromSmiles('F[C@](Br)(I)Cl') self.assertTrue(m1 is not None) self.assertTrue(m1.GetNumAtoms() == 5) self.assertTrue(Chem.MolToSmiles(m1, 1) == 'F[C@](Cl)(Br)I', Chem.MolToSmiles(m1, 1)) m1 = Chem.MolFromSmiles('CC1C[C@@]1(Cl)F') self.assertTrue(m1 is not None) self.assertTrue(m1.GetNumAtoms() == 6) self.assertTrue(Chem.MolToSmiles(m1, 1) == 'CC1C[C@]1(F)Cl', Chem.MolToSmiles(m1, 1)) m1 = Chem.MolFromSmiles('CC1C[C@]1(Cl)F') self.assertTrue(m1 is not None) self.assertTrue(m1.GetNumAtoms() == 6) self.assertTrue(Chem.MolToSmiles(m1, 1) == 'CC1C[C@@]1(F)Cl', Chem.MolToSmiles(m1, 1)) def test31aChiralitySubstructs(self): m1 = Chem.MolFromSmiles('CC1C[C@@]1(Cl)F') self.assertTrue(m1 is not None) self.assertTrue(m1.GetNumAtoms() == 6) self.assertTrue(Chem.MolToSmiles(m1, 1) == 'CC1C[C@]1(F)Cl', Chem.MolToSmiles(m1, 1)) m2 = Chem.MolFromSmiles('CC1C[C@]1(Cl)F') self.assertTrue(m2 is not None) self.assertTrue(m2.GetNumAtoms() == 6) self.assertTrue(Chem.MolToSmiles(m2, 1) == 'CC1C[C@@]1(F)Cl', Chem.MolToSmiles(m2, 1)) self.assertTrue(m1.HasSubstructMatch(m1)) self.assertTrue(m1.HasSubstructMatch(m2)) self.assertTrue(m1.HasSubstructMatch(m1, useChirality=True)) self.assertTrue(not m1.HasSubstructMatch(m2, useChirality=True)) def _test32MolFilesWithChirality(self): inD = """chiral1.mol ChemDraw10160313232D 5 4 0 0 0 0 0 0 0 0999 V2000 0.0553 0.6188 0.0000 F 0 0 0 0 0 0 0 0 0 0 0 0 0.0553 -0.2062 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 0.7697 -0.6188 0.0000 I 0 0 0 0 0 0 0 0 0 0 0 0 -0.6592 -0.6188 0.0000 Br 0 0 0 0 0 0 0 0 0 0 0 0 -0.7697 -0.2062 0.0000 Cl 0 0 0 0 0 0 0 0 0 0 0 0 1 2 1 0 2 3 1 0 2 4 1 1 2 5 1 0 M END """ m1 = Chem.MolFromMolBlock(inD) self.assertTrue(m1 is not None) self.assertTrue(m1.GetNumAtoms() == 5) self.assertTrue(smi == 'F[C@](Cl)(Br)I', smi) inD = """chiral2.cdxml ChemDraw10160314052D 5 4 0 0 0 0 0 0 0 0999 V2000 0.0553 0.6188 0.0000 F 0 0 0 0 0 0 0 0 0 0 0 0 0.0553 -0.2062 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 0.7697 -0.6188 0.0000 I 0 0 0 0 0 0 0 0 0 0 0 0 -0.6592 -0.6188 0.0000 Br 0 0 0 0 0 0 0 0 0 0 0 0 -0.7697 -0.2062 0.0000 Cl 0 0 0 0 0 0 0 0 0 0 0 0 1 2 1 0 2 3 1 0 2 4 1 6 2 5 1 0 M END """ m1 = Chem.MolFromMolBlock(inD) self.assertTrue(m1 is not None) self.assertTrue(m1.GetNumAtoms() == 5) self.assertTrue(Chem.MolToSmiles(m1, 1) == 'F[C@@](Cl)(Br)I') inD = """chiral1.mol ChemDraw10160313232D 5 4 0 0 0 0 0 0 0 0999 V2000 0.0553 0.6188 0.0000 F 0 0 0 0 0 0 0 0 0 0 0 0 0.0553 -0.2062 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 -0.7697 -0.2062 0.0000 Cl 0 0 0 0 0 0 0 0 0 0 0 0 -0.6592 -0.6188 0.0000 Br 0 0 0 0 0 0 0 0 0 0 0 0 0.7697 -0.6188 0.0000 I 0 0 0 0 0 0 0 0 0 0 0 0 1 2 1 0 2 3 1 0 2 4 1 1 2 5 1 0 M END """ m1 = Chem.MolFromMolBlock(inD) self.assertTrue(m1 is not None) self.assertTrue(m1.GetNumAtoms() == 5) self.assertTrue(Chem.MolToSmiles(m1, 1) == 'F[C@](Cl)(Br)I') inD = """chiral1.mol ChemDraw10160313232D 5 4 0 0 0 0 0 0 0 0999 V2000 0.0553 -0.2062 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 -0.7697 -0.2062 0.0000 Cl 0 0 0 0 0 0 0 0 0 0 0 0 -0.6592 -0.6188 0.0000 Br 0 0 0 0 0 0 0 0 0 0 0 0 0.7697 -0.6188 0.0000 I 0 0 0 0 0 0 0 0 0 0 0 0 0.0553 0.6188 0.0000 F 0 0 0 0 0 0 0 0 0 0 0 0 1 2 1 0 1 3 1 1 1 4 1 0 1 5 1 0 M END """ m1 = Chem.MolFromMolBlock(inD) self.assertTrue(m1 is not None) self.assertTrue(m1.GetNumAtoms() == 5) self.assertTrue(Chem.MolToSmiles(m1, 1) == 'F[C@](Cl)(Br)I') inD = """chiral3.mol ChemDraw10160314362D 4 3 0 0 0 0 0 0 0 0999 V2000 0.4125 0.6188 0.0000 F 0 0 0 0 0 0 0 0 0 0 0 0 0.4125 -0.2062 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 -0.3020 -0.6188 0.0000 Br 0 0 0 0 0 0 0 0 0 0 0 0 -0.4125 -0.2062 0.0000 Cl 0 0 0 0 0 0 0 0 0 0 0 0 1 2 1 0 2 3 1 1 2 4 1 0 M END """ m1 = Chem.MolFromMolBlock(inD) self.assertTrue(m1 is not None) self.assertTrue(m1.GetNumAtoms() == 4) self.assertTrue(Chem.MolToSmiles(m1, 1) == 'F[C@H](Cl)Br') inD = """chiral4.mol ChemDraw10160314362D 4 3 0 0 0 0 0 0 0 0999 V2000 0.4125 0.6188 0.0000 F 0 0 0 0 0 0 0 0 0 0 0 0 0.4125 -0.2062 0.0000 N 0 0 0 0 0 0 0 0 0 0 0 0 -0.3020 -0.6188 0.0000 Br 0 0 0 0 0 0 0 0 0 0 0 0 -0.4125 -0.2062 0.0000 Cl 0 0 0 0 0 0 0 0 0 0 0 0 1 2 1 0 2 3 1 1 2 4 1 0 M END """ m1 = Chem.MolFromMolBlock(inD) self.assertTrue(m1 is not None) self.assertTrue(m1.GetNumAtoms() == 4) self.assertTrue(Chem.MolToSmiles(m1, 1) == 'FN(Cl)Br') inD = """chiral5.mol ChemDraw10160314362D 4 3 0 0 0 0 0 0 0 0999 V2000 0.4125 0.6188 0.0000 F 0 0 0 0 0 0 0 0 0 0 0 0 0.4125 -0.2062 0.0000 N 0 0 0 0 0 0 0 0 0 0 0 0 -0.3020 -0.6188 0.0000 Br 0 0 0 0 0 0 0 0 0 0 0 0 -0.4125 -0.2062 0.0000 Cl 0 0 0 0 0 0 0 0 0 0 0 0 1 2 1 0 2 3 1 1 2 4 1 0 M CHG 1 2 1 M END """ m1 = Chem.MolFromMolBlock(inD) self.assertTrue(m1 is not None) self.assertTrue(m1.GetNumAtoms() == 4) self.assertTrue(Chem.MolToSmiles(m1, 1) == 'F[N@H+](Cl)Br') inD = """Case 10-14-3 ChemDraw10140308512D 4 3 0 0 0 0 0 0 0 0999 V2000 -0.8250 -0.4125 0.0000 F 0 0 0 0 0 0 0 0 0 0 0 0 0.0000 -0.4125 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 0.8250 -0.4125 0.0000 Cl 0 0 0 0 0 0 0 0 0 0 0 0 0.0000 0.4125 0.0000 Br 0 0 0 0 0 0 0 0 0 0 0 0 1 2 1 0 2 3 1 0 2 4 1 1 M END """ m1 = Chem.MolFromMolBlock(inD) self.assertTrue(m1 is not None) self.assertTrue(m1.GetNumAtoms() == 4) self.assertTrue(Chem.MolToSmiles(m1, 1) == 'F[C@H](Cl)Br') inD = """Case 10-14-4 ChemDraw10140308512D 4 3 0 0 0 0 0 0 0 0999 V2000 -0.8250 -0.4125 0.0000 F 0 0 0 0 0 0 0 0 0 0 0 0 0.0000 -0.4125 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 0.8250 -0.4125 0.0000 Cl 0 0 0 0 0 0 0 0 0 0 0 0 0.0000 0.4125 0.0000 Br 0 0 0 0 0 0 0 0 0 0 0 0 1 2 1 0 2 3 1 1 2 4 1 0 M END """ m1 = Chem.MolFromMolBlock(inD) self.assertTrue(m1 is not None) self.assertTrue(m1.GetNumAtoms() == 4) self.assertTrue(Chem.MolToSmiles(m1, 1) == 'F[C@H](Cl)Br') inD = """chiral4.mol ChemDraw10160315172D 6 6 0 0 0 0 0 0 0 0999 V2000 -0.4422 0.1402 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 -0.4422 -0.6848 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 0.2723 -0.2723 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 -0.8547 0.8547 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 0.6848 0.4422 0.0000 F 0 0 0 0 0 0 0 0 0 0 0 0 0.8547 -0.8547 0.0000 Cl 0 0 0 0 0 0 0 0 0 0 0 0 1 2 1 0 2 3 1 0 3 1 1 0 1 4 1 0 3 5 1 1 3 6 1 0 M END """ m1 = Chem.MolFromMolBlock(inD) self.assertTrue(m1 is not None) self.assertTrue(m1.GetNumAtoms() == 6) self.assertTrue(Chem.MolToSmiles(m1, 1) == 'CC1C[C@@]1(F)Cl', Chem.MolToSmiles(m1, 1)) inD = """chiral4.mol ChemDraw10160315172D 6 6 0 0 0 0 0 0 0 0999 V2000 -0.4422 0.1402 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 -0.4422 -0.6848 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 0.2723 -0.2723 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 -0.8547 0.8547 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 0.6848 0.4422 0.0000 F 0 0 0 0 0 0 0 0 0 0 0 0 0.8547 -0.8547 0.0000 Cl 0 0 0 0 0 0 0 0 0 0 0 0 1 2 1 0 2 3 1 0 3 1 1 0 1 4 1 0 3 5 1 6 3 6 1 0 M END """ m1 = Chem.MolFromMolBlock(inD) self.assertTrue(m1 is not None) self.assertTrue(m1.GetNumAtoms() == 6) self.assertTrue(Chem.MolToSmiles(m1, 1) == 'CC1C[C@]1(F)Cl', Chem.MolToSmiles(m1, 1)) def test33Issue65(self): """ issue 65 relates to handling of [H] in SMARTS """ m1 = Chem.MolFromSmiles('OC(O)(O)O') m2 = Chem.MolFromSmiles('OC(O)O') m3 = Chem.MolFromSmiles('OCO') q1 = Chem.MolFromSmarts('OC[H]', 1) q2 = Chem.MolFromSmarts('O[C;H1]', 1) q3 = Chem.MolFromSmarts('O[C;H1][H]', 1) self.assertTrue(not m1.HasSubstructMatch(q1)) self.assertTrue(not m1.HasSubstructMatch(q2)) self.assertTrue(not m1.HasSubstructMatch(q3)) self.assertTrue(m2.HasSubstructMatch(q1)) self.assertTrue(m2.HasSubstructMatch(q2)) self.assertTrue(m2.HasSubstructMatch(q3)) self.assertTrue(m3.HasSubstructMatch(q1)) self.assertTrue(not m3.HasSubstructMatch(q2)) self.assertTrue(not m3.HasSubstructMatch(q3)) m1H = Chem.AddHs(m1) m2H = Chem.AddHs(m2) m3H = Chem.AddHs(m3) q1 = Chem.MolFromSmarts('OC[H]') q2 = Chem.MolFromSmarts('O[C;H1]') q3 = Chem.MolFromSmarts('O[C;H1][H]') self.assertTrue(not m1H.HasSubstructMatch(q1)) self.assertTrue(not m1H.HasSubstructMatch(q2)) self.assertTrue(not m1H.HasSubstructMatch(q3)) #m2H.Debug() self.assertTrue(m2H.HasSubstructMatch(q1)) self.assertTrue(m2H.HasSubstructMatch(q2)) self.assertTrue(m2H.HasSubstructMatch(q3)) self.assertTrue(m3H.HasSubstructMatch(q1)) self.assertTrue(not m3H.HasSubstructMatch(q2)) self.assertTrue(not m3H.HasSubstructMatch(q3)) def test34Issue124(self): """ issue 124 relates to calculation of the distance matrix """ m = Chem.MolFromSmiles('CC=C') d = Chem.GetDistanceMatrix(m, 0) self.assertTrue(feq(d[0, 1], 1.0)) self.assertTrue(feq(d[0, 2], 2.0)) # force an update: d = Chem.GetDistanceMatrix(m, 1, 0, 1) self.assertTrue(feq(d[0, 1], 1.0)) self.assertTrue(feq(d[0, 2], 1.5)) def test35ChiralityPerception(self): """ Test perception of chirality and CIP encoding """ m = Chem.MolFromSmiles('F[C@]([C@])(Cl)Br') Chem.AssignStereochemistry(m, 1) self.assertTrue(m.GetAtomWithIdx(1).HasProp('_CIPCode')) self.assertFalse(m.GetAtomWithIdx(2).HasProp('_CIPCode')) Chem.RemoveStereochemistry(m) self.assertFalse(m.GetAtomWithIdx(1).HasProp('_CIPCode')) m = Chem.MolFromSmiles('F[C@H](C)C') Chem.AssignStereochemistry(m, 1) self.assertTrue(m.GetAtomWithIdx(1).GetChiralTag() == Chem.ChiralType.CHI_UNSPECIFIED) self.assertFalse(m.GetAtomWithIdx(1).HasProp('_CIPCode')) m = Chem.MolFromSmiles('F\\C=C/Cl') self.assertTrue(m.GetBondWithIdx(0).GetStereo() == Chem.BondStereo.STEREONONE) self.assertTrue(m.GetBondWithIdx(1).GetStereo() == Chem.BondStereo.STEREOZ) atoms = m.GetBondWithIdx(1).GetStereoAtoms() self.assertTrue(0 in atoms) self.assertTrue(3 in atoms) self.assertTrue(m.GetBondWithIdx(2).GetStereo() == Chem.BondStereo.STEREONONE) Chem.RemoveStereochemistry(m) self.assertTrue(m.GetBondWithIdx(1).GetStereo() == Chem.BondStereo.STEREONONE) m = Chem.MolFromSmiles('F\\C=CCl') self.assertTrue(m.GetBondWithIdx(1).GetStereo() == Chem.BondStereo.STEREONONE) def checkDefaultBondProperties(self, m): for bond in m.GetBonds(): self.assertIn(bond.GetBondType(), [Chem.BondType.SINGLE, Chem.BondType.DOUBLE]) self.assertEquals(bond.GetBondDir(), Chem.BondDir.NONE) self.assertEquals(list(bond.GetStereoAtoms()), []) self.assertEquals(bond.GetStereo(), Chem.BondStereo.STEREONONE) def assertHasDoubleBondStereo(self, smi): m = Chem.MolFromSmiles(smi) self.checkDefaultBondProperties(m) Chem.FindPotentialStereoBonds(m) for bond in m.GetBonds(): self.assertIn(bond.GetBondType(), [Chem.BondType.SINGLE, Chem.BondType.DOUBLE]) self.assertEquals(bond.GetBondDir(), Chem.BondDir.NONE) if bond.GetBondType() == Chem.BondType.DOUBLE: self.assertEquals(bond.GetStereo(), Chem.BondStereo.STEREOANY) self.assertEquals(len(list(bond.GetStereoAtoms())), 2) else: self.assertEquals(list(bond.GetStereoAtoms()), []) self.assertEquals(bond.GetStereo(), Chem.BondStereo.STEREONONE) def testFindPotentialStereoBonds(self): self.assertHasDoubleBondStereo("FC=CF") self.assertHasDoubleBondStereo("FC(Cl)=C(Br)I") self.assertHasDoubleBondStereo("FC=CC=CC=CCl") self.assertHasDoubleBondStereo("C1CCCCC1C=CC1CCCCC1") def assertDoesNotHaveDoubleBondStereo(self, smi): m = Chem.MolFromSmiles(smi) self.checkDefaultBondProperties(m) Chem.FindPotentialStereoBonds(m) self.checkDefaultBondProperties(m) def testFindPotentialStereoBondsShouldNotFindThisDoubleBondAsStereo(self): self.assertDoesNotHaveDoubleBondStereo("FC(F)=CF") self.assertDoesNotHaveDoubleBondStereo("C=C") self.assertDoesNotHaveDoubleBondStereo("C1CCCCC1C(C1CCCCC1)=CC1CCCCC1") def assertDoubleBondStereo(self, smi, stereo): mol = Chem.MolFromSmiles(smi) bond = mol.GetBondWithIdx(1) self.assertEquals(bond.GetBondType(), Chem.BondType.DOUBLE) self.assertEquals(bond.GetStereo(), stereo) self.assertEquals(list(bond.GetStereoAtoms()), [0, 3]) def allStereoBonds(self, bonds): for bond in bonds: self.assertEquals(len(list(bond.GetStereoAtoms())), 2) def testBondSetStereo(self): for testAssignStereo in [False, True]: mol = Chem.MolFromSmiles("FC=CF") Chem.FindPotentialStereoBonds(mol) for bond in mol.GetBonds(): if (bond.GetBondType() == Chem.BondType.DOUBLE and bond.GetStereo() == Chem.BondStereo.STEREOANY): break self.assertEquals(bond.GetBondType(), Chem.BondType.DOUBLE) self.assertEquals(bond.GetStereo(), Chem.BondStereo.STEREOANY) self.assertEquals(list(bond.GetStereoAtoms()), [0, 3]) bond.SetStereo(Chem.BondStereo.STEREOTRANS) self.assertEquals(bond.GetStereo(), Chem.BondStereo.STEREOTRANS) if testAssignStereo: # should be invariant of Chem.AssignStereochemistry being called Chem.AssignStereochemistry(mol, force=True) smi = Chem.MolToSmiles(mol, isomericSmiles=True) self.allStereoBonds([bond]) self.assertEquals(smi, "F/C=C/F") self.assertDoubleBondStereo(smi, Chem.BondStereo.STEREOE) bond.SetStereo(Chem.BondStereo.STEREOCIS) self.assertEquals(bond.GetStereo(), Chem.BondStereo.STEREOCIS) if testAssignStereo: Chem.AssignStereochemistry(mol, force=True) smi = Chem.MolToSmiles(mol, isomericSmiles=True) self.allStereoBonds([bond]) self.assertEquals(smi, "F/C=C\F") self.assertDoubleBondStereo(smi, Chem.BondStereo.STEREOZ) def recursive_enumerate_stereo_bonds(self, mol, done_bonds, bonds): if not bonds: yield done_bonds, Chem.Mol(mol) return bond = bonds[0] child_bonds = bonds[1:] self.assertEquals(len(list(bond.GetStereoAtoms())), 2) bond.SetStereo(Chem.BondStereo.STEREOTRANS) for isomer in self.recursive_enumerate_stereo_bonds(mol, done_bonds + [Chem.BondStereo.STEREOE], child_bonds): yield isomer self.assertEquals(len(list(bond.GetStereoAtoms())), 2) bond.SetStereo(Chem.BondStereo.STEREOCIS) for isomer in self.recursive_enumerate_stereo_bonds(mol, done_bonds + [Chem.BondStereo.STEREOZ], child_bonds): yield isomer def testBondSetStereoDifficultCase(self): unspec_smiles = "CCC=CC(CO)=C(C)CC" mol = Chem.MolFromSmiles(unspec_smiles) Chem.FindPotentialStereoBonds(mol) stereo_bonds = [] for bond in mol.GetBonds(): if bond.GetStereo() == Chem.BondStereo.STEREOANY: stereo_bonds.append(bond) isomers = set() for bond_stereo, isomer in self.recursive_enumerate_stereo_bonds(mol, [], stereo_bonds): self.allStereoBonds(stereo_bonds) isosmi = Chem.MolToSmiles(isomer, isomericSmiles=True) self.allStereoBonds(stereo_bonds) self.assertNotIn(isosmi, isomers) isomers.add(isosmi) isomol = Chem.MolFromSmiles(isosmi) round_trip_stereo = [ b.GetStereo() for b in isomol.GetBonds() if b.GetStereo() != Chem.BondStereo.STEREONONE ] self.assertEquals(bond_stereo, round_trip_stereo) self.assertEqual(len(isomers), 4) def getNumUnspecifiedBondStereo(self, smi): mol = Chem.MolFromSmiles(smi) Chem.FindPotentialStereoBonds(mol) count = 0 for bond in mol.GetBonds(): if bond.GetStereo() == Chem.BondStereo.STEREOANY: count += 1 return count def testBondSetStereoReallyDifficultCase(self): # this one is much trickier because a double bond can gain and # lose it's stereochemistry based upon whether 2 other double # bonds have the same or different stereo chemistry. unspec_smiles = "CCC=CC(C=CCC)=C(CO)CC" mol = Chem.MolFromSmiles(unspec_smiles) Chem.FindPotentialStereoBonds(mol) stereo_bonds = [] for bond in mol.GetBonds(): if bond.GetStereo() == Chem.BondStereo.STEREOANY: stereo_bonds.append(bond) self.assertEquals(len(stereo_bonds), 2) isomers = set() for bond_stereo, isomer in self.recursive_enumerate_stereo_bonds(mol, [], stereo_bonds): isosmi = Chem.MolToSmiles(isomer, isomericSmiles=True) isomers.add(isosmi) self.assertEquals(len(isomers), 3) # one of these then gains a new stereo bond due to the # introduction of a new symmetry counts = {} for isosmi in isomers: num_unspecified = self.getNumUnspecifiedBondStereo(isosmi) counts[num_unspecified] = counts.get(num_unspecified, 0) + 1 # 2 of the isomers don't have any unspecified bond stereo centers # left, 1 does self.assertEquals(counts, {0: 2, 1: 1}) def assertBondSetStereoIsAlwaysEquivalent(self, all_smiles, desired_stereo, bond_idx): refSmiles = None for smi in all_smiles: mol = Chem.MolFromSmiles(smi) doubleBond = None for bond in mol.GetBonds(): if bond.GetBondType() == Chem.BondType.DOUBLE: doubleBond = bond self.assertTrue(doubleBond is not None) Chem.FindPotentialStereoBonds(mol) doubleBond.SetStereo(desired_stereo) isosmi = Chem.MolToSmiles(mol, isomericSmiles=True) if refSmiles is None: refSmiles = isosmi self.assertEquals(refSmiles, isosmi) def testBondSetStereoAllHalogens(self): # can't get much more brutal than this test from itertools import combinations, permutations halogens = ['F', 'Cl', 'Br', 'I'] # binary double bond stereo for unique_set in combinations(halogens, 2): all_smiles = [] for fmt in ['%sC=C%s', 'C(%s)=C%s']: for ordering in permutations(unique_set): all_smiles.append(fmt % ordering) #print(fmt, all_smiles) for desired_stereo in [Chem.BondStereo.STEREOTRANS, Chem.BondStereo.STEREOCIS]: self.assertBondSetStereoIsAlwaysEquivalent(all_smiles, desired_stereo, 1) # tertiary double bond stereo for unique_set in combinations(halogens, 3): for mono_side in unique_set: halogens_left = list(unique_set) halogens_left.remove(mono_side) for binary_side in combinations(halogens_left, 2): all_smiles = [] for binary_side_permutation in permutations(binary_side): all_smiles.append('%sC=C(%s)%s' % ((mono_side, ) + binary_side_permutation)) all_smiles.append('C(%s)=C(%s)%s' % ((mono_side, ) + binary_side_permutation)) all_smiles.append('%sC(%s)=C%s' % (binary_side_permutation + (mono_side, ))) all_smiles.append('C(%s)(%s)=C%s' % (binary_side_permutation + (mono_side, ))) #print(all_smiles) for desired_stereo in [Chem.BondStereo.STEREOTRANS, Chem.BondStereo.STEREOCIS]: self.assertBondSetStereoIsAlwaysEquivalent(all_smiles, desired_stereo, 1) # quaternary double bond stereo for unique_ordering in permutations(halogens): left_side = unique_ordering[:2] rght_side = unique_ordering[2:] all_smiles = [] for left_side_permutation in permutations(left_side): for rght_side_permutation in permutations(rght_side): for smifmt in ['%sC(%s)=C(%s)%s', 'C(%s)(%s)=C(%s)%s']: all_smiles.append(smifmt % (left_side_permutation + rght_side_permutation)) #print(all_smiles) for desired_stereo in [Chem.BondStereo.STEREOTRANS, Chem.BondStereo.STEREOCIS]: self.assertBondSetStereoIsAlwaysEquivalent(all_smiles, desired_stereo, 1) def testBondSetStereoAtoms(self): # use this difficult molecule that only generates 4 isomers, but # assume all double bonds are stereo! unspec_smiles = "CCC=CC(C=CCC)=C(CO)CC" mol = Chem.MolFromSmiles(unspec_smiles) def getNbr(atom, exclude): for nbr in atom.GetNeighbors(): if nbr.GetIdx() not in exclude: return nbr raise ValueError("No neighbor found!") double_bonds = [] for bond in mol.GetBonds(): if bond.GetBondType() == 2: double_bonds.append(bond) exclude = {bond.GetBeginAtomIdx(), bond.GetEndAtomIdx()} bgnNbr = getNbr(bond.GetBeginAtom(), exclude) endNbr = getNbr(bond.GetEndAtom(), exclude) bond.SetStereoAtoms(bgnNbr.GetIdx(), endNbr.GetIdx()) self.assertEquals(len(double_bonds), 3) import itertools stereos = [Chem.BondStereo.STEREOE, Chem.BondStereo.STEREOZ] isomers = set() for stereo_config in itertools.product(stereos, repeat=len(double_bonds)): for bond, stereo in zip(double_bonds, stereo_config): bond.SetStereo(stereo) smi = Chem.MolToSmiles(mol, True) isomers.add(smi) # the dependent double bond stereo isn't picked up by this, should it? self.assertEquals(len(isomers), 6) # round tripping them through one more time does pick up the dependency, so meh? round_trip_isomers = set() for smi in isomers: isosmi = Chem.MolToSmiles(Chem.MolFromSmiles(smi), True) round_trip_isomers.add(isosmi) self.assertEquals(len(round_trip_isomers), 4) def test36SubstructMatchStr(self): """ test the _SubstructMatchStr function """ query = Chem.MolFromSmarts('[n,p]1ccccc1') self.assertTrue(query) mol = Chem.MolFromSmiles('N1=CC=CC=C1') self.assertTrue(mol.HasSubstructMatch(query)) self.assertTrue(Chem._HasSubstructMatchStr(mol.ToBinary(), query)) mol = Chem.MolFromSmiles('S1=CC=CC=C1') self.assertTrue(not Chem._HasSubstructMatchStr(mol.ToBinary(), query)) self.assertTrue(not mol.HasSubstructMatch(query)) mol = Chem.MolFromSmiles('P1=CC=CC=C1') self.assertTrue(mol.HasSubstructMatch(query)) self.assertTrue(Chem._HasSubstructMatchStr(mol.ToBinary(), query)) def test37SanitException(self): mol = Chem.MolFromSmiles('CC(C)(C)(C)C', 0) self.assertTrue(mol) self.assertRaises(ValueError, lambda: Chem.SanitizeMol(mol)) def test38TDTSuppliers(self): data = """$SMI<Cc1nnc(N)nc1C> CAS<17584-12-2> | $SMI<Cc1n[nH]c(=O)nc1N> CAS<~> | $SMI<Cc1n[nH]c(=O)[nH]c1=O> CAS<932-53-6> | $SMI<Cc1nnc(NN)nc1O> CAS<~> |""" suppl = Chem.TDTMolSupplier() suppl.SetData(data, "CAS") i = 0 for mol in suppl: self.assertTrue(mol) self.assertTrue(mol.GetNumAtoms()) self.assertTrue(mol.HasProp("CAS")) self.assertTrue(mol.HasProp("_Name")) self.assertTrue(mol.GetProp("CAS") == mol.GetProp("_Name")) self.assertTrue(mol.GetNumConformers() == 0) i += 1 self.assertTrue(i == 4) self.assertTrue(len(suppl) == 4) def test38Issue266(self): """ test issue 266: generation of kekulized smiles""" mol = Chem.MolFromSmiles('c1ccccc1') Chem.Kekulize(mol) smi = Chem.MolToSmiles(mol) self.assertTrue(smi == 'c1ccccc1') smi = Chem.MolToSmiles(mol, kekuleSmiles=True) self.assertTrue(smi == 'C1=CC=CC=C1') def test39Issue273(self): """ test issue 273: MolFileComments and MolFileInfo props ending up in SD files """ fileN = os.path.join(RDConfig.RDBaseDir, 'Code', 'GraphMol', 'Wrap', 'test_data', 'outNCI_few.sdf') suppl = Chem.SDMolSupplier(fileN) ms = [x for x in suppl] for m in ms: self.assertTrue(m.HasProp('_MolFileInfo')) self.assertTrue(m.HasProp('_MolFileComments')) fName = tempfile.mktemp('.sdf') w = Chem.SDWriter(fName) w.SetProps(ms[0].GetPropNames()) for m in ms: w.write(m) w = None with open(fName, 'r') as txtFile: txt = txtFile.read() os.unlink(fName) self.assertTrue(txt.find('MolFileInfo') == -1) self.assertTrue(txt.find('MolFileComments') == -1) def test40SmilesRootedAtAtom(self): """ test the rootAtAtom functionality """ smi = 'CN(C)C' m = Chem.MolFromSmiles(smi) self.assertTrue(Chem.MolToSmiles(m) == 'CN(C)C') self.assertTrue(Chem.MolToSmiles(m, rootedAtAtom=1) == 'N(C)(C)C') def test41SetStreamIndices(self): fileN = os.path.join(RDConfig.RDBaseDir, 'Code', 'GraphMol', 'FileParsers', 'test_data', 'NCI_aids_few.sdf') allIndices = [] ifs = open(fileN, 'rb') addIndex = True line = True pos = 0 while (line): if (addIndex): pos = ifs.tell() line = ifs.readline().decode('utf-8') if (line): if (addIndex): allIndices.append(pos) addIndex = (line[:4] == '$$$$') ifs.close() indices = allIndices sdSup = Chem.SDMolSupplier(fileN) molNames = [ "48", "78", "128", "163", "164", "170", "180", "186", "192", "203", "210", "211", "213", "220", "229", "256" ] sdSup._SetStreamIndices(indices) self.assertTrue(len(sdSup) == 16) mol = sdSup[5] self.assertTrue(mol.GetProp("_Name") == "170") i = 0 for mol in sdSup: self.assertTrue(mol) self.assertTrue(mol.GetProp("_Name") == molNames[i]) i += 1 ns = [mol.GetProp("_Name") for mol in sdSup] self.assertTrue(ns == molNames) # this can also be used to skip molecules in the file: indices = [allIndices[0], allIndices[2], allIndices[5]] sdSup._SetStreamIndices(indices) self.assertTrue(len(sdSup) == 3) mol = sdSup[2] self.assertTrue(mol.GetProp("_Name") == "170") # or to reorder them: indices = [allIndices[0], allIndices[5], allIndices[2]] sdSup._SetStreamIndices(indices) self.assertTrue(len(sdSup) == 3) mol = sdSup[1] self.assertTrue(mol.GetProp("_Name") == "170") def test42LifeTheUniverseAndEverything(self): self.assertTrue(True) def test43TplFileParsing(self): fileN = os.path.join(RDConfig.RDBaseDir, 'Code', 'GraphMol', 'FileParsers', 'test_data', 'cmpd2.tpl') m1 = Chem.MolFromTPLFile(fileN) self.assertTrue(m1 is not None) self.assertTrue(m1.GetNumAtoms() == 12) self.assertTrue(m1.GetNumConformers() == 2) m1 = Chem.MolFromTPLFile(fileN, skipFirstConf=True) self.assertTrue(m1 is not None) self.assertTrue(m1.GetNumAtoms() == 12) self.assertTrue(m1.GetNumConformers() == 1) with open(fileN, 'r') as blockFile: block = blockFile.read() m1 = Chem.MolFromTPLBlock(block) self.assertTrue(m1 is not None) self.assertTrue(m1.GetNumAtoms() == 12) self.assertTrue(m1.GetNumConformers() == 2) def test44TplFileWriting(self): fileN = os.path.join(RDConfig.RDBaseDir, 'Code', 'GraphMol', 'FileParsers', 'test_data', 'cmpd2.tpl') m1 = Chem.MolFromTPLFile(fileN) self.assertTrue(m1 is not None) self.assertTrue(m1.GetNumAtoms() == 12) self.assertTrue(m1.GetNumConformers() == 2) block = Chem.MolToTPLBlock(m1) m1 = Chem.MolFromTPLBlock(block) self.assertTrue(m1 is not None) self.assertTrue(m1.GetNumAtoms() == 12) self.assertTrue(m1.GetNumConformers() == 2) def test45RingInfo(self): """ test the RingInfo class """ smi = 'CNC' m = Chem.MolFromSmiles(smi) ri = m.GetRingInfo() self.assertTrue(ri) self.assertTrue(ri.NumRings() == 0) self.assertFalse(ri.IsAtomInRingOfSize(0, 3)) self.assertFalse(ri.IsAtomInRingOfSize(1, 3)) self.assertFalse(ri.IsAtomInRingOfSize(2, 3)) self.assertFalse(ri.IsBondInRingOfSize(1, 3)) self.assertFalse(ri.IsBondInRingOfSize(2, 3)) smi = 'C1CC2C1C2' m = Chem.MolFromSmiles(smi) ri = m.GetRingInfo() self.assertTrue(ri) self.assertTrue(ri.NumRings() == 2) self.assertFalse(ri.IsAtomInRingOfSize(0, 3)) self.assertTrue(ri.IsAtomInRingOfSize(0, 4)) self.assertFalse(ri.IsBondInRingOfSize(0, 3)) self.assertTrue(ri.IsBondInRingOfSize(0, 4)) self.assertTrue(ri.IsAtomInRingOfSize(2, 4)) self.assertTrue(ri.IsAtomInRingOfSize(2, 3)) self.assertTrue(ri.IsBondInRingOfSize(2, 3)) self.assertTrue(ri.IsBondInRingOfSize(2, 4)) def test46ReplaceCore(self): """ test the ReplaceCore functionality """ core = Chem.MolFromSmiles('C=O') smi = 'CCC=O' m = Chem.MolFromSmiles(smi) r = Chem.ReplaceCore(m, core) self.assertTrue(r) self.assertEqual(Chem.MolToSmiles(r, True), '[1*]CC') smi = 'C1CC(=O)CC1' m = Chem.MolFromSmiles(smi) r = Chem.ReplaceCore(m, core) self.assertTrue(r) self.assertEqual(Chem.MolToSmiles(r, True), '[1*]CCCC[2*]') smi = 'C1CC(=N)CC1' m = Chem.MolFromSmiles(smi) r = Chem.ReplaceCore(m, core) self.assertFalse(r) # smiles, smarts, replaceDummies, labelByIndex, useChirality expected = { ('C1O[C@@]1(OC)NC', 'C1O[C@]1(*)*', False, False, False): '[1*]OC.[2*]NC', ('C1O[C@@]1(OC)NC', 'C1O[C@]1(*)*', False, False, True): '[1*]NC.[2*]OC', ('C1O[C@@]1(OC)NC', 'C1O[C@]1(*)*', False, True, False): '[3*]OC.[4*]NC', ('C1O[C@@]1(OC)NC', 'C1O[C@]1(*)*', False, True, True): '[3*]NC.[4*]OC', ('C1O[C@@]1(OC)NC', 'C1O[C@]1(*)*', True, False, False): '[1*]C.[2*]C', ('C1O[C@@]1(OC)NC', 'C1O[C@]1(*)*', True, False, True): '[1*]C.[2*]C', ('C1O[C@@]1(OC)NC', 'C1O[C@]1(*)*', True, True, False): '[3*]C.[4*]C', ('C1O[C@@]1(OC)NC', 'C1O[C@]1(*)*', True, True, True): '[3*]C.[4*]C', ('C1O[C@]1(OC)NC', 'C1O[C@]1(*)*', False, False, False): '[1*]OC.[2*]NC', ('C1O[C@]1(OC)NC', 'C1O[C@]1(*)*', False, False, True): '[1*]OC.[2*]NC', ('C1O[C@]1(OC)NC', 'C1O[C@]1(*)*', False, True, False): '[3*]OC.[4*]NC', ('C1O[C@]1(OC)NC', 'C1O[C@]1(*)*', False, True, True): '[3*]OC.[4*]NC', ('C1O[C@]1(OC)NC', 'C1O[C@]1(*)*', True, False, False): '[1*]C.[2*]C', ('C1O[C@]1(OC)NC', 'C1O[C@]1(*)*', True, False, True): '[1*]C.[2*]C', ('C1O[C@]1(OC)NC', 'C1O[C@]1(*)*', True, True, False): '[3*]C.[4*]C', ('C1O[C@]1(OC)NC', 'C1O[C@]1(*)*', True, True, True): '[3*]C.[4*]C', } for (smiles, smarts, replaceDummies, labelByIndex, useChirality), expected_smiles in expected.items(): mol = Chem.MolFromSmiles(smiles) core = Chem.MolFromSmarts(smarts) nm = Chem.ReplaceCore(mol, core, replaceDummies=replaceDummies, labelByIndex=labelByIndex, useChirality=useChirality) if Chem.MolToSmiles(nm, True) != expected_smiles: print( "ReplaceCore(%r, %r, replaceDummies=%r, labelByIndex=%r, useChirality=%r" % (smiles, smarts, replaceDummies, labelByIndex, useChirality), file=sys.stderr) print("expected: %s\ngot: %s" % (expected_smiles, Chem.MolToSmiles(nm, True)), file=sys.stderr) self.assertEquals(expected_smiles, Chem.MolToSmiles(nm, True)) matchVect = mol.GetSubstructMatch(core, useChirality=useChirality) nm = Chem.ReplaceCore(mol, core, matchVect, replaceDummies=replaceDummies, labelByIndex=labelByIndex) if Chem.MolToSmiles(nm, True) != expected_smiles: print( "ReplaceCore(%r, %r, %r, replaceDummies=%r, labelByIndex=%rr" % (smiles, smarts, matchVect, replaceDummies, labelByIndex), file=sys.stderr) print("expected: %s\ngot: %s" % (expected_smiles, Chem.MolToSmiles(nm, True)), file=sys.stderr) self.assertEquals(expected_smiles, Chem.MolToSmiles(nm, True)) mol = Chem.MolFromSmiles("C") smarts = Chem.MolFromSmarts("C") try: Chem.ReplaceCore(mol, smarts, (3, )) self.asssertFalse(True) except: pass mol = Chem.MolFromSmiles("C") smarts = Chem.MolFromSmarts("C") try: Chem.ReplaceCore(mol, smarts, (0, 0)) self.asssertFalse(True) except: pass def test47RWMols(self): """ test the RWMol class """ mol = Chem.MolFromSmiles('C1CCC1') self.assertTrue(type(mol) == Chem.Mol) for rwmol in [Chem.EditableMol(mol), Chem.RWMol(mol)]: self.assertTrue(type(rwmol) in [Chem.EditableMol, Chem.RWMol]) newAt = Chem.Atom(8) rwmol.ReplaceAtom(0, newAt) self.assertTrue(Chem.MolToSmiles(rwmol.GetMol()) == 'C1COC1') rwmol.RemoveBond(0, 1) self.assertTrue(Chem.MolToSmiles(rwmol.GetMol()) == 'CCCO') a = Chem.Atom(7) idx = rwmol.AddAtom(a) self.assertEqual(rwmol.GetMol().GetNumAtoms(), 5) self.assertEqual(idx, 4) idx = rwmol.AddBond(0, 4, order=Chem.BondType.SINGLE) self.assertEqual(idx, 4) self.assertTrue(Chem.MolToSmiles(rwmol.GetMol()) == 'CCCON') rwmol.AddBond(4, 1, order=Chem.BondType.SINGLE) self.assertTrue(Chem.MolToSmiles(rwmol.GetMol()) == 'C1CNOC1') rwmol.RemoveAtom(3) self.assertTrue(Chem.MolToSmiles(rwmol.GetMol()) == 'CCNO') # practice shooting ourselves in the foot: m = Chem.MolFromSmiles('c1ccccc1') em = Chem.EditableMol(m) em.RemoveAtom(0) m2 = em.GetMol() self.assertRaises(ValueError, lambda: Chem.SanitizeMol(m2)) m = Chem.MolFromSmiles('c1ccccc1') em = Chem.EditableMol(m) em.RemoveBond(0, 1) m2 = em.GetMol() self.assertRaises(ValueError, lambda: Chem.SanitizeMol(m2)) # boundary cases: # removing non-existent bonds: m = Chem.MolFromSmiles('c1ccccc1') em = Chem.EditableMol(m) em.RemoveBond(0, 2) m2 = em.GetMol() Chem.SanitizeMol(m2) self.assertTrue(Chem.MolToSmiles(m2) == 'c1ccccc1') # removing non-existent atoms: m = Chem.MolFromSmiles('c1ccccc1') em = Chem.EditableMol(m) self.assertRaises(RuntimeError, lambda: em.RemoveAtom(12)) # confirm that an RWMol can be constructed without arguments m = Chem.RWMol() # test replaceAtom/Bond preserving properties mol = Chem.MolFromSmiles('C1CCC1') mol2 = Chem.MolFromSmiles('C1CCC1') mol.GetAtomWithIdx(0).SetProp("foo", "bar") mol.GetBondWithIdx(0).SetProp("foo", "bar") newBond = mol2.GetBondWithIdx(0) self.assertTrue(type(mol) == Chem.Mol) for rwmol in [Chem.EditableMol(mol), Chem.RWMol(mol)]: newAt = Chem.Atom(8) rwmol.ReplaceAtom(0, newAt) self.assertTrue(Chem.MolToSmiles(rwmol.GetMol()) == 'C1COC1') self.assertFalse(rwmol.GetMol().GetAtomWithIdx(0).HasProp("foo")) for rwmol in [Chem.EditableMol(mol), Chem.RWMol(mol)]: newAt = Chem.Atom(8) rwmol.ReplaceAtom(0, newAt, preserveProps=True) self.assertTrue(Chem.MolToSmiles(rwmol.GetMol()) == 'C1COC1') self.assertTrue(rwmol.GetMol().GetAtomWithIdx(0).HasProp("foo")) self.assertEqual(rwmol.GetMol().GetAtomWithIdx(0).GetProp("foo"), "bar") for rwmol in [Chem.EditableMol(mol), Chem.RWMol(mol)]: rwmol.ReplaceBond(0, newBond) self.assertTrue(Chem.MolToSmiles(rwmol.GetMol()) == 'C1CCC1') self.assertFalse(rwmol.GetMol().GetBondWithIdx(0).HasProp("foo")) for rwmol in [Chem.EditableMol(mol), Chem.RWMol(mol)]: rwmol.ReplaceBond(0, newBond, preserveProps=True) self.assertTrue(Chem.MolToSmiles(rwmol.GetMol()) == 'C1CCC1') self.assertTrue(rwmol.GetMol().GetBondWithIdx(0).HasProp("foo")) self.assertEqual(rwmol.GetMol().GetBondWithIdx(0).GetProp("foo"), "bar") def test47SmartsPieces(self): """ test the GetAtomSmarts and GetBondSmarts functions """ m = Chem.MolFromSmarts("[C,N]C") self.assertTrue(m.GetAtomWithIdx(0).GetSmarts() == '[C,N]') self.assertTrue(m.GetAtomWithIdx(1).GetSmarts() == 'C') self.assertEqual(m.GetBondBetweenAtoms(0, 1).GetSmarts(), '') m = Chem.MolFromSmarts("[$(C=O)]-O") self.assertTrue(m.GetAtomWithIdx(0).GetSmarts() == '[$(C=O)]') self.assertTrue(m.GetAtomWithIdx(1).GetSmarts() == 'O') self.assertTrue(m.GetBondBetweenAtoms(0, 1).GetSmarts() == '-') m = Chem.MolFromSmiles("CO") self.assertTrue(m.GetAtomWithIdx(0).GetSmarts() == 'C') self.assertTrue(m.GetAtomWithIdx(1).GetSmarts() == 'O') self.assertTrue(m.GetBondBetweenAtoms(0, 1).GetSmarts() == '') self.assertTrue(m.GetBondBetweenAtoms(0, 1).GetSmarts(allBondsExplicit=True) == '-') m = Chem.MolFromSmiles("C=O") self.assertTrue(m.GetAtomWithIdx(0).GetSmarts() == 'C') self.assertTrue(m.GetAtomWithIdx(1).GetSmarts() == 'O') self.assertTrue(m.GetBondBetweenAtoms(0, 1).GetSmarts() == '=') m = Chem.MolFromSmiles('C[C@H](F)[15NH3+]') self.assertEqual(m.GetAtomWithIdx(0).GetSmarts(), 'C') self.assertEqual(m.GetAtomWithIdx(0).GetSmarts(allHsExplicit=True), '[CH3]') self.assertEqual(m.GetAtomWithIdx(3).GetSmarts(), '[15NH3+]') self.assertEqual(m.GetAtomWithIdx(3).GetSmarts(allHsExplicit=True), '[15NH3+]') def test48Issue1928819(self): """ test a crash involving looping directly over mol suppliers """ fileN = os.path.join(RDConfig.RDBaseDir, 'Code', 'GraphMol', 'FileParsers', 'test_data', 'NCI_aids_few.sdf') ms = [x for x in Chem.SDMolSupplier(fileN)] self.assertEqual(len(ms), 16) count = 0 for m in Chem.SDMolSupplier(fileN): count += 1 self.assertEqual(count, 16) fileN = os.path.join(RDConfig.RDBaseDir, 'Code', 'GraphMol', 'FileParsers', 'test_data', 'fewSmi.csv') count = 0 for m in Chem.SmilesMolSupplier(fileN, titleLine=False, smilesColumn=1, delimiter=','): count += 1 self.assertEqual(count, 10) fileN = os.path.join(RDConfig.RDBaseDir, 'Code', 'GraphMol', 'FileParsers', 'test_data', 'acd_few.tdt') count = 0 for m in Chem.TDTMolSupplier(fileN): count += 1 self.assertEqual(count, 10) def test49Issue1932365(self): """ test aromatic Se and Te from smiles/smarts """ m = Chem.MolFromSmiles('c1ccc[se]1') self.assertTrue(m) self.assertTrue(m.GetAtomWithIdx(0).GetIsAromatic()) self.assertTrue(m.GetAtomWithIdx(4).GetIsAromatic()) m = Chem.MolFromSmiles('c1ccc[te]1') self.assertTrue(m) self.assertTrue(m.GetAtomWithIdx(0).GetIsAromatic()) self.assertTrue(m.GetAtomWithIdx(4).GetIsAromatic()) m = Chem.MolFromSmiles('C1=C[Se]C=C1') self.assertTrue(m) self.assertTrue(m.GetAtomWithIdx(0).GetIsAromatic()) self.assertTrue(m.GetAtomWithIdx(2).GetIsAromatic()) m = Chem.MolFromSmiles('C1=C[Te]C=C1') self.assertTrue(m) self.assertTrue(m.GetAtomWithIdx(0).GetIsAromatic()) self.assertTrue(m.GetAtomWithIdx(2).GetIsAromatic()) p = Chem.MolFromSmarts('[se]') self.assertTrue(Chem.MolFromSmiles('c1ccc[se]1').HasSubstructMatch(p)) self.assertFalse(Chem.MolFromSmiles('C1=CCC[Se]1').HasSubstructMatch(p)) p = Chem.MolFromSmarts('[te]') self.assertTrue(Chem.MolFromSmiles('c1ccc[te]1').HasSubstructMatch(p)) self.assertFalse(Chem.MolFromSmiles('C1=CCC[Te]1').HasSubstructMatch(p)) def test50Issue1968608(self): """ test sf.net issue 1968608 """ smarts = Chem.MolFromSmarts("[r5]") mol = Chem.MolFromSmiles("N12CCC36C1CC(C(C2)=CCOC4CC5=O)C4C3N5c7ccccc76") count = len(mol.GetSubstructMatches(smarts, uniquify=0)) self.assertTrue(count == 9) def test51RadicalHandling(self): """ test handling of atoms with radicals """ mol = Chem.MolFromSmiles("[C]C") self.assertTrue(mol) atom = mol.GetAtomWithIdx(0) self.assertTrue(atom.GetNumRadicalElectrons() == 3) self.assertTrue(atom.GetNoImplicit()) atom.SetNoImplicit(False) atom.SetNumRadicalElectrons(1) mol.UpdatePropertyCache() self.assertTrue(atom.GetNumRadicalElectrons() == 1) self.assertTrue(atom.GetNumImplicitHs() == 2) mol = Chem.MolFromSmiles("[c]1ccccc1") self.assertTrue(mol) atom = mol.GetAtomWithIdx(0) self.assertTrue(atom.GetNumRadicalElectrons() == 1) self.assertTrue(atom.GetNoImplicit()) mol = Chem.MolFromSmiles("[n]1ccccc1") self.assertTrue(mol) atom = mol.GetAtomWithIdx(0) self.assertTrue(atom.GetNumRadicalElectrons() == 0) self.assertTrue(atom.GetNoImplicit()) def test52MolFrags(self): """ test GetMolFrags functionality """ mol = Chem.MolFromSmiles("C.CC") self.assertTrue(mol) fs = Chem.GetMolFrags(mol) self.assertTrue(len(fs) == 2) self.assertTrue(len(fs[0]) == 1) self.assertTrue(tuple(fs[0]) == (0, )) self.assertTrue(len(fs[1]) == 2) self.assertTrue(tuple(fs[1]) == (1, 2)) fs = Chem.GetMolFrags(mol, True) self.assertTrue(len(fs) == 2) self.assertTrue(fs[0].GetNumAtoms() == 1) self.assertTrue(fs[1].GetNumAtoms() == 2) mol = Chem.MolFromSmiles("CCC") self.assertTrue(mol) fs = Chem.GetMolFrags(mol) self.assertTrue(len(fs) == 1) self.assertTrue(len(fs[0]) == 3) self.assertTrue(tuple(fs[0]) == (0, 1, 2)) fs = Chem.GetMolFrags(mol, True) self.assertTrue(len(fs) == 1) self.assertTrue(fs[0].GetNumAtoms() == 3) mol = Chem.MolFromSmiles("CO") em = Chem.EditableMol(mol) em.RemoveBond(0, 1) nm = em.GetMol() fs = Chem.GetMolFrags(nm, asMols=True) self.assertEqual([x.GetNumAtoms(onlyExplicit=False) for x in fs], [5, 3]) fs = Chem.GetMolFrags(nm, asMols=True, sanitizeFrags=False) self.assertEqual([x.GetNumAtoms(onlyExplicit=False) for x in fs], [4, 2]) mol = Chem.MolFromSmiles("CC.CCC") fs = Chem.GetMolFrags(mol, asMols=True) self.assertEqual([x.GetNumAtoms() for x in fs], [2, 3]) frags = [] fragsMolAtomMapping = [] fs = Chem.GetMolFrags(mol, asMols=True, frags=frags, fragsMolAtomMapping=fragsMolAtomMapping) self.assertEqual(mol.GetNumAtoms(onlyExplicit=True), len(frags)) fragsCheck = [] for i, f in enumerate(fs): fragsCheck.extend([i] * f.GetNumAtoms(onlyExplicit=True)) self.assertEqual(frags, fragsCheck) fragsMolAtomMappingCheck = [] i = 0 for f in fs: n = f.GetNumAtoms(onlyExplicit=True) fragsMolAtomMappingCheck.append(tuple(range(i, i + n))) i += n self.assertEqual(fragsMolAtomMapping, fragsMolAtomMappingCheck) def test53Matrices(self): """ test adjacency and distance matrices """ m = Chem.MolFromSmiles('CC=C') d = Chem.GetDistanceMatrix(m, 0) self.assertTrue(feq(d[0, 1], 1.0)) self.assertTrue(feq(d[0, 2], 2.0)) self.assertTrue(feq(d[1, 0], 1.0)) self.assertTrue(feq(d[2, 0], 2.0)) a = Chem.GetAdjacencyMatrix(m, 0) self.assertTrue(a[0, 1] == 1) self.assertTrue(a[0, 2] == 0) self.assertTrue(a[1, 2] == 1) self.assertTrue(a[1, 0] == 1) self.assertTrue(a[2, 0] == 0) m = Chem.MolFromSmiles('C1CC1') d = Chem.GetDistanceMatrix(m, 0) self.assertTrue(feq(d[0, 1], 1.0)) self.assertTrue(feq(d[0, 2], 1.0)) a = Chem.GetAdjacencyMatrix(m, 0) self.assertTrue(a[0, 1] == 1) self.assertTrue(a[0, 2] == 1) self.assertTrue(a[1, 2] == 1) m = Chem.MolFromSmiles('CC.C') d = Chem.GetDistanceMatrix(m, 0) self.assertTrue(feq(d[0, 1], 1.0)) self.assertTrue(d[0, 2] > 1000) self.assertTrue(d[1, 2] > 1000) a = Chem.GetAdjacencyMatrix(m, 0) self.assertTrue(a[0, 1] == 1) self.assertTrue(a[0, 2] == 0) self.assertTrue(a[1, 2] == 0) def test54Mol2Parser(self): """ test the mol2 parser """ fileN = os.path.join(RDConfig.RDBaseDir, 'Code', 'GraphMol', 'FileParsers', 'test_data', 'pyrazole_pyridine.mol2') m = Chem.MolFromMol2File(fileN) self.assertTrue(m.GetNumAtoms() == 5) self.assertTrue(Chem.MolToSmiles(m) == 'c1cn[nH]c1', Chem.MolToSmiles(m)) fileN = os.path.join(RDConfig.RDBaseDir, 'Code', 'GraphMol', 'FileParsers', 'test_data', '3505.mol2') m = Chem.MolFromMol2File(fileN) self.assertTrue(m.GetBondBetweenAtoms(3, 12) is not None) self.assertEqual(m.GetBondBetweenAtoms(3, 12).GetBondType(), Chem.BondType.SINGLE) self.assertEqual(m.GetAtomWithIdx(12).GetFormalCharge(), 0) m = Chem.MolFromMol2File(fileN, cleanupSubstructures=False) self.assertTrue(m.GetBondBetweenAtoms(3, 12) is not None) self.assertEqual(m.GetBondBetweenAtoms(3, 12).GetBondType(), Chem.BondType.DOUBLE) self.assertEqual(m.GetAtomWithIdx(12).GetFormalCharge(), 1) def test55LayeredFingerprint(self): m1 = Chem.MolFromSmiles('CC(C)C') fp1 = Chem.LayeredFingerprint(m1) self.assertEqual(len(fp1), 2048) atomCounts = [0] * m1.GetNumAtoms() fp2 = Chem.LayeredFingerprint(m1, atomCounts=atomCounts) self.assertEqual(fp1, fp2) self.assertEqual(atomCounts, [4, 7, 4, 4]) fp2 = Chem.LayeredFingerprint(m1, atomCounts=atomCounts) self.assertEqual(fp1, fp2) self.assertEqual(atomCounts, [8, 14, 8, 8]) pbv = DataStructs.ExplicitBitVect(2048) fp3 = Chem.LayeredFingerprint(m1, setOnlyBits=pbv) self.assertEqual(fp3.GetNumOnBits(), 0) fp3 = Chem.LayeredFingerprint(m1, setOnlyBits=fp2) self.assertEqual(fp3, fp2) m2 = Chem.MolFromSmiles('CC') fp4 = Chem.LayeredFingerprint(m2) atomCounts = [0] * m1.GetNumAtoms() fp3 = Chem.LayeredFingerprint(m1, setOnlyBits=fp4, atomCounts=atomCounts) self.assertEqual(atomCounts, [1, 3, 1, 1]) m2 = Chem.MolFromSmiles('CCC') fp4 = Chem.LayeredFingerprint(m2) atomCounts = [0] * m1.GetNumAtoms() fp3 = Chem.LayeredFingerprint(m1, setOnlyBits=fp4, atomCounts=atomCounts) self.assertEqual(atomCounts, [3, 6, 3, 3]) def test56LazySDMolSupplier(self): if not hasattr(Chem, 'CompressedSDMolSupplier'): return self.assertRaises(ValueError, lambda: Chem.CompressedSDMolSupplier('nosuchfile.sdf.gz')) fileN = os.path.join(RDConfig.RDBaseDir, 'Code', 'GraphMol', 'FileParsers', 'test_data', 'NCI_aids_few.sdf.gz') sdSup = Chem.CompressedSDMolSupplier(fileN) molNames = [ "48", "78", "128", "163", "164", "170", "180", "186", "192", "203", "210", "211", "213", "220", "229", "256" ] chgs192 = {8: 1, 11: 1, 15: -1, 18: -1, 20: 1, 21: 1, 23: -1, 25: -1} i = 0 for mol in sdSup: self.assertTrue(mol) self.assertTrue(mol.GetProp("_Name") == molNames[i]) i += 1 if (mol.GetProp("_Name") == "192"): # test parsed charges on one of the molecules for id in chgs192.keys(): self.assertTrue(mol.GetAtomWithIdx(id).GetFormalCharge() == chgs192[id]) self.assertEqual(i, 16) sdSup = Chem.CompressedSDMolSupplier(fileN) ns = [mol.GetProp("_Name") for mol in sdSup] self.assertTrue(ns == molNames) sdSup = Chem.CompressedSDMolSupplier(fileN, 0) for mol in sdSup: self.assertTrue(not mol.HasProp("numArom")) def test57AddRecursiveQuery(self): q1 = Chem.MolFromSmiles('CC') q2 = Chem.MolFromSmiles('CO') Chem.AddRecursiveQuery(q1, q2, 1) m1 = Chem.MolFromSmiles('OCC') self.assertTrue(m1.HasSubstructMatch(q2)) self.assertTrue(m1.HasSubstructMatch(q1)) self.assertTrue(m1.HasSubstructMatch(q1)) self.assertTrue(m1.GetSubstructMatch(q1) == (2, 1)) q3 = Chem.MolFromSmiles('CS') Chem.AddRecursiveQuery(q1, q3, 1) self.assertFalse(m1.HasSubstructMatch(q3)) self.assertFalse(m1.HasSubstructMatch(q1)) m2 = Chem.MolFromSmiles('OC(S)C') self.assertTrue(m2.HasSubstructMatch(q1)) self.assertTrue(m2.GetSubstructMatch(q1) == (3, 1)) m3 = Chem.MolFromSmiles('SCC') self.assertTrue(m3.HasSubstructMatch(q3)) self.assertFalse(m3.HasSubstructMatch(q1)) q1 = Chem.MolFromSmiles('CC') Chem.AddRecursiveQuery(q1, q2, 1) Chem.AddRecursiveQuery(q1, q3, 1, False) self.assertTrue(m3.HasSubstructMatch(q1)) self.assertTrue(m3.GetSubstructMatch(q1) == (2, 1)) def test58Issue2983794(self): fileN = os.path.join(RDConfig.RDBaseDir, 'Code', 'GraphMol', 'Wrap', 'test_data', 'issue2983794.sdf') m1 = Chem.MolFromMolFile(fileN) self.assertTrue(m1) em = Chem.EditableMol(m1) em.RemoveAtom(0) m2 = em.GetMol() Chem.Kekulize(m2) def test59Issue3007178(self): m = Chem.MolFromSmiles('CCC') a = m.GetAtomWithIdx(0) m = None self.assertEqual(Chem.MolToSmiles(a.GetOwningMol()), 'CCC') a = None m = Chem.MolFromSmiles('CCC') b = m.GetBondWithIdx(0) m = None self.assertEqual(Chem.MolToSmiles(b.GetOwningMol()), 'CCC') def test60SmilesWriterClose(self): fileN = os.path.join(RDConfig.RDBaseDir, 'Code', 'GraphMol', 'FileParsers', 'test_data', 'fewSmi.csv') smiSup = Chem.SmilesMolSupplier(fileN, delimiter=",", smilesColumn=1, nameColumn=0, titleLine=0) ms = [x for x in smiSup] ofile = os.path.join(RDConfig.RDBaseDir, 'Code', 'GraphMol', 'Wrap', 'test_data', 'outSmiles.txt') writer = Chem.SmilesWriter(ofile) for mol in ms: writer.write(mol) writer.close() newsup = Chem.SmilesMolSupplier(ofile) newms = [x for x in newsup] self.assertEqual(len(ms), len(newms)) def test61PathToSubmol(self): m = Chem.MolFromSmiles('CCCCCC1C(O)CC(O)N1C=CCO') env = Chem.FindAtomEnvironmentOfRadiusN(m, 2, 11) self.assertEqual(len(env), 8) amap = {} submol = Chem.PathToSubmol(m, env, atomMap=amap) self.assertEqual(submol.GetNumAtoms(), len(amap.keys())) self.assertEqual(submol.GetNumAtoms(), 9) smi = Chem.MolToSmiles(submol, rootedAtAtom=amap[11]) self.assertEqual(smi[0], 'N') refsmi = Chem.MolToSmiles(Chem.MolFromSmiles('N(C=C)(C(C)C)C(O)C')) csmi = Chem.MolToSmiles(Chem.MolFromSmiles(smi)) self.assertEqual(refsmi, csmi) def test62SmilesAndSmartsReplacements(self): mol = Chem.MolFromSmiles('C{branch}C', replacements={'{branch}': 'C1(CC1)'}) self.assertEqual(mol.GetNumAtoms(), 5) mol = Chem.MolFromSmarts('C{branch}C', replacements={'{branch}': 'C1(CC1)'}) self.assertEqual(mol.GetNumAtoms(), 5) mol = Chem.MolFromSmiles('C{branch}C{acid}', replacements={ '{branch}': 'C1(CC1)', '{acid}': "C(=O)O" }) self.assertEqual(mol.GetNumAtoms(), 8) def test63Issue3313539(self): fileN = os.path.join(RDConfig.RDBaseDir, 'Code', 'GraphMol', 'FileParsers', 'test_data', 'rgroups1.mol') m = Chem.MolFromMolFile(fileN) self.assertTrue(m is not None) at = m.GetAtomWithIdx(3) self.assertTrue(at is not None) self.assertTrue(at.HasProp('_MolFileRLabel')) p = at.GetProp('_MolFileRLabel') self.assertEqual(p, '2') self.assertEqual(Chem.GetAtomRLabel(at), 2) at = m.GetAtomWithIdx(4) self.assertTrue(at is not None) self.assertTrue(at.HasProp('_MolFileRLabel')) p = at.GetProp('_MolFileRLabel') self.assertEqual(p, '1') self.assertEqual(Chem.GetAtomRLabel(at), 1) def test64MoleculeCleanup(self): m = Chem.MolFromSmiles('CN(=O)=O', False) self.assertTrue(m) self.assertTrue(m.GetAtomWithIdx(1).GetFormalCharge()==0 and \ m.GetAtomWithIdx(2).GetFormalCharge()==0 and \ m.GetAtomWithIdx(3).GetFormalCharge()==0) self.assertTrue(m.GetBondBetweenAtoms(1,3).GetBondType()==Chem.BondType.DOUBLE and \ m.GetBondBetweenAtoms(1,2).GetBondType()==Chem.BondType.DOUBLE ) Chem.Cleanup(m) m.UpdatePropertyCache() self.assertTrue(m.GetAtomWithIdx(1).GetFormalCharge()==1 and \ (m.GetAtomWithIdx(2).GetFormalCharge()==-1 or \ m.GetAtomWithIdx(3).GetFormalCharge()==-1)) self.assertTrue(m.GetBondBetweenAtoms(1,3).GetBondType()==Chem.BondType.SINGLE or \ m.GetBondBetweenAtoms(1,2).GetBondType()==Chem.BondType.SINGLE ) def test65StreamSupplier(self): fileN = os.path.join(RDConfig.RDBaseDir, 'Code', 'GraphMol', 'FileParsers', 'test_data', 'NCI_aids_few.sdf.gz') molNames = [ "48", "78", "128", "163", "164", "170", "180", "186", "192", "203", "210", "211", "213", "220", "229", "256" ] inf = gzip.open(fileN) if 0: sb = Chem.streambuf(inf) suppl = Chem.ForwardSDMolSupplier(sb) else: suppl = Chem.ForwardSDMolSupplier(inf) i = 0 while not suppl.atEnd(): mol = six.next(suppl) self.assertTrue(mol) self.assertTrue(mol.GetProp("_Name") == molNames[i]) i += 1 self.assertEqual(i, 16) # make sure we have object ownership preserved inf = gzip.open(fileN) suppl = Chem.ForwardSDMolSupplier(inf) inf = None i = 0 while not suppl.atEnd(): mol = six.next(suppl) self.assertTrue(mol) self.assertTrue(mol.GetProp("_Name") == molNames[i]) i += 1 self.assertEqual(i, 16) def testMaeStreamSupplier(self): try: MaeMolSupplier = Chem.MaeMolSupplier except AttributeError: # Built without Maestro support, return w/o testing return fileN = os.path.join(RDConfig.RDBaseDir, 'Code', 'GraphMol', 'FileParsers', 'test_data', 'NCI_aids_few.maegz') molNames = [ "48", "78", "128", "163", "164", "170", "180", "186", "192", "203", "210", "211", "213", "220", "229", "256" ] inf = gzip.open(fileN) suppl = MaeMolSupplier(inf) i = 0 while not suppl.atEnd(): mol = six.next(suppl) self.assertTrue(mol) self.assertTrue(mol.GetProp("_Name") == molNames[i]) i += 1 self.assertEqual(i, 16) # make sure we have object ownership preserved inf = gzip.open(fileN) suppl = MaeMolSupplier(inf) inf = None i = 0 while not suppl.atEnd(): mol = six.next(suppl) self.assertTrue(mol) self.assertTrue(mol.GetProp("_Name") == molNames[i]) i += 1 self.assertEqual(i, 16) def testMaeFileSupplier(self): try: MaeMolSupplier = Chem.MaeMolSupplier except AttributeError: # Built without Maestro support, return w/o testing return fileN = os.path.join(RDConfig.RDBaseDir, 'Code', 'GraphMol', 'FileParsers', 'test_data', 'NCI_aids_few.mae') molNames = [ "48", "78", "128", "163", "164", "170", "180", "186", "192", "203", "210", "211", "213", "220", "229", "256" ] suppl = MaeMolSupplier(fileN) i = 0 while not suppl.atEnd(): mol = six.next(suppl) self.assertTrue(mol) self.assertTrue(mol.GetProp("_Name") == molNames[i]) i += 1 self.assertEqual(i, 16) def test66StreamSupplierIter(self): fileN = os.path.join(RDConfig.RDBaseDir, 'Code', 'GraphMol', 'FileParsers', 'test_data', 'NCI_aids_few.sdf.gz') inf = gzip.open(fileN) if 0: sb = Chem.streambuf(inf) suppl = Chem.ForwardSDMolSupplier(sb) else: suppl = Chem.ForwardSDMolSupplier(inf) molNames = [ "48", "78", "128", "163", "164", "170", "180", "186", "192", "203", "210", "211", "213", "220", "229", "256" ] i = 0 for mol in suppl: self.assertTrue(mol) self.assertTrue(mol.GetProp("_Name") == molNames[i]) i += 1 self.assertEqual(i, 16) def test67StreamSupplierStringIO(self): fileN = os.path.join(RDConfig.RDBaseDir, 'Code', 'GraphMol', 'FileParsers', 'test_data', 'NCI_aids_few.sdf.gz') if six.PY3: from io import BytesIO sio = BytesIO(gzip.open(fileN).read()) else: import StringIO sio = StringIO.StringIO(gzip.open(fileN).read()) suppl = Chem.ForwardSDMolSupplier(sio) molNames = [ "48", "78", "128", "163", "164", "170", "180", "186", "192", "203", "210", "211", "213", "220", "229", "256" ] i = 0 for mol in suppl: self.assertTrue(mol) self.assertTrue(mol.GetProp("_Name") == molNames[i]) i += 1 self.assertEqual(i, 16) def test68ForwardSupplierUsingFilename(self): fileN = os.path.join(RDConfig.RDBaseDir, 'Code', 'GraphMol', 'FileParsers', 'test_data', 'NCI_aids_few.sdf') suppl = Chem.ForwardSDMolSupplier(fileN) molNames = [ "48", "78", "128", "163", "164", "170", "180", "186", "192", "203", "210", "211", "213", "220", "229", "256" ] i = 0 for mol in suppl: self.assertTrue(mol) self.assertTrue(mol.GetProp("_Name") == molNames[i]) i += 1 self.assertEqual(i, 16) self.assertRaises(IOError, lambda: Chem.ForwardSDMolSupplier('nosuchfile.sdf')) def test69StreamSupplierStreambuf(self): fileN = os.path.join(RDConfig.RDBaseDir, 'Code', 'GraphMol', 'FileParsers', 'test_data', 'NCI_aids_few.sdf.gz') sb = rdBase.streambuf(gzip.open(fileN)) suppl = Chem.ForwardSDMolSupplier(sb) molNames = [ "48", "78", "128", "163", "164", "170", "180", "186", "192", "203", "210", "211", "213", "220", "229", "256" ] i = 0 for mol in suppl: self.assertTrue(mol) self.assertTrue(mol.GetProp("_Name") == molNames[i]) i += 1 self.assertEqual(i, 16) def test70StreamSDWriter(self): if six.PY3: from io import BytesIO, StringIO else: from StringIO import StringIO fileN = os.path.join(RDConfig.RDBaseDir, 'Code', 'GraphMol', 'FileParsers', 'test_data', 'NCI_aids_few.sdf.gz') inf = gzip.open(fileN) suppl = Chem.ForwardSDMolSupplier(inf) osio = StringIO() w = Chem.SDWriter(osio) molNames = [ "48", "78", "128", "163", "164", "170", "180", "186", "192", "203", "210", "211", "213", "220", "229", "256" ] i = 0 for mol in suppl: self.assertTrue(mol) self.assertTrue(mol.GetProp("_Name") == molNames[i]) w.write(mol) i += 1 self.assertEqual(i, 16) w.flush() w = None if six.PY3: txt = osio.getvalue().encode() isio = BytesIO(txt) else: isio = StringIO(osio.getvalue()) suppl = Chem.ForwardSDMolSupplier(isio) i = 0 for mol in suppl: self.assertTrue(mol) self.assertTrue(mol.GetProp("_Name") == molNames[i]) i += 1 self.assertEqual(i, 16) def test71StreamSmilesWriter(self): from rdkit.six.moves import StringIO fileN = os.path.join(RDConfig.RDBaseDir, 'Code', 'GraphMol', 'FileParsers', 'test_data', 'esters.sdf') suppl = Chem.ForwardSDMolSupplier(fileN) osio = StringIO() w = Chem.SmilesWriter(osio) ms = [x for x in suppl] w.SetProps(ms[0].GetPropNames()) i = 0 for mol in ms: self.assertTrue(mol) w.write(mol) i += 1 self.assertEqual(i, 6) w.flush() w = None txt = osio.getvalue() self.assertEqual(txt.count('ID'), 1) self.assertEqual(txt.count('\n'), 7) def test72StreamTDTWriter(self): from rdkit.six.moves import StringIO fileN = os.path.join(RDConfig.RDBaseDir, 'Code', 'GraphMol', 'FileParsers', 'test_data', 'esters.sdf') suppl = Chem.ForwardSDMolSupplier(fileN) osio = StringIO() w = Chem.TDTWriter(osio) ms = [x for x in suppl] w.SetProps(ms[0].GetPropNames()) i = 0 for mol in ms: self.assertTrue(mol) w.write(mol) i += 1 self.assertEqual(i, 6) w.flush() w = None txt = osio.getvalue() self.assertEqual(txt.count('ID'), 6) self.assertEqual(txt.count('NAME'), 6) def test73SanitizationOptions(self): m = Chem.MolFromSmiles('c1ccccc1', sanitize=False) res = Chem.SanitizeMol(m, catchErrors=True) self.assertEqual(res, 0) m = Chem.MolFromSmiles('c1cccc1', sanitize=False) res = Chem.SanitizeMol(m, catchErrors=True) self.assertEqual(res, Chem.SanitizeFlags.SANITIZE_KEKULIZE) m = Chem.MolFromSmiles('CC(C)(C)(C)C', sanitize=False) res = Chem.SanitizeMol(m, catchErrors=True) self.assertEqual(res, Chem.SanitizeFlags.SANITIZE_PROPERTIES) m = Chem.MolFromSmiles('c1cccc1', sanitize=False) res = Chem.SanitizeMol( m, sanitizeOps=Chem.SanitizeFlags.SANITIZE_ALL ^ Chem.SanitizeFlags.SANITIZE_KEKULIZE, catchErrors=True) self.assertEqual(res, Chem.SanitizeFlags.SANITIZE_NONE) def test74Issue3510149(self): mol = Chem.MolFromSmiles("CCC1CNCC1CC") atoms = mol.GetAtoms() mol = None for atom in atoms: idx = atom.GetIdx() p = atom.GetOwningMol().GetNumAtoms() mol = Chem.MolFromSmiles("CCC1CNCC1CC") bonds = mol.GetBonds() mol = None for bond in bonds: idx = bond.GetIdx() p = atom.GetOwningMol().GetNumAtoms() mol = Chem.MolFromSmiles("CCC1CNCC1CC") bond = mol.GetBondBetweenAtoms(0, 1) mol = None idx = bond.GetBeginAtomIdx() p = bond.GetOwningMol().GetNumAtoms() fileN = os.path.join(RDConfig.RDBaseDir, 'Code', 'GraphMol', 'FileParsers', 'test_data', 'NCI_aids_few.sdf') sdSup = Chem.SDMolSupplier(fileN) mol = six.next(sdSup) nats = mol.GetNumAtoms() conf = mol.GetConformer() mol = None self.assertEqual(nats, conf.GetNumAtoms()) conf.GetOwningMol().GetProp("_Name") def test75AllBondsExplicit(self): m = Chem.MolFromSmiles("CCC") smi = Chem.MolToSmiles(m) self.assertEqual(smi, "CCC") smi = Chem.MolToSmiles(m, allBondsExplicit=True) self.assertEqual(smi, "C-C-C") m = Chem.MolFromSmiles("c1ccccc1") smi = Chem.MolToSmiles(m) self.assertEqual(smi, "c1ccccc1") smi = Chem.MolToSmiles(m, allBondsExplicit=True) self.assertEqual(smi, "c1:c:c:c:c:c:1") def test76VeryLargeMolecule(self): # this is sf.net issue 3524984 smi = '[C@H](F)(Cl)' + 'c1cc[nH]c1' * 500 + '[C@H](F)(Cl)' m = Chem.MolFromSmiles(smi) self.assertTrue(m) self.assertEqual(m.GetNumAtoms(), 2506) scs = Chem.FindMolChiralCenters(m) self.assertEqual(len(scs), 2) def test77MolFragmentToSmiles(self): smi = "OC1CC1CC" m = Chem.MolFromSmiles(smi) fsmi = Chem.MolFragmentToSmiles(m, [1, 2, 3]) self.assertEqual(fsmi, "C1CC1") fsmi = Chem.MolFragmentToSmiles(m, [1, 2, 3], bondsToUse=[1, 2, 5]) self.assertEqual(fsmi, "C1CC1") fsmi = Chem.MolFragmentToSmiles(m, [1, 2, 3], bondsToUse=[1, 2]) self.assertEqual(fsmi, "CCC") fsmi = Chem.MolFragmentToSmiles(m, [1, 2, 3], atomSymbols=["", "[A]", "[C]", "[B]", "", ""]) self.assertEqual(fsmi, "[A]1[B][C]1") fsmi = Chem.MolFragmentToSmiles(m, [1, 2, 3], bondSymbols=["", "%", "%", "", "", "%"]) self.assertEqual(fsmi, "C1%C%C%1") smi = "c1ccccc1C" m = Chem.MolFromSmiles(smi) fsmi = Chem.MolFragmentToSmiles(m, range(6)) self.assertEqual(fsmi, "c1ccccc1") Chem.Kekulize(m) fsmi = Chem.MolFragmentToSmiles(m, range(6), kekuleSmiles=True) self.assertEqual(fsmi, "C1=CC=CC=C1") fsmi = Chem.MolFragmentToSmiles(m, range(6), atomSymbols=["[C]"] * 7, kekuleSmiles=True) self.assertEqual(fsmi, "[C]1=[C][C]=[C][C]=[C]1") self.assertRaises(ValueError, lambda: Chem.MolFragmentToSmiles(m, [])) def test78AtomAndBondProps(self): m = Chem.MolFromSmiles('c1ccccc1') at = m.GetAtomWithIdx(0) self.assertFalse(at.HasProp('foo')) at.SetProp('foo', 'bar') self.assertTrue(at.HasProp('foo')) self.assertEqual(at.GetProp('foo'), 'bar') bond = m.GetBondWithIdx(0) self.assertFalse(bond.HasProp('foo')) bond.SetProp('foo', 'bar') self.assertTrue(bond.HasProp('foo')) self.assertEqual(bond.GetProp('foo'), 'bar') def test79AddRecursiveStructureQueries(self): qs = {'carbonyl': Chem.MolFromSmiles('CO'), 'amine': Chem.MolFromSmiles('CN')} q = Chem.MolFromSmiles('CCC') q.GetAtomWithIdx(0).SetProp('query', 'carbonyl,amine') Chem.MolAddRecursiveQueries(q, qs, 'query') m = Chem.MolFromSmiles('CCCO') self.assertTrue(m.HasSubstructMatch(q)) m = Chem.MolFromSmiles('CCCN') self.assertTrue(m.HasSubstructMatch(q)) m = Chem.MolFromSmiles('CCCC') self.assertFalse(m.HasSubstructMatch(q)) def test80ParseMolQueryDefFile(self): fileN = os.path.join(RDConfig.RDBaseDir, 'Code', 'GraphMol', 'ChemTransforms', 'testData', 'query_file1.txt') d = Chem.ParseMolQueryDefFile(fileN, standardize=False) self.assertTrue('CarboxylicAcid' in d) m = Chem.MolFromSmiles('CC(=O)O') self.assertTrue(m.HasSubstructMatch(d['CarboxylicAcid'])) self.assertFalse(m.HasSubstructMatch(d['CarboxylicAcid.Aromatic'])) d = Chem.ParseMolQueryDefFile(fileN) self.assertTrue('carboxylicacid' in d) self.assertFalse('CarboxylicAcid' in d) def test81Issue275(self): smi = Chem.MolToSmiles( Chem.MurckoDecompose(Chem.MolFromSmiles('CCCCC[C@H]1CC[C@H](C(=O)O)CC1'))) self.assertEqual(smi, 'C1CCCCC1') def test82Issue288(self): m = Chem.MolFromSmiles('CC*') m.GetAtomWithIdx(2).SetProp('molAtomMapNumber', '30') smi = Chem.MolToSmiles(m) self.assertEqual(smi, 'CC[*:30]') # try newer api m = Chem.MolFromSmiles('CC*') m.GetAtomWithIdx(2).SetAtomMapNum(30) smi = Chem.MolToSmiles(m) self.assertEqual(smi, 'CC[*:30]') def test83GitHubIssue19(self): fileN = os.path.join(RDConfig.RDBaseDir, 'Code', 'GraphMol', 'FileParsers', 'test_data', 'empty2.sdf') sdSup = Chem.SDMolSupplier(fileN) self.assertTrue(sdSup.atEnd()) self.assertRaises(IndexError, lambda: sdSup[0]) sdSup.SetData('') self.assertTrue(sdSup.atEnd()) self.assertRaises(IndexError, lambda: sdSup[0]) sdSup = Chem.SDMolSupplier(fileN) self.assertRaises(IndexError, lambda: sdSup[0]) sdSup.SetData('') self.assertRaises(IndexError, lambda: sdSup[0]) sdSup = Chem.SDMolSupplier(fileN) self.assertEqual(len(sdSup), 0) sdSup.SetData('') self.assertEqual(len(sdSup), 0) def test84PDBBasics(self): fileN = os.path.join(RDConfig.RDBaseDir, 'Code', 'GraphMol', 'FileParsers', 'test_data', '1CRN.pdb') m = Chem.MolFromPDBFile(fileN, proximityBonding=False) self.assertEqual(m.GetNumAtoms(), 327) self.assertEqual(m.GetNumBonds(), 3) m = Chem.MolFromPDBFile(fileN) self.assertTrue(m is not None) self.assertEqual(m.GetNumAtoms(), 327) self.assertEqual(m.GetNumBonds(), 337) self.assertTrue(m.GetAtomWithIdx(0).GetPDBResidueInfo()) self.assertEqual(m.GetAtomWithIdx(0).GetPDBResidueInfo().GetName(), " N ") self.assertEqual(m.GetAtomWithIdx(0).GetPDBResidueInfo().GetResidueName(), "THR") self.assertAlmostEqual(m.GetAtomWithIdx(0).GetPDBResidueInfo().GetTempFactor(), 13.79, 2) m = Chem.MolFromPDBBlock(Chem.MolToPDBBlock(m)) self.assertEqual(m.GetNumAtoms(), 327) self.assertEqual(m.GetNumBonds(), 337) self.assertTrue(m.GetAtomWithIdx(0).GetPDBResidueInfo()) self.assertEqual(m.GetAtomWithIdx(0).GetPDBResidueInfo().GetName(), " N ") self.assertEqual(m.GetAtomWithIdx(0).GetPDBResidueInfo().GetResidueName(), "THR") self.assertAlmostEqual(m.GetAtomWithIdx(0).GetPDBResidueInfo().GetTempFactor(), 13.79, 2) # test multivalent Hs fileN = os.path.join(RDConfig.RDBaseDir, 'Code', 'GraphMol', 'FileParsers', 'test_data', '2c92_hypervalentH.pdb') mol = Chem.MolFromPDBFile(fileN, sanitize=False, removeHs=False) atom = mol.GetAtomWithIdx(84) self.assertEqual(atom.GetAtomicNum(), 1) # is it H self.assertEqual(atom.GetDegree(), 1) # H should have 1 bond for n in atom.GetNeighbors(): # Check if neighbor is from the same residue self.assertEqual(atom.GetPDBResidueInfo().GetResidueName(), n.GetPDBResidueInfo().GetResidueName()) # test unbinding metals (ZN) fileN = os.path.join(RDConfig.RDBaseDir, 'Code', 'GraphMol', 'FileParsers', 'test_data', '1ps3_zn.pdb') mol = Chem.MolFromPDBFile(fileN, sanitize=False, removeHs=False) atom = mol.GetAtomWithIdx(40) self.assertEqual(atom.GetAtomicNum(), 30) # is it Zn self.assertEqual(atom.GetDegree(), 4) # Zn should have 4 zero-order bonds self.assertEqual(atom.GetExplicitValence(), 0) bonds_order = [bond.GetBondType() for bond in atom.GetBonds()] self.assertEqual(bonds_order, [Chem.BondType.ZERO] * atom.GetDegree()) # test metal bonds without proximity bonding mol = Chem.MolFromPDBFile(fileN, sanitize=False, removeHs=False, proximityBonding=False) atom = mol.GetAtomWithIdx(40) self.assertEqual(atom.GetAtomicNum(), 30) # is it Zn self.assertEqual(atom.GetDegree(), 4) # Zn should have 4 zero-order bonds self.assertEqual(atom.GetExplicitValence(), 0) bonds_order = [bond.GetBondType() for bond in atom.GetBonds()] self.assertEqual(bonds_order, [Chem.BondType.ZERO] * atom.GetDegree()) # test unbinding HOHs fileN = os.path.join(RDConfig.RDBaseDir, 'Code', 'GraphMol', 'FileParsers', 'test_data', '2vnf_bindedHOH.pdb') mol = Chem.MolFromPDBFile(fileN, sanitize=False, removeHs=False) atom = mol.GetAtomWithIdx(10) self.assertEqual(atom.GetPDBResidueInfo().GetResidueName(), 'HOH') self.assertEqual(atom.GetDegree(), 0) # HOH should have no bonds # test metal bonding in ligand fileN = os.path.join(RDConfig.RDBaseDir, 'Code', 'GraphMol', 'FileParsers', 'test_data', '2dej_APW.pdb') mol = Chem.MolFromPDBFile(fileN, sanitize=False, removeHs=False) atom = mol.GetAtomWithIdx(6) self.assertEqual(atom.GetAtomicNum(), 12) self.assertEqual(atom.GetDegree(), 2) atom = mol.GetAtomWithIdx(35) self.assertEqual(atom.GetPDBResidueInfo().GetResidueName(), 'HOH') self.assertEqual(atom.GetDegree(), 0) def test85MolCopying(self): m = Chem.MolFromSmiles('C1CC1[C@H](F)Cl') m.SetProp('foo', 'bar') m2 = Chem.Mol(m) self.assertEqual(Chem.MolToSmiles(m, True), Chem.MolToSmiles(m2, True)) self.assertTrue(m2.HasProp('foo')) self.assertEqual(m2.GetProp('foo'), 'bar') ri = m2.GetRingInfo() self.assertTrue(ri) self.assertEqual(ri.NumRings(), 1) def test85MolCopying2(self): import copy m1 = Chem.MolFromSmiles('CC') m1.SetProp('Foo', 'bar') m1.foo = [1] m2 = copy.copy(m1) m3 = copy.copy(m2) m4 = copy.deepcopy(m1) m5 = copy.deepcopy(m2) m6 = copy.deepcopy(m4) self.assertEquals(m1.GetProp('Foo'), 'bar') self.assertEquals(m2.GetProp('Foo'), 'bar') self.assertEquals(m3.GetProp('Foo'), 'bar') self.assertEquals(m4.GetProp('Foo'), 'bar') self.assertEquals(m5.GetProp('Foo'), 'bar') self.assertEquals(m6.GetProp('Foo'), 'bar') m2.foo.append(4) self.assertEquals(m1.foo, [1, 4]) self.assertEquals(m2.foo, [1, 4]) self.assertEquals(m3.foo, [1, 4]) self.assertEquals(m4.foo, [1]) self.assertEquals(m5.foo, [1]) self.assertEquals(m6.foo, [1]) m7 = Chem.RWMol(m1) self.failIf(hasattr(m7, 'foo')) m7.foo = [1] m8 = copy.copy(m7) m9 = copy.deepcopy(m7) m8.foo.append(4) self.assertEquals(m7.GetProp('Foo'), 'bar') self.assertEquals(m8.GetProp('Foo'), 'bar') self.assertEquals(m9.GetProp('Foo'), 'bar') self.assertEquals(m8.foo, [1, 4]) self.assertEquals(m9.foo, [1]) def test86MolRenumbering(self): import random m = Chem.MolFromSmiles('C[C@H]1CC[C@H](C/C=C/[C@H](F)Cl)CC1') cSmi = Chem.MolToSmiles(m, True) for i in range(m.GetNumAtoms()): ans = list(range(m.GetNumAtoms())) random.shuffle(ans) m2 = Chem.RenumberAtoms(m, ans) nSmi = Chem.MolToSmiles(m2, True) self.assertEqual(cSmi, nSmi) def test87FragmentOnBonds(self): m = Chem.MolFromSmiles('CC1CC(O)C1CCC1CC1') bis = m.GetSubstructMatches(Chem.MolFromSmarts('[!R][R]')) bs = [] labels = [] for bi in bis: b = m.GetBondBetweenAtoms(bi[0], bi[1]) if b.GetBeginAtomIdx() == bi[0]: labels.append((10, 1)) else: labels.append((1, 10)) bs.append(b.GetIdx()) nm = Chem.FragmentOnBonds(m, bs) frags = Chem.GetMolFrags(nm) self.assertEqual(len(frags), 5) self.assertEqual(frags, ((0, 12), (1, 2, 3, 5, 11, 14, 16), (4, 13), (6, 7, 15, 18), (8, 9, 10, 17))) smi = Chem.MolToSmiles(nm, True) self.assertEqual(smi, '*C1CC([4*])C1[6*].[1*]C.[3*]O.[5*]CC[8*].[7*]C1CC1') nm = Chem.FragmentOnBonds(m, bs, dummyLabels=labels) frags = Chem.GetMolFrags(nm) self.assertEqual(len(frags), 5) self.assertEqual(frags, ((0, 12), (1, 2, 3, 5, 11, 14, 16), (4, 13), (6, 7, 15, 18), (8, 9, 10, 17))) smi = Chem.MolToSmiles(nm, True) self.assertEqual(smi, '[1*]C.[1*]CC[1*].[1*]O.[10*]C1CC([10*])C1[10*].[10*]C1CC1') m = Chem.MolFromSmiles('CCC(=O)CC(=O)C') bis = m.GetSubstructMatches(Chem.MolFromSmarts('C=O')) bs = [] for bi in bis: b = m.GetBondBetweenAtoms(bi[0], bi[1]) bs.append(b.GetIdx()) bts = [Chem.BondType.DOUBLE] * len(bs) nm = Chem.FragmentOnBonds(m, bs, bondTypes=bts) frags = Chem.GetMolFrags(nm) self.assertEqual(len(frags), 3) smi = Chem.MolToSmiles(nm, True) self.assertEqual(smi, '[2*]=O.[3*]=C(CC)CC(=[6*])C.[5*]=O') # github issue 430: m = Chem.MolFromSmiles('OCCCCN') self.assertRaises(ValueError, lambda: Chem.FragmentOnBonds(m, ())) def test88QueryAtoms(self): from rdkit.Chem import rdqueries m = Chem.MolFromSmiles('c1nc(C)n(CC)c1') qa = rdqueries.ExplicitDegreeEqualsQueryAtom(3) l = tuple([x.GetIdx() for x in m.GetAtomsMatchingQuery(qa)]) self.assertEqual(l, (2, 4)) qa.ExpandQuery(rdqueries.AtomNumEqualsQueryAtom(6, negate=True)) l = tuple([x.GetIdx() for x in m.GetAtomsMatchingQuery(qa)]) self.assertEqual(l, (4, )) qa = rdqueries.ExplicitDegreeEqualsQueryAtom(3) qa.ExpandQuery( rdqueries.AtomNumEqualsQueryAtom(6, negate=True), how=Chem.CompositeQueryType.COMPOSITE_OR) l = tuple([x.GetIdx() for x in m.GetAtomsMatchingQuery(qa)]) self.assertEqual(l, (1, 2, 4)) qa = rdqueries.ExplicitDegreeEqualsQueryAtom(3) qa.ExpandQuery( rdqueries.AtomNumEqualsQueryAtom(6, negate=True), how=Chem.CompositeQueryType.COMPOSITE_XOR) l = tuple([x.GetIdx() for x in m.GetAtomsMatchingQuery(qa)]) self.assertEqual(l, (1, 2)) qa = rdqueries.ExplicitDegreeGreaterQueryAtom(2) l = tuple([x.GetIdx() for x in m.GetAtomsMatchingQuery(qa)]) self.assertEqual(l, (2, 4)) qa = rdqueries.ExplicitDegreeLessQueryAtom(2) l = tuple([x.GetIdx() for x in m.GetAtomsMatchingQuery(qa)]) self.assertEqual(l, (3, 6)) m = Chem.MolFromSmiles('N[CH][CH]') qa = rdqueries.NumRadicalElectronsGreaterQueryAtom(0) l = tuple([x.GetIdx() for x in m.GetAtomsMatchingQuery(qa)]) self.assertEqual(l, (1, 2)) qa = rdqueries.NumRadicalElectronsGreaterQueryAtom(1) l = tuple([x.GetIdx() for x in m.GetAtomsMatchingQuery(qa)]) self.assertEqual(l, (2, )) m = Chem.MolFromSmiles('F[C@H](Cl)C') qa = rdqueries.HasChiralTagQueryAtom() l = tuple([x.GetIdx() for x in m.GetAtomsMatchingQuery(qa)]) self.assertEqual(l, (1, )) qa = rdqueries.MissingChiralTagQueryAtom() l = tuple([x.GetIdx() for x in m.GetAtomsMatchingQuery(qa)]) self.assertEqual(l, ()) m = Chem.MolFromSmiles('F[CH](Cl)C') qa = rdqueries.HasChiralTagQueryAtom() l = tuple([x.GetIdx() for x in m.GetAtomsMatchingQuery(qa)]) self.assertEqual(l, ()) qa = rdqueries.MissingChiralTagQueryAtom() l = tuple([x.GetIdx() for x in m.GetAtomsMatchingQuery(qa)]) self.assertEqual(l, (1, )) m = Chem.MolFromSmiles('CNCON') qa = rdqueries.NumHeteroatomNeighborsEqualsQueryAtom(2) l = tuple([x.GetIdx() for x in m.GetAtomsMatchingQuery(qa)]) self.assertEqual(l, (2, )) qa = rdqueries.NumHeteroatomNeighborsGreaterQueryAtom(0) l = tuple([x.GetIdx() for x in m.GetAtomsMatchingQuery(qa)]) self.assertEqual(l, (0, 2, 3, 4)) def test89UnicodeInput(self): m = Chem.MolFromSmiles(u'c1ccccc1') self.assertTrue(m is not None) self.assertEqual(m.GetNumAtoms(), 6) m = Chem.MolFromSmarts(u'c1ccccc1') self.assertTrue(m is not None) self.assertEqual(m.GetNumAtoms(), 6) def test90FragmentOnSomeBonds(self): m = Chem.MolFromSmiles('OCCCCN') pieces = Chem.FragmentOnSomeBonds(m, (0, 2, 4), 2) self.assertEqual(len(pieces), 3) frags = Chem.GetMolFrags(pieces[0]) self.assertEqual(len(frags), 3) self.assertEqual(len(frags[0]), 2) self.assertEqual(len(frags[1]), 4) self.assertEqual(len(frags[2]), 4) frags = Chem.GetMolFrags(pieces[1]) self.assertEqual(len(frags), 3) self.assertEqual(len(frags[0]), 2) self.assertEqual(len(frags[1]), 6) self.assertEqual(len(frags[2]), 2) frags = Chem.GetMolFrags(pieces[2]) self.assertEqual(len(frags), 3) self.assertEqual(len(frags[0]), 4) self.assertEqual(len(frags[1]), 4) self.assertEqual(len(frags[2]), 2) pieces, cpa = Chem.FragmentOnSomeBonds(m, (0, 2, 4), 2, returnCutsPerAtom=True) self.assertEqual(len(pieces), 3) self.assertEqual(len(cpa), 3) self.assertEqual(len(cpa[0]), m.GetNumAtoms()) # github issue 430: m = Chem.MolFromSmiles('OCCCCN') self.assertRaises(ValueError, lambda: Chem.FragmentOnSomeBonds(m, ())) pieces = Chem.FragmentOnSomeBonds(m, (0, 2, 4), 0) self.assertEqual(len(pieces), 0) def test91RankAtoms(self): m = Chem.MolFromSmiles('ONCS.ONCS') ranks = Chem.CanonicalRankAtoms(m, breakTies=False) self.assertEqual(list(ranks[0:4]), list(ranks[4:])) m = Chem.MolFromSmiles("c1ccccc1") ranks = Chem.CanonicalRankAtoms(m, breakTies=False) for x in ranks: self.assertEqual(x, 0) m = Chem.MolFromSmiles("C1NCN1") ranks = Chem.CanonicalRankAtoms(m, breakTies=False) self.assertEqual(ranks[0], ranks[2]) self.assertEqual(ranks[1], ranks[3]) def test92RankAtomsInFragment(self): m = Chem.MolFromSmiles('ONCS.ONCS') ranks = Chem.CanonicalRankAtomsInFragment(m, [0, 1, 2, 3], [0, 1, 2]) ranks2 = Chem.CanonicalRankAtomsInFragment(m, [4, 5, 6, 7], [3, 4, 5]) self.assertEquals(list(ranks[0:4]), list(ranks2[4:])) self.assertEquals(list(ranks[4:]), [-1] * 4) self.assertEquals(list(ranks2[0:4]), [-1] * 4) # doc tests mol = Chem.MolFromSmiles('C1NCN1.C1NCN1') self.assertEquals( list(Chem.CanonicalRankAtomsInFragment(mol, atomsToUse=range(0, 4), breakTies=False)), [4, 6, 4, 6, -1, -1, -1, -1]) self.assertEquals( list(Chem.CanonicalRankAtomsInFragment(mol, atomsToUse=range(4, 8), breakTies=False)), [-1, -1, -1, -1, 4, 6, 4, 6]) def test93RWMolsAsROMol(self): """ test the RWMol class as a proper ROMol """ mol = Chem.MolFromSmiles('C1CCC1') self.assertTrue(type(mol) == Chem.Mol) rwmol = Chem.RWMol(mol) self.assertEqual(Chem.MolToSmiles(rwmol, True), Chem.MolToSmiles(rwmol.GetMol())) newAt = Chem.Atom(8) rwmol.ReplaceAtom(0, newAt) self.assertEqual(Chem.MolToSmiles(rwmol, True), Chem.MolToSmiles(rwmol.GetMol())) def test94CopyWithConfs(self): """ test copying Mols with some conformers """ fileN = os.path.join(RDConfig.RDBaseDir, 'Code', 'GraphMol', 'FileParsers', 'test_data', 'cmpd2.tpl') m1 = Chem.MolFromTPLFile(fileN) self.assertTrue(m1 is not None) self.assertEquals(m1.GetNumAtoms(), 12) self.assertEquals(m1.GetNumConformers(), 2) self.assertEquals(m1.GetConformer(0).GetNumAtoms(), 12) self.assertEquals(m1.GetConformer(1).GetNumAtoms(), 12) m2 = Chem.Mol(m1) self.assertEquals(m2.GetNumAtoms(), 12) self.assertEquals(m2.GetNumConformers(), 2) self.assertEquals(m2.GetConformer(0).GetNumAtoms(), 12) self.assertEquals(m2.GetConformer(1).GetNumAtoms(), 12) m2 = Chem.Mol(m1, False, 0) self.assertEquals(m2.GetNumAtoms(), 12) self.assertEquals(m2.GetNumConformers(), 1) self.assertEquals(m2.GetConformer(0).GetNumAtoms(), 12) m2 = Chem.Mol(m1, False, 1) self.assertEquals(m2.GetNumAtoms(), 12) self.assertEquals(m2.GetNumConformers(), 1) self.assertEquals(m2.GetConformer(1).GetNumAtoms(), 12) m2 = Chem.Mol(m1, True) self.assertTrue(m2.GetNumAtoms() == 12) self.assertTrue(m2.GetNumConformers() == 0) m2 = Chem.RWMol(m1) self.assertEquals(m2.GetNumAtoms(), 12) self.assertEquals(m2.GetNumConformers(), 2) self.assertEquals(m2.GetConformer(0).GetNumAtoms(), 12) self.assertEquals(m2.GetConformer(1).GetNumAtoms(), 12) m2 = Chem.RWMol(m1, False, 0) self.assertEquals(m2.GetNumAtoms(), 12) self.assertEquals(m2.GetNumConformers(), 1) self.assertEquals(m2.GetConformer(0).GetNumAtoms(), 12) m2 = Chem.RWMol(m1, False, 1) self.assertEquals(m2.GetNumAtoms(), 12) self.assertEquals(m2.GetNumConformers(), 1) self.assertEquals(m2.GetConformer(1).GetNumAtoms(), 12) m2 = Chem.RWMol(m1, True) self.assertTrue(m2.GetNumAtoms() == 12) self.assertTrue(m2.GetNumConformers() == 0) def testAtomPropQueries(self): """ test the property queries """ from rdkit.Chem import rdqueries m = Chem.MolFromSmiles("C" * 14) atoms = m.GetAtoms() atoms[0].SetProp("hah", "hah") atoms[1].SetIntProp("bar", 1) atoms[2].SetIntProp("bar", 2) atoms[3].SetBoolProp("baz", True) atoms[4].SetBoolProp("baz", False) atoms[5].SetProp("boo", "hoo") atoms[6].SetProp("boo", "-urns") atoms[7].SetDoubleProp("boot", 1.0) atoms[8].SetDoubleProp("boot", 4.0) atoms[9].SetDoubleProp("number", 4.0) atoms[10].SetIntProp("number", 4) tests = ((rdqueries.HasIntPropWithValueQueryAtom, "bar", { 1: [1], 2: [2] }), (rdqueries.HasBoolPropWithValueQueryAtom, "baz", { True: [3], False: [4] }), (rdqueries.HasStringPropWithValueQueryAtom, "boo", { "hoo": [5], "-urns": [6] }), (rdqueries.HasDoublePropWithValueQueryAtom, "boot", { 1.0: [7], 4.0: [8] })) for query, name, lookups in tests: for t, v in lookups.items(): q = query(name, t) self.assertEqual(v, [x.GetIdx() for x in m.GetAtomsMatchingQuery(q)]) q = query(name, t, negate=True) self.assertEqual( sorted(set(range(14)) - set(v)), [x.GetIdx() for x in m.GetAtomsMatchingQuery(q)]) # check tolerances self.assertEqual([ x.GetIdx() for x in m.GetAtomsMatchingQuery( rdqueries.HasDoublePropWithValueQueryAtom("boot", 1.0, tolerance=3.)) ], [7, 8]) # numbers are numbers?, i.e. int!=double self.assertEqual([ x.GetIdx() for x in m.GetAtomsMatchingQuery(rdqueries.HasIntPropWithValueQueryAtom("number", 4)) ], [10]) def testBondPropQueries(self): """ test the property queries """ from rdkit.Chem import rdqueries m = Chem.MolFromSmiles("C" * 14) bonds = m.GetBonds() bonds[0].SetProp("hah", "hah") bonds[1].SetIntProp("bar", 1) bonds[2].SetIntProp("bar", 2) bonds[3].SetBoolProp("baz", True) bonds[4].SetBoolProp("baz", False) bonds[5].SetProp("boo", "hoo") bonds[6].SetProp("boo", "-urns") bonds[7].SetDoubleProp("boot", 1.0) bonds[8].SetDoubleProp("boot", 4.0) bonds[9].SetDoubleProp("number", 4.0) bonds[10].SetIntProp("number", 4) tests = ((rdqueries.HasIntPropWithValueQueryBond, "bar", { 1: [1], 2: [2] }), (rdqueries.HasBoolPropWithValueQueryBond, "baz", { True: [3], False: [4] }), (rdqueries.HasStringPropWithValueQueryBond, "boo", { "hoo": [5], "-urns": [6] }), (rdqueries.HasDoublePropWithValueQueryBond, "boot", { 1.0: [7], 4.0: [8] })) for query, name, lookups in tests: for t, v in lookups.items(): q = query(name, t) self.assertEqual(v, [x.GetIdx() for x in m.GetBonds() if q.Match(x)]) q = query(name, t, negate=True) self.assertEqual( sorted(set(range(13)) - set(v)), [x.GetIdx() for x in m.GetBonds() if q.Match(x)]) # check tolerances q = rdqueries.HasDoublePropWithValueQueryBond("boot", 1.0, tolerance=3.) self.assertEqual([x.GetIdx() for x in m.GetBonds() if q.Match(x)], [7, 8]) # numbers are numbers?, i.e. int!=double q = rdqueries.HasIntPropWithValueQueryBond("number", 4) self.assertEqual([x.GetIdx() for x in m.GetBonds() if q.Match(x)], [10]) def testGetShortestPath(self): """ test the GetShortestPath() wrapper """ smi = "CC(OC1C(CCCC3)C3C(CCCC2)C2C1OC(C)=O)=O" m = Chem.MolFromSmiles(smi) path = Chem.GetShortestPath(m, 1, 20) self.assertEqual(path, (1, 2, 3, 16, 17, 18, 20)) def testGithub497(self): outf = gzip.open(tempfile.mktemp(), 'wb+') m = Chem.MolFromSmiles('C') w = Chem.SDWriter(outf) e = False try: w.write(m) except Exception: sys.stderr.write('Opening gzip as binary fails on Python3 ' \ 'upon writing to SDWriter without crashing the RDKit\n') e = True else: e = (sys.version_info < (3, 0)) try: w.close() except Exception: sys.stderr.write('Opening gzip as binary fails on Python3 ' \ 'upon closing SDWriter without crashing the RDKit\n') e = True else: if (not e): e = (sys.version_info < (3, 0)) w = None try: outf.close() except Exception: sys.stderr.write('Opening gzip as binary fails on Python3 ' \ 'upon closing the stream without crashing the RDKit\n') e = True else: if (not e): e = (sys.version_info < (3, 0)) self.assertTrue(e) def testGithub498(self): if (sys.version_info < (3, 0)): mode = 'w+' else: mode = 'wt+' outf = gzip.open(tempfile.mktemp(), mode) m = Chem.MolFromSmiles('C') w = Chem.SDWriter(outf) w.write(m) w.close() w = None outf.close() def testReplaceBond(self): origmol = Chem.RWMol(Chem.MolFromSmiles("CC")) bonds = list(origmol.GetBonds()) self.assertEqual(len(bonds), 1) singlebond = bonds[0] self.assertEqual(singlebond.GetBondType(), Chem.BondType.SINGLE) # this is the only way we create a bond, is take it from another molecule doublebonded = Chem.MolFromSmiles("C=C") doublebond = list(doublebonded.GetBonds())[0] # make sure replacing the bond changes the smiles self.assertEquals(Chem.MolToSmiles(origmol), "CC") origmol.ReplaceBond(singlebond.GetIdx(), doublebond) Chem.SanitizeMol(origmol) self.assertEquals(Chem.MolToSmiles(origmol), "C=C") def testAdjustQueryProperties(self): m = Chem.MolFromSmarts('C1CCC1*') am = Chem.AdjustQueryProperties(m) self.assertTrue(Chem.MolFromSmiles('C1CCC1C').HasSubstructMatch(m)) self.assertTrue(Chem.MolFromSmiles('C1CCC1C').HasSubstructMatch(am)) self.assertTrue(Chem.MolFromSmiles('C1CC(C)C1C').HasSubstructMatch(m)) self.assertFalse(Chem.MolFromSmiles('C1CC(C)C1C').HasSubstructMatch(am)) m = Chem.MolFromSmiles('C1CCC1*') am = Chem.AdjustQueryProperties(m) self.assertFalse(Chem.MolFromSmiles('C1CCC1C').HasSubstructMatch(m)) self.assertTrue(Chem.MolFromSmiles('C1CCC1C').HasSubstructMatch(am)) qps = Chem.AdjustQueryParameters() qps.makeDummiesQueries = False am = Chem.AdjustQueryProperties(m, qps) self.assertFalse(Chem.MolFromSmiles('C1CCC1C').HasSubstructMatch(am)) m = Chem.MolFromSmiles('C1=CC=CC=C1', sanitize=False) am = Chem.AdjustQueryProperties(m) self.assertTrue(Chem.MolFromSmiles('c1ccccc1').HasSubstructMatch(am)) qp = Chem.AdjustQueryParameters() qp.aromatizeIfPossible = False am = Chem.AdjustQueryProperties(m, qp) self.assertFalse(Chem.MolFromSmiles('c1ccccc1').HasSubstructMatch(am)) m = Chem.MolFromSmiles('C1CCC1OC') qps = Chem.AdjustQueryParameters() qps.makeAtomsGeneric = True am = Chem.AdjustQueryProperties(m, qps) self.assertEqual(Chem.MolToSmarts(am), '*1-*-*-*-1-*-*') qps.makeAtomsGenericFlags = Chem.ADJUST_IGNORERINGS am = Chem.AdjustQueryProperties(m, qps) self.assertEqual(Chem.MolToSmarts(am), '[#6&D2]1-[#6&D2]-[#6&D2]-[#6&D3]-1-*-*') qps = Chem.AdjustQueryParameters() qps.makeBondsGeneric = True am = Chem.AdjustQueryProperties(m, qps) self.assertEqual(Chem.MolToSmarts(am), '[#6&D2]1~[#6&D2]~[#6&D2]~[#6&D3]~1~[#8]~[#6]') qps.makeBondsGenericFlags = Chem.ADJUST_IGNORERINGS am = Chem.AdjustQueryProperties(m, qps) self.assertEqual(Chem.MolToSmarts(am), '[#6&D2]1-[#6&D2]-[#6&D2]-[#6&D3]-1~[#8]~[#6]') def testAdjustQueryPropertiesgithubIssue1474(self): core = Chem.MolFromSmiles('[*:1]C1N([*:2])C([*:3])O1') core.GetAtomWithIdx(0).SetProp('foo', 'bar') core.GetAtomWithIdx(1).SetProp('foo', 'bar') ap = Chem.AdjustQueryProperties(core) self.assertEqual(ap.GetAtomWithIdx(0).GetPropsAsDict()["foo"], "bar") self.assertEqual(ap.GetAtomWithIdx(1).GetPropsAsDict()["foo"], "bar") def testGithubIssue579(self): fileN = os.path.join(RDConfig.RDBaseDir, 'Code', 'GraphMol', 'FileParsers', 'test_data', 'NCI_aids_few.sdf.gz') inf = gzip.open(fileN) suppl = Chem.ForwardSDMolSupplier(inf) m0 = next(suppl) self.assertIsNot(m0, None) inf.close() del suppl def testSequenceBasics(self): " very basic round-tripping of the sequence reader/writer support " helm = 'PEPTIDE1{C.Y.I.Q.N.C.P.L.G}$$$$' seq = 'CYIQNCPLG' fasta = '>\nCYIQNCPLG\n' smi = 'CC[C@H](C)[C@H](NC(=O)[C@H](Cc1ccc(O)cc1)NC(=O)[C@@H](N)CS)C(=O)N[C@@H](CCC(N)=O)C(=O)N[C@@H](CC(N)=O)C(=O)N[C@@H](CS)C(=O)N1CCC[C@H]1C(=O)N[C@@H](CC(C)C)C(=O)NCC(=O)O' m = Chem.MolFromSequence(seq) self.assertTrue(m is not None) self.assertEqual(Chem.MolToSequence(m), seq) self.assertEqual(Chem.MolToHELM(m), helm) self.assertEqual(Chem.MolToFASTA(m), fasta) self.assertEqual(Chem.MolToSmiles(m, isomericSmiles=True), smi) m = Chem.MolFromHELM(helm) self.assertTrue(m is not None) self.assertEqual(Chem.MolToSequence(m), seq) self.assertEqual(Chem.MolToHELM(m), helm) self.assertEqual(Chem.MolToFASTA(m), fasta) self.assertEqual(Chem.MolToSmiles(m, isomericSmiles=True), smi) m = Chem.MolFromFASTA(fasta) self.assertTrue(m is not None) self.assertEqual(Chem.MolToSequence(m), seq) self.assertEqual(Chem.MolToHELM(m), helm) self.assertEqual(Chem.MolToFASTA(m), fasta) self.assertEqual(Chem.MolToSmiles(m, isomericSmiles=True), smi) seq = "CGCGAATTACCGCG" m = Chem.MolFromSequence(seq, flavor=6) # DNA self.assertEqual(Chem.MolToSequence(m), 'CGCGAATTACCGCG') self.assertEqual( Chem.MolToHELM(m), 'RNA1{[dR](C)P.[dR](G)P.[dR](C)P.[dR](G)P.[dR](A)P.[dR](A)P.[dR](T)P.[dR](T)P.[dR](A)P.[dR](C)P.[dR](C)P.[dR](G)P.[dR](C)P.[dR](G)}$$$$' ) seq = "CGCGAAUUACCGCG" m = Chem.MolFromSequence(seq, flavor=2) # RNA self.assertEqual(Chem.MolToSequence(m), 'CGCGAAUUACCGCG') self.assertEqual( Chem.MolToHELM(m), 'RNA1{R(C)P.R(G)P.R(C)P.R(G)P.R(A)P.R(A)P.R(U)P.R(U)P.R(A)P.R(C)P.R(C)P.R(G)P.R(C)P.R(G)}$$$$' ) m = Chem.MolFromSequence(seq, flavor=3) # RNA - 5' cap self.assertEqual(Chem.MolToSequence(m), 'CGCGAAUUACCGCG') self.assertEqual( Chem.MolToHELM(m), 'RNA1{P.R(C)P.R(G)P.R(C)P.R(G)P.R(A)P.R(A)P.R(U)P.R(U)P.R(A)P.R(C)P.R(C)P.R(G)P.R(C)P.R(G)}$$$$' ) def testResMolSupplier(self): mol = Chem.MolFromSmiles('CC') resMolSuppl = Chem.ResonanceMolSupplier(mol) del resMolSuppl resMolSuppl = Chem.ResonanceMolSupplier(mol) self.assertEqual(resMolSuppl.GetNumConjGrps(), 0) self.assertEqual(len(resMolSuppl), 1) self.assertEqual(resMolSuppl.GetNumConjGrps(), 0) mol = Chem.MolFromSmiles('NC(=[NH2+])c1ccc(cc1)C(=O)[O-]') totalFormalCharge = getTotalFormalCharge(mol) resMolSuppl = Chem.ResonanceMolSupplier(mol) self.assertFalse(resMolSuppl.GetIsEnumerated()) self.assertEqual(len(resMolSuppl), 4) self.assertTrue(resMolSuppl.GetIsEnumerated()) resMolSuppl = Chem.ResonanceMolSupplier(mol) self.assertFalse(resMolSuppl.GetIsEnumerated()) resMolSuppl.Enumerate() self.assertTrue(resMolSuppl.GetIsEnumerated()) self.assertTrue((resMolSuppl[0].GetBondBetweenAtoms(0, 1).GetBondType() \ != resMolSuppl[1].GetBondBetweenAtoms(0, 1).GetBondType()) or (resMolSuppl[0].GetBondBetweenAtoms(9, 10).GetBondType() \ != resMolSuppl[1].GetBondBetweenAtoms(9, 10).GetBondType())) resMolSuppl = Chem.ResonanceMolSupplier(mol, Chem.KEKULE_ALL) self.assertEqual(len(resMolSuppl), 8) bondTypeSet = set() # check that we actually have two alternate Kekule structures bondTypeSet.add(resMolSuppl[0].GetBondBetweenAtoms(3, 4).GetBondType()) bondTypeSet.add(resMolSuppl[1].GetBondBetweenAtoms(3, 4).GetBondType()) self.assertEqual(len(bondTypeSet), 2) bondTypeDict = {} resMolSuppl = Chem.ResonanceMolSupplier(mol, Chem.ALLOW_INCOMPLETE_OCTETS \ | Chem.UNCONSTRAINED_CATIONS \ | Chem.UNCONSTRAINED_ANIONS) self.assertEqual(len(resMolSuppl), 32) for i in range(len(resMolSuppl)): resMol = resMolSuppl[i] self.assertEqual(getTotalFormalCharge(resMol), totalFormalCharge) while (not resMolSuppl.atEnd()): resMol = six.next(resMolSuppl) self.assertEqual(getTotalFormalCharge(resMol), totalFormalCharge) resMolSuppl.reset() cmpFormalChargeBondOrder(self, resMolSuppl[0], six.next(resMolSuppl)) resMolSuppl = Chem.ResonanceMolSupplier(mol, Chem.ALLOW_INCOMPLETE_OCTETS \ | Chem.UNCONSTRAINED_CATIONS \ | Chem.UNCONSTRAINED_ANIONS, 10) self.assertEqual(len(resMolSuppl), 10) crambinPdb = os.path.join(RDConfig.RDBaseDir, 'Code', 'GraphMol', 'FileParsers', 'test_data', '1CRN.pdb') mol = Chem.MolFromPDBFile(crambinPdb) resMolSuppl = Chem.ResonanceMolSupplier(mol) self.assertEqual(len(resMolSuppl), 1) resMolSuppl = Chem.ResonanceMolSupplier(mol, Chem.KEKULE_ALL) self.assertEqual(len(resMolSuppl), 8) def testSubstructMatchAcetate(self): mol = Chem.MolFromSmiles('CC(=O)[O-]') query = Chem.MolFromSmarts('C(=O)[O-]') resMolSuppl = Chem.ResonanceMolSupplier(mol) matches = mol.GetSubstructMatches(query) self.assertEqual(len(matches), 1) self.assertEqual(matches, ((1, 2, 3), )) matches = mol.GetSubstructMatches(query, uniquify=True) self.assertEqual(len(matches), 1) self.assertEqual(matches, ((1, 2, 3), )) matches = mol.GetSubstructMatches(query, uniquify=False) self.assertEqual(len(matches), 1) self.assertEqual(matches, ((1, 2, 3), )) matches = resMolSuppl.GetSubstructMatches(query) self.assertEqual(len(matches), 2) self.assertEqual(matches, ((1, 2, 3), (1, 3, 2))) matches = resMolSuppl.GetSubstructMatches(query, uniquify=True) self.assertEqual(len(matches), 1) self.assertEqual(matches, ((1, 2, 3), )) matches = resMolSuppl.GetSubstructMatches(query, uniquify=False) self.assertEqual(len(matches), 2) self.assertEqual(matches, ((1, 2, 3), (1, 3, 2))) query = Chem.MolFromSmarts('C(~O)~O') matches = mol.GetSubstructMatches(query, uniquify=False) self.assertEqual(len(matches), 2) self.assertEqual(matches, ((1, 2, 3), (1, 3, 2))) matches = mol.GetSubstructMatches(query, uniquify=True) self.assertEqual(len(matches), 1) self.assertEqual(matches, ((1, 2, 3), )) matches = resMolSuppl.GetSubstructMatches(query, uniquify=False) self.assertEqual(len(matches), 2) self.assertEqual(matches, ((1, 2, 3), (1, 3, 2))) matches = resMolSuppl.GetSubstructMatches(query, uniquify=True) self.assertEqual(len(matches), 1) self.assertEqual(matches, ((1, 2, 3), )) def testSubstructMatchDMAP(self): mol = Chem.MolFromSmiles('C(C)Nc1cc[nH+]cc1') query = Chem.MolFromSmarts('[#7+]') resMolSuppl = Chem.ResonanceMolSupplier(mol) matches = mol.GetSubstructMatches(query, False, False, False) self.assertEqual(len(matches), 1) p = matches[0] self.assertEqual(p[0], 6) matches = resMolSuppl.GetSubstructMatches(query, False, False, False) self.assertEqual(len(matches), 2) v = [] p = matches[0] v.append(p[0]) p = matches[1] v.append(p[0]) v.sort() self.assertEqual(v[0], 2) self.assertEqual(v[1], 6) def testCrambin(self): crambinPdb = os.path.join(RDConfig.RDBaseDir, 'Code', 'GraphMol', 'FileParsers', 'test_data', '1CRN.pdb') crambin = Chem.MolFromPDBFile(crambinPdb) res = [] # protonate NH2 res.append(Chem.MolFromSmarts('[Nh2][Ch;Ch2]')) # protonate Arg res.append(Chem.MolFromSmarts('[Nh][C]([Nh2])=[Nh]')) setResidueFormalCharge(crambin, res, 1) res = [] # deprotonate COOH res.append(Chem.MolFromSmarts('C(=O)[Oh]')) setResidueFormalCharge(crambin, res, -1) res = [] resMolSupplST = Chem.ResonanceMolSupplier(crambin) # crambin has 2 Arg (3 resonance structures each); 1 Asp, 1 Glu # and 1 terminal COO- (2 resonance structures each) # so possible resonance structures are 3^2 * 2^3 = 72 self.assertEqual(len(resMolSupplST), 72) self.assertEqual(resMolSupplST.GetNumConjGrps(), 56) carboxylateQuery = Chem.MolFromSmarts('C(=O)[O-]') guanidiniumQuery = Chem.MolFromSmarts('NC(=[NH2+])N') matches = crambin.GetSubstructMatches(carboxylateQuery) self.assertEqual(len(matches), 3) matches = crambin.GetSubstructMatches(carboxylateQuery, uniquify=False) self.assertEqual(len(matches), 3) matches = crambin.GetSubstructMatches(guanidiniumQuery) self.assertEqual(len(matches), 0) matches = crambin.GetSubstructMatches(guanidiniumQuery, uniquify=False) self.assertEqual(len(matches), 0) matches = resMolSupplST.GetSubstructMatches(carboxylateQuery) self.assertEqual(len(matches), 6) self.assertEqual(matches, ((166, 167, 168), (166, 168, 167), (298, 299, 300), (298, 300, 299), (320, 321, 326), (320, 326, 321))) matches = resMolSupplST.GetSubstructMatches(carboxylateQuery, uniquify=True) self.assertEqual(len(matches), 3) self.assertEqual(matches, ((166, 167, 168), (298, 299, 300), (320, 321, 326))) matches = resMolSupplST.GetSubstructMatches(guanidiniumQuery) self.assertEqual(len(matches), 8) self.assertEqual(matches, ((66, 67, 68, 69), (66, 67, 69, 68), (68, 67, 69, 66), (69, 67, 68, 66), (123, 124, 125, 126), (123, 124, 126, 125), (125, 124, 126, 123), (126, 124, 125, 123))) matches = resMolSupplST.GetSubstructMatches(guanidiniumQuery, uniquify=True) self.assertEqual(len(matches), 2) self.assertEqual(matches, ((66, 67, 69, 68), (123, 124, 126, 125))) btList2ST = getBtList2(resMolSupplST) self.assertTrue(btList2ST) resMolSupplMT = Chem.ResonanceMolSupplier(crambin) resMolSupplMT.SetNumThreads(0) self.assertEqual(len(resMolSupplST), len(resMolSupplMT)) btList2MT = getBtList2(resMolSupplMT) self.assertTrue(btList2MT) self.assertEqual(len(btList2ST), len(btList2MT)) for i in range(len(btList2ST)): for j in range(len(btList2ST)): self.assertEqual(btList2ST[i][j], btList2MT[i][j]) for suppl in [resMolSupplST, resMolSupplMT]: matches = suppl.GetSubstructMatches(carboxylateQuery, numThreads=0) self.assertEqual(len(matches), 6) self.assertEqual(matches, ((166, 167, 168), (166, 168, 167), (298, 299, 300), (298, 300, 299), (320, 321, 326), (320, 326, 321))) matches = suppl.GetSubstructMatches(carboxylateQuery, uniquify=True, numThreads=0) self.assertEqual(len(matches), 3) self.assertEqual(matches, ((166, 167, 168), (298, 299, 300), (320, 321, 326))) matches = suppl.GetSubstructMatches(guanidiniumQuery, numThreads=0) self.assertEqual(len(matches), 8) self.assertEqual(matches, ((66, 67, 68, 69), (66, 67, 69, 68), (68, 67, 69, 66), (69, 67, 68, 66), (123, 124, 125, 126), (123, 124, 126, 125), (125, 124, 126, 123), (126, 124, 125, 123))) matches = suppl.GetSubstructMatches(guanidiniumQuery, uniquify=True, numThreads=0) self.assertEqual(len(matches), 2) self.assertEqual(matches, ((66, 67, 69, 68), (123, 124, 126, 125))) def testGitHUb1166(self): mol = Chem.MolFromSmiles('NC(=[NH2+])c1ccc(cc1)C(=O)[O-]') resMolSuppl = Chem.ResonanceMolSupplier(mol, Chem.KEKULE_ALL) self.assertEqual(len(resMolSuppl), 8) # check that formal charges on odd indices are in the same position # as on even indices for i in range(0, len(resMolSuppl), 2): self.assertEqual(resMolSuppl[i].GetNumAtoms(), resMolSuppl[i + 1].GetNumAtoms()) for atomIdx in range(resMolSuppl[i].GetNumAtoms()): self.assertEqual(resMolSuppl[i].GetAtomWithIdx(atomIdx).GetFormalCharge(), resMolSuppl[i + 1].GetAtomWithIdx(atomIdx).GetFormalCharge()) # check that bond orders are alternate on aromatic bonds between # structures on odd indices and structures on even indices self.assertEqual(resMolSuppl[i].GetNumBonds(), resMolSuppl[i + 1].GetNumBonds()) for bondIdx in range(resMolSuppl[i].GetNumBonds()): self.assertTrue( ((not resMolSuppl[i].GetBondWithIdx(bondIdx).GetIsAromatic()) and (not resMolSuppl[i + 1].GetBondWithIdx(bondIdx).GetIsAromatic()) and (resMolSuppl[i].GetBondWithIdx(bondIdx).GetBondType() == resMolSuppl[i + 1] .GetBondWithIdx(bondIdx).GetBondType())) or (resMolSuppl[i].GetBondWithIdx(bondIdx).GetIsAromatic() and resMolSuppl[i + 1].GetBondWithIdx(bondIdx).GetIsAromatic() and (int( round(resMolSuppl[i].GetBondWithIdx(bondIdx).GetBondTypeAsDouble() + resMolSuppl[i + 1].GetBondWithIdx(bondIdx).GetBondTypeAsDouble())) == 3))) def testAtomBondProps(self): m = Chem.MolFromSmiles('c1ccccc1') for atom in m.GetAtoms(): d = atom.GetPropsAsDict() self.assertEquals(set(d.keys()), set(['_CIPRank', '__computedProps'])) self.assertEquals(d['_CIPRank'], 0) self.assertEquals(list(d['__computedProps']), ['_CIPRank']) for bond in m.GetBonds(): self.assertEquals(bond.GetPropsAsDict(), {}) def testSDProps(self): fileN = os.path.join(RDConfig.RDBaseDir, 'Code', 'GraphMol', 'FileParsers', 'test_data', 'NCI_aids_few.sdf') #fileN = "../FileParsers/test_data/NCI_aids_few.sdf" sddata = [ { '_MolFileInfo': 'BBtclserve11129916382D 0 0.00000 0.00000 48', 'NSC': 48, 'NCI_AIDS_Antiviral_Screen_IC50': '2.00E-04\tM\t=\t2.46E-05\t3', '_Name': 48, 'CAS_RN': '15716-70-8', '_MolFileComments': '15716-70-8', 'NCI_AIDS_Antiviral_Screen_EC50': '2.00E-04\tM\t>\t2.00E-04\t3', 'NCI_AIDS_Antiviral_Screen_Conclusion': 'CI' }, { '_MolFileInfo': 'BBtclserve11129916382D 0 0.00000 0.00000 78', 'NSC': 78, 'NCI_AIDS_Antiviral_Screen_IC50': '2.00E-04\tM\t=\t9.80E-05\t3', '_Name': 78, 'CAS_RN': '6290-84-2', '_MolFileComments': '6290-84-2', 'NCI_AIDS_Antiviral_Screen_EC50': '2.00E-04\tM\t>\t2.00E-04\t3', 'NCI_AIDS_Antiviral_Screen_Conclusion': 'CI' }, { '_MolFileInfo': 'BBtclserve11129916382D 0 0.00000 0.00000 128', 'NSC': 128, 'NCI_AIDS_Antiviral_Screen_IC50': '2.00E-04\tM\t=\t4.60E-05\t4', '_Name': 128, 'CAS_RN': '5395-10-8', '_MolFileComments': '5395-10-8', 'NCI_AIDS_Antiviral_Screen_EC50': '2.00E-04\tM\t>\t2.00E-04\t4', 'NCI_AIDS_Antiviral_Screen_Conclusion': 'CI' }, { '_MolFileInfo': 'BBtclserve11129916382D 0 0.00000 0.00000 163', 'NSC': 163, 'NCI_AIDS_Antiviral_Screen_IC50': '6.75E-04\tM\t>\t6.75E-04\t2', '_Name': 163, 'CAS_RN': '81-11-8', '_MolFileComments': '81-11-8', 'NCI_AIDS_Antiviral_Screen_EC50': '6.75E-04\tM\t>\t6.75E-04\t2', 'NCI_AIDS_Antiviral_Screen_Conclusion': 'CI' }, { '_MolFileInfo': 'BBtclserve11129916382D 0 0.00000 0.00000 164', 'NSC': 164, 'NCI_AIDS_Antiviral_Screen_IC50': '2.00E-04\tM\t>\t2.00E-04\t2', '_Name': 164, 'CAS_RN': '5325-43-9', '_MolFileComments': '5325-43-9', 'NCI_AIDS_Antiviral_Screen_EC50': '2.00E-04\tM\t>\t2.00E-04\t2', 'NCI_AIDS_Antiviral_Screen_Conclusion': 'CI' }, { '_MolFileInfo': 'BBtclserve11129916382D 0 0.00000 0.00000 170', 'NSC': 170, '_Name': 170, 'CAS_RN': '999-99-9', '_MolFileComments': '999-99-9', 'NCI_AIDS_Antiviral_Screen_EC50': '9.47E-04\tM\t>\t9.47E-04\t1', 'NCI_AIDS_Antiviral_Screen_Conclusion': 'CI' }, { '_MolFileInfo': 'BBtclserve11129916382D 0 0.00000 0.00000 180', 'NSC': 180, 'NCI_AIDS_Antiviral_Screen_IC50': '6.46E-04\tM\t=\t5.80E-04\t2\n1.81E-03\tM\t=\t6.90E-04\t2', '_Name': 180, 'CAS_RN': '69-72-7', '_MolFileComments': '69-72-7', 'NCI_AIDS_Antiviral_Screen_EC50': '6.46E-04\tM\t>\t6.46E-04\t2\n1.81E-03\tM\t>\t1.81E-03\t2', 'NCI_AIDS_Antiviral_Screen_Conclusion': 'CI' }, { '_MolFileInfo': 'BBtclserve11129916382D 0 0.00000 0.00000 186', 'NSC': 186, 'NCI_AIDS_Antiviral_Screen_IC50': '1.44E-04\tM\t=\t2.49E-05\t2', '_Name': 186, 'CAS_RN': '518-75-2', '_MolFileComments': '518-75-2', 'NCI_AIDS_Antiviral_Screen_EC50': '1.44E-04\tM\t>\t1.44E-04\t2', 'NCI_AIDS_Antiviral_Screen_Conclusion': 'CI' }, { '_MolFileInfo': 'BBtclserve11129916382D 0 0.00000 0.00000 192', 'NSC': 192, 'NCI_AIDS_Antiviral_Screen_IC50': '2.00E-04\tM\t=\t3.38E-06\t2', '_Name': 192, 'CAS_RN': '2217-55-2', '_MolFileComments': '2217-55-2', 'NCI_AIDS_Antiviral_Screen_EC50': '2.00E-04\tM\t>\t2.00E-04\t2', 'NCI_AIDS_Antiviral_Screen_Conclusion': 'CI' }, { '_MolFileInfo': 'BBtclserve11129916382D 0 0.00000 0.00000 203', 'NSC': 203, '_Name': 203, 'CAS_RN': '1155-00-6', '_MolFileComments': '1155-00-6', 'NCI_AIDS_Antiviral_Screen_Conclusion': 'CI' }, { '_MolFileInfo': 'BBtclserve11129916382D 0 0.00000 0.00000 210', 'NSC': 210, 'NCI_AIDS_Antiviral_Screen_IC50': '1.33E-03\tM\t>\t1.33E-03\t2', '_Name': 210, 'CAS_RN': '5325-75-7', '_MolFileComments': '5325-75-7', 'NCI_AIDS_Antiviral_Screen_EC50': '1.33E-03\tM\t>\t1.33E-03\t2', 'NCI_AIDS_Antiviral_Screen_Conclusion': 'CI' }, { '_MolFileInfo': 'BBtclserve11129916382D 0 0.00000 0.00000 211', 'NSC': 211, 'NCI_AIDS_Antiviral_Screen_IC50': '2.00E-04\tM\t>\t2.00E-04\t8\n2.00E-03\tM\t=\t1.12E-03\t2', '_Name': 211, 'CAS_RN': '5325-76-8', '_MolFileComments': '5325-76-8', 'NCI_AIDS_Antiviral_Screen_EC50': '2.00E-04\tM\t>\t7.42E-05\t8\n2.00E-03\tM\t=\t6.35E-05\t2', 'NCI_AIDS_Antiviral_Screen_Conclusion': 'CM' }, { '_MolFileInfo': 'BBtclserve11129916382D 0 0.00000 0.00000 213', 'NSC': 213, 'NCI_AIDS_Antiviral_Screen_IC50': '2.00E-04\tM\t>\t2.00E-04\t4', '_Name': 213, 'CAS_RN': '119-80-2', '_MolFileComments': '119-80-2', 'NCI_AIDS_Antiviral_Screen_EC50': '2.00E-04\tM\t>\t2.00E-04\t4', 'NCI_AIDS_Antiviral_Screen_Conclusion': 'CI' }, { '_MolFileInfo': 'BBtclserve11129916382D 0 0.00000 0.00000 220', 'NSC': 220, 'NCI_AIDS_Antiviral_Screen_IC50': '2.00E-04\tM\t>\t2.00E-04\t4', '_Name': 220, 'CAS_RN': '5325-83-7', '_MolFileComments': '5325-83-7', 'NCI_AIDS_Antiviral_Screen_EC50': '2.00E-04\tM\t>\t2.00E-04\t4', 'NCI_AIDS_Antiviral_Screen_Conclusion': 'CI' }, { '_MolFileInfo': 'BBtclserve11129916382D 0 0.00000 0.00000 229', 'NSC': 229, 'NCI_AIDS_Antiviral_Screen_IC50': '2.00E-04\tM\t>\t2.00E-04\t2', '_Name': 229, 'CAS_RN': '5325-88-2', '_MolFileComments': '5325-88-2', 'NCI_AIDS_Antiviral_Screen_EC50': '2.00E-04\tM\t>\t2.00E-04\t2', 'NCI_AIDS_Antiviral_Screen_Conclusion': 'CI' }, { '_MolFileInfo': 'BBtclserve11129916382D 0 0.00000 0.00000 256', 'NSC': 256, 'NCI_AIDS_Antiviral_Screen_IC50': '2.00E-04\tM\t>\t2.00E-04\t4', '_Name': 256, 'CAS_RN': '5326-06-7', '_MolFileComments': '5326-06-7', 'NCI_AIDS_Antiviral_Screen_EC50': '2.00E-04\tM\t>\t2.00E-04\t4', 'NCI_AIDS_Antiviral_Screen_Conclusion': 'CI' }, ] sdSup = Chem.SDMolSupplier(fileN) for i, mol in enumerate(sdSup): self.assertEquals(mol.GetPropsAsDict(includePrivate=True), sddata[i]) def testGetSetProps(self): m = Chem.MolFromSmiles("CC") errors = { "int": "key `foo` exists but does not result in an integer value", "double": "key `foo` exists but does not result in a double value", "bool": "key `foo` exists but does not result in a True or False value" } for ob in [m, list(m.GetAtoms())[0], list(m.GetBonds())[0]]: ob.SetDoubleProp("foo", 2.0) with self.assertRaises(ValueError) as e: ob.GetBoolProp("foo") self.assertEquals(str(e.exception), errors["bool"]) with self.assertRaises(ValueError) as e: ob.GetIntProp("foo") self.assertEquals(str(e.exception), errors["int"]) ob.SetBoolProp("foo", True) with self.assertRaises(ValueError) as e: ob.GetDoubleProp("foo") self.assertEquals(str(e.exception), errors["double"]) with self.assertRaises(ValueError) as e: ob.GetIntProp("foo") self.assertEquals(str(e.exception), errors["int"]) def testInvariantException(self): m = Chem.MolFromSmiles("C") try: m.GetAtomWithIdx(3) except RuntimeError as e: import platform details = str(e) if platform.system() == 'Windows': details = details.replace('\\', '/') self.assertTrue("Code/GraphMol/ROMol.cpp".lower() in details.lower()) self.assertTrue("Failed Expression: 3 < 1" in details) self.assertTrue("RDKIT:" in details) self.assertTrue(__version__ in details) # this test should probably always be last since it wraps # the logging stream def testLogging(self): err = sys.stderr try: loggers = [("RDKit ERROR", "1", Chem.LogErrorMsg), ("RDKit WARNING", "2", Chem.LogWarningMsg)] for msg, v, log in loggers: sys.stderr = six.StringIO() log(v) self.assertEquals(sys.stderr.getvalue(), "") Chem.WrapLogs() for msg, v, log in loggers: sys.stderr = six.StringIO() log(v) s = sys.stderr.getvalue() self.assertTrue(msg in s) finally: sys.stderr = err def testGetSDText(self): fileN = os.path.join(RDConfig.RDBaseDir, 'Code', 'GraphMol', 'FileParsers', 'test_data', 'NCI_aids_few.sdf') #fileN = "../FileParsers/test_data/NCI_aids_few.sdf" sdSup = Chem.SDMolSupplier(fileN) for m in sdSup: sdt = Chem.SDWriter.GetText(m) ts = Chem.SDMolSupplier() ts.SetData(sdt) nm = next(ts) self.assertEqual(Chem.MolToSmiles(m, True), Chem.MolToSmiles(nm, True)) for pn in m.GetPropNames(): self.assertTrue(nm.HasProp(pn)) self.assertEqual(m.GetProp(pn), nm.GetProp(pn)) def testUnfoldedRDKFingerprint(self): from rdkit.Chem import AllChem m = Chem.MolFromSmiles('c1ccccc1N') fp = AllChem.UnfoldedRDKFingerprintCountBased(m) fpDict = fp.GetNonzeroElements() self.assertEquals(len(fpDict.items()), 19) self.assertTrue(374073638 in fpDict) self.assertEquals(fpDict[374073638], 6) self.assertTrue(464351883 in fpDict) self.assertEquals(fpDict[464351883], 2) self.assertTrue(1949583554 in fpDict) self.assertEquals(fpDict[1949583554], 6) self.assertTrue(4105342207 in fpDict) self.assertEquals(fpDict[4105342207], 1) self.assertTrue(794080973 in fpDict) self.assertEquals(fpDict[794080973], 1) self.assertTrue(3826517238 in fpDict) self.assertEquals(fpDict[3826517238], 2) m = Chem.MolFromSmiles('Cl') fp = AllChem.UnfoldedRDKFingerprintCountBased(m) fpDict = fp.GetNonzeroElements() self.assertEquals(len(fpDict.items()), 0) m = Chem.MolFromSmiles('CCCO') aBits = {} fp = AllChem.UnfoldedRDKFingerprintCountBased(m, bitInfo=aBits) fpDict = fp.GetNonzeroElements() self.assertEquals(len(fpDict.items()), 5) self.assertTrue(1524090560 in fpDict) self.assertEquals(fpDict[1524090560], 1) self.assertTrue(1940446997 in fpDict) self.assertEquals(fpDict[1940446997], 1) self.assertTrue(3977409745 in fpDict) self.assertEquals(fpDict[3977409745], 1) self.assertTrue(4274652475 in fpDict) self.assertEquals(fpDict[4274652475], 1) self.assertTrue(4275705116 in fpDict) self.assertEquals(fpDict[4275705116], 2) self.assertTrue(1524090560 in aBits) self.assertEquals(aBits[1524090560], [[1, 2]]) self.assertTrue(1940446997 in aBits) self.assertEquals(aBits[1940446997], [[0, 1]]) self.assertTrue(3977409745 in aBits) self.assertEquals(aBits[3977409745], [[0, 1, 2]]) self.assertTrue(4274652475 in aBits) self.assertEquals(aBits[4274652475], [[2]]) self.assertTrue(4275705116 in aBits) self.assertEquals(aBits[4275705116], [[0], [1]]) def testRDKFingerprintBitInfo(self): m = Chem.MolFromSmiles('CCCO') aBits = {} fp1 = Chem.RDKFingerprint(m, bitInfo=aBits) self.assertTrue(1183 in aBits) self.assertEquals(aBits[1183], [[1, 2]]) self.assertTrue(709 in aBits) self.assertEquals(aBits[709], [[0, 1]]) self.assertTrue(1118 in aBits) self.assertEquals(aBits[1118], [[0, 1, 2]]) self.assertTrue(562 in aBits) self.assertEquals(aBits[562], [[2]]) self.assertTrue(1772 in aBits) self.assertEquals(aBits[1772], [[0], [1]]) def testSimpleAromaticity(self): m = Chem.MolFromSmiles('c1ccccc1') self.assertTrue(m.GetBondWithIdx(0).GetIsAromatic()) self.assertTrue(m.GetAtomWithIdx(0).GetIsAromatic()) Chem.Kekulize(m, True) self.assertFalse(m.GetBondWithIdx(0).GetIsAromatic()) self.assertFalse(m.GetAtomWithIdx(0).GetIsAromatic()) Chem.SetAromaticity(m, Chem.AROMATICITY_SIMPLE) self.assertTrue(m.GetBondWithIdx(0).GetIsAromatic()) self.assertTrue(m.GetAtomWithIdx(0).GetIsAromatic()) m = Chem.MolFromSmiles('c1c[nH]cc1') self.assertTrue(m.GetBondWithIdx(0).GetIsAromatic()) self.assertTrue(m.GetAtomWithIdx(0).GetIsAromatic()) Chem.Kekulize(m, True) self.assertFalse(m.GetBondWithIdx(0).GetIsAromatic()) self.assertFalse(m.GetAtomWithIdx(0).GetIsAromatic()) Chem.SetAromaticity(m, Chem.AROMATICITY_SIMPLE) self.assertTrue(m.GetBondWithIdx(0).GetIsAromatic()) self.assertTrue(m.GetAtomWithIdx(0).GetIsAromatic()) m = Chem.MolFromSmiles('c1cccoocc1') self.assertTrue(m.GetBondWithIdx(0).GetIsAromatic()) self.assertTrue(m.GetAtomWithIdx(0).GetIsAromatic()) Chem.Kekulize(m, True) self.assertFalse(m.GetBondWithIdx(0).GetIsAromatic()) self.assertFalse(m.GetAtomWithIdx(0).GetIsAromatic()) Chem.SetAromaticity(m, Chem.AROMATICITY_SIMPLE) self.assertFalse(m.GetBondWithIdx(0).GetIsAromatic()) self.assertFalse(m.GetAtomWithIdx(0).GetIsAromatic()) m = Chem.MolFromSmiles('c1ooc1') self.assertTrue(m.GetBondWithIdx(0).GetIsAromatic()) self.assertTrue(m.GetAtomWithIdx(0).GetIsAromatic()) Chem.Kekulize(m, True) self.assertFalse(m.GetBondWithIdx(0).GetIsAromatic()) self.assertFalse(m.GetAtomWithIdx(0).GetIsAromatic()) Chem.SetAromaticity(m, Chem.AROMATICITY_SIMPLE) self.assertFalse(m.GetBondWithIdx(0).GetIsAromatic()) self.assertFalse(m.GetAtomWithIdx(0).GetIsAromatic()) m = Chem.MolFromSmiles('C1=CC2=CC=CC=CC2=C1') self.assertTrue(m.GetBondWithIdx(0).GetIsAromatic()) self.assertTrue(m.GetAtomWithIdx(0).GetIsAromatic()) Chem.Kekulize(m, True) self.assertFalse(m.GetBondWithIdx(0).GetIsAromatic()) self.assertFalse(m.GetAtomWithIdx(0).GetIsAromatic()) Chem.SetAromaticity(m, Chem.AROMATICITY_SIMPLE) self.assertFalse(m.GetBondWithIdx(0).GetIsAromatic()) self.assertFalse(m.GetAtomWithIdx(0).GetIsAromatic()) def testGithub955(self): m = Chem.MolFromSmiles("CCC") m.GetAtomWithIdx(0).SetProp("foo", "1") self.assertEqual(list(m.GetAtomWithIdx(0).GetPropNames()), ["foo"]) m.GetBondWithIdx(0).SetProp("foo", "1") self.assertEqual(list(m.GetBondWithIdx(0).GetPropNames()), ["foo"]) def testMDLProps(self): m = Chem.MolFromSmiles("CCC") m.GetAtomWithIdx(0).SetAtomMapNum(1) Chem.SetAtomAlias(m.GetAtomWithIdx(1), "foo") Chem.SetAtomValue(m.GetAtomWithIdx(1), "bar") m = Chem.MolFromMolBlock(Chem.MolToMolBlock(m)) self.assertEquals(m.GetAtomWithIdx(0).GetAtomMapNum(), 1) self.assertEquals(Chem.GetAtomAlias(m.GetAtomWithIdx(1)), "foo") self.assertEquals(Chem.GetAtomValue(m.GetAtomWithIdx(1)), "bar") def testSmilesProps(self): m = Chem.MolFromSmiles("C") Chem.SetSupplementalSmilesLabel(m.GetAtomWithIdx(0), 'xxx') self.assertEquals(Chem.MolToSmiles(m), "Cxxx") def testGithub1051(self): # just need to test that this exists: self.assertTrue(Chem.BondDir.EITHERDOUBLE) def testGithub1041(self): a = Chem.Atom(6) self.assertRaises(RuntimeError, lambda: a.GetOwningMol()) self.assertRaises(RuntimeError, lambda: a.GetNeighbors()) self.assertRaises(RuntimeError, lambda: a.GetBonds()) self.assertRaises(RuntimeError, lambda: a.IsInRing()) self.assertRaises(RuntimeError, lambda: a.IsInRingSize(4)) def testSmilesParseParams(self): smi = "CCC |$foo;;bar$| ourname" m = Chem.MolFromSmiles(smi) self.assertTrue(m is not None) ps = Chem.SmilesParserParams() ps.allowCXSMILES = False m = Chem.MolFromSmiles(smi, ps) self.assertTrue(m is None) ps.allowCXSMILES = True ps.parseName = True m = Chem.MolFromSmiles(smi, ps) self.assertTrue(m is not None) self.assertTrue(m.GetAtomWithIdx(0).HasProp('atomLabel')) self.assertEquals(m.GetAtomWithIdx(0).GetProp('atomLabel'), "foo") self.assertTrue(m.HasProp('_Name')) self.assertEquals(m.GetProp('_Name'), "ourname") def testPickleProps(self): from rdkit.six.moves import cPickle m = Chem.MolFromSmiles('C1=CN=CC=C1') m.SetProp("_Name", "Name") for atom in m.GetAtoms(): atom.SetProp("_foo", "bar" + str(atom.GetIdx())) atom.SetProp("foo", "baz" + str(atom.GetIdx())) Chem.SetDefaultPickleProperties(Chem.PropertyPickleOptions.AllProps) pkl = cPickle.dumps(m) m2 = cPickle.loads(pkl) smi1 = Chem.MolToSmiles(m) smi2 = Chem.MolToSmiles(m2) self.assertTrue(smi1 == smi2) self.assertEqual(m2.GetProp("_Name"), "Name") for atom in m2.GetAtoms(): self.assertEqual(atom.GetProp("_foo"), "bar" + str(atom.GetIdx())) self.assertEqual(atom.GetProp("foo"), "baz" + str(atom.GetIdx())) Chem.SetDefaultPickleProperties(Chem.PropertyPickleOptions.AtomProps) pkl = cPickle.dumps(m) m2 = cPickle.loads(pkl) smi1 = Chem.MolToSmiles(m) smi2 = Chem.MolToSmiles(m2) self.assertTrue(smi1 == smi2) self.assertFalse(m2.HasProp("_Name")) for atom in m2.GetAtoms(): self.assertFalse(atom.HasProp("_foo")) self.assertEqual(atom.GetProp("foo"), "baz" + str(atom.GetIdx())) Chem.SetDefaultPickleProperties(Chem.PropertyPickleOptions.NoProps) pkl = cPickle.dumps(m) m2 = cPickle.loads(pkl) smi1 = Chem.MolToSmiles(m) smi2 = Chem.MolToSmiles(m2) self.assertTrue(smi1 == smi2) self.assertFalse(m2.HasProp("_Name")) for atom in m2.GetAtoms(): self.assertFalse(atom.HasProp("_foo")) self.assertFalse(atom.HasProp("foo")) Chem.SetDefaultPickleProperties(Chem.PropertyPickleOptions.MolProps | Chem.PropertyPickleOptions.PrivateProps) pkl = cPickle.dumps(m) m2 = cPickle.loads(pkl) smi1 = Chem.MolToSmiles(m) smi2 = Chem.MolToSmiles(m2) self.assertTrue(smi1 == smi2) self.assertEqual(m2.GetProp("_Name"), "Name") for atom in m2.GetAtoms(): self.assertFalse(atom.HasProp("_foo")) self.assertFalse(atom.HasProp("foo")) def testGithub1352(self): self.assertTrue('SP' in Chem.HybridizationType.names) self.assertTrue('S' in Chem.HybridizationType.names) m = Chem.MolFromSmiles('CC(=O)O.[Na]') self.assertEqual(m.GetAtomWithIdx(0).GetHybridization().name, 'SP3') self.assertEqual(m.GetAtomWithIdx(4).GetHybridization().name, 'S') def testGithub1366(self): mol = Chem.MolFromSmiles('*C*') mol = Chem.RWMol(mol) ats = iter(mol.GetAtoms()) atom = next(ats) mol.RemoveAtom(atom.GetIdx()) self.assertRaises(RuntimeError, next, ats) mol = Chem.MolFromSmiles('*C*') mol = Chem.RWMol(mol) bonds = iter(mol.GetBonds()) bond = next(bonds) mol.RemoveBond(bond.GetBeginAtomIdx(), bond.GetEndAtomIdx()) self.assertRaises(RuntimeError, next, bonds) def testGithub1478(self): data = """ MJ150720 8 8 0 0 0 0 0 0 0 0999 V2000 -0.4242 -1.4883 0.0000 O 0 0 0 0 0 0 0 0 0 0 0 0 0.2901 -1.0758 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 1.0046 0.9865 0.0000 A 0 0 0 0 0 0 0 0 0 0 0 0 1.0046 0.1614 0.0000 A 0 0 0 0 0 0 0 0 0 0 0 0 0.2901 -0.2508 0.0000 A 0 0 0 0 0 0 0 0 0 0 0 0 -0.4243 0.1614 0.0000 A 0 0 0 0 0 0 0 0 0 0 0 0 -0.4243 0.9865 0.0000 A 0 0 0 0 0 0 0 0 0 0 0 0 0.2901 1.3990 0.0000 A 0 0 0 0 0 0 0 0 0 0 0 0 7 6 4 0 0 0 0 8 7 4 0 0 0 0 6 5 4 0 0 0 0 5 4 4 0 0 0 0 5 2 1 0 0 0 0 4 3 4 0 0 0 0 8 3 4 0 0 0 0 2 1 2 0 0 0 0 M END """ pattern = Chem.MolFromMolBlock(data) m = Chem.MolFromSmiles("c1ccccc1C=O") self.assertTrue(m.HasSubstructMatch(pattern)) def testGithub1320(self): import pickle mol = Chem.MolFromSmiles('N[C@@H](C)O') mol2 = pickle.loads(pickle.dumps(mol)) self.assertEqual( Chem.MolToSmiles(mol, isomericSmiles=True), Chem.MolToSmiles(mol2, isomericSmiles=True)) Chem.SetDefaultPickleProperties(Chem.PropertyPickleOptions.AtomProps | Chem.PropertyPickleOptions.BondProps | Chem.PropertyPickleOptions.MolProps | Chem.PropertyPickleOptions.PrivateProps | Chem.PropertyPickleOptions.ComputedProps) mol3 = pickle.loads(pickle.dumps(mol)) for a1, a2 in zip(mol.GetAtoms(), mol3.GetAtoms()): d1 = a1.GetPropsAsDict() d2 = a2.GetPropsAsDict() if "__computedProps" in d1: c1 = list(d1["__computedProps"]) c2 = list(d2["__computedProps"]) del d1["__computedProps"] del d2["__computedProps"] self.assertEqual(c1, c2) assert d1 == d2 for a1, a2 in zip(mol.GetBonds(), mol3.GetBonds()): d1 = a1.GetPropsAsDict() d2 = a2.GetPropsAsDict() if "__computedProps" in d1: c1 = list(d1["__computedProps"]) c2 = list(d2["__computedProps"]) del d1["__computedProps"] del d2["__computedProps"] self.assertEqual(c1, c2) assert d1 == d2 self.assertEqual( Chem.MolToSmiles(mol, isomericSmiles=True), Chem.MolToSmiles(mol3, isomericSmiles=True)) def testOldPropPickles(self): data = 'crdkit.Chem.rdchem\nMol\np0\n(S\'\\xef\\xbe\\xad\\xde\\x00\\x00\\x00\\x00\\x08\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00)\\x00\\x00\\x00-\\x00\\x00\\x00\\x80\\x01\\x06\\x00`\\x00\\x00\\x00\\x01\\x03\\x07\\x00`\\x00\\x00\\x00\\x02\\x01\\x06 4\\x00\\x00\\x00\\x01\\x01\\x04\\x06\\x00`\\x00\\x00\\x00\\x01\\x03\\x06\\x00(\\x00\\x00\\x00\\x03\\x04\\x08\\x00(\\x00\\x00\\x00\\x03\\x02\\x07\\x00h\\x00\\x00\\x00\\x03\\x02\\x01\\x06 4\\x00\\x00\\x00\\x02\\x01\\x04\\x06\\x00(\\x00\\x00\\x00\\x03\\x04\\x08\\x00(\\x00\\x00\\x00\\x03\\x02\\x07\\x00(\\x00\\x00\\x00\\x03\\x03\\x06\\x00`\\x00\\x00\\x00\\x02\\x02\\x06 4\\x00\\x00\\x00\\x01\\x01\\x04\\x08\\x00(\\x00\\x00\\x00\\x03\\x02\\x06@(\\x00\\x00\\x00\\x03\\x04\\x06@h\\x00\\x00\\x00\\x03\\x03\\x01\\x06@h\\x00\\x00\\x00\\x03\\x03\\x01\\x06@h\\x00\\x00\\x00\\x03\\x03\\x01\\x06@h\\x00\\x00\\x00\\x03\\x03\\x01\\x06@h\\x00\\x00\\x00\\x03\\x03\\x01\\x06\\x00`\\x00\\x00\\x00\\x02\\x02\\x06 4\\x00\\x00\\x00\\x01\\x01\\x04\\x06\\x00(\\x00\\x00\\x00\\x03\\x04\\x08\\x00(\\x00\\x00\\x00\\x03\\x02\\x07\\x00h\\x00\\x00\\x00\\x03\\x02\\x01\\x06 4\\x00\\x00\\x00\\x02\\x01\\x04\\x06\\x00`\\x00\\x00\\x00\\x02\\x02\\x06\\x00`\\x00\\x00\\x00\\x02\\x02\\x06\\x00`\\x00\\x00\\x00\\x02\\x02\\x06@(\\x00\\x00\\x00\\x03\\x04\\x06@h\\x00\\x00\\x00\\x03\\x03\\x01\\x06@h\\x00\\x00\\x00\\x03\\x03\\x01\\x06@h\\x00\\x00\\x00\\x03\\x03\\x01\\x06@h\\x00\\x00\\x00\\x03\\x03\\x01\\x06@(\\x00\\x00\\x00\\x03\\x04\\x06\\x00`\\x00\\x00\\x00\\x03\\x01\\x06\\x00`\\x00\\x00\\x00\\x02\\x02\\x06\\x00`\\x00\\x00\\x00\\x02\\x02\\x06\\x00`\\x00\\x00\\x00\\x02\\x02\\x06\\x00`\\x00\\x00\\x00\\x02\\x02\\x06\\x00`\\x00\\x00\\x00\\x02\\x02\\x0b\\x00\\x01\\x00\\x01\\x02\\x00\\x02\\x03\\x00\\x02\\x04\\x00\\x04\\x05(\\x02\\x04\\x06 \\x06\\x07\\x00\\x07\\x08\\x00\\x08\\t(\\x02\\x08\\n \\n\\x0b\\x00\\x0b\\x0c\\x00\\x0c\\r\\x00\\r\\x0e \\x0e\\x0fh\\x0c\\x0f\\x10h\\x0c\\x10\\x11h\\x0c\\x11\\x12h\\x0c\\x12\\x13h\\x0c\\x0c\\x14\\x00\\x14\\x15\\x00\\x15\\x16\\x00\\x16\\x17(\\x02\\x16\\x18 \\x18\\x19\\x00\\x19\\x1a\\x00\\x1a\\x1b\\x00\\x1b\\x1c\\x00\\x1c\\x1d\\x00\\x1d\\x1eh\\x0c\\x1e\\x1fh\\x0c\\x1f h\\x0c !h\\x0c!"h\\x0c\\x07#\\x00#$\\x00$%\\x00%&\\x00&\\\'\\x00\\\'(\\x00\\x15\\n\\x00"\\x19\\x00(#\\x00\\x13\\x0eh\\x0c"\\x1dh\\x0c\\x14\\x05\\x05\\x0b\\n\\x15\\x14\\x0c\\x06\\x0f\\x10\\x11\\x12\\x13\\x0e\\x06\\x1a\\x1b\\x1c\\x1d"\\x19\\x06\\x1e\\x1f !"\\x1d\\x06$%&\\\'(#\\x17\\x00\\x00\\x00\\x00\\x12\\x03\\x00\\x00\\x00\\x07\\x00\\x00\\x00numArom\\x01\\x02\\x00\\x00\\x00\\x0f\\x00\\x00\\x00_StereochemDone\\x01\\x01\\x00\\x00\\x00\\x03\\x00\\x00\\x00foo\\x00\\x03\\x00\\x00\\x00bar\\x13:\\x02\\x00\\x00\\x00\\x08\\x00\\x00\\x00_CIPRank\\x02\\x12\\x00\\x00\\x00\\x05\\x00\\x00\\x00myidx\\x00\\x01\\x00\\x00\\x000\\x02\\x00\\x00\\x00\\x08\\x00\\x00\\x00_CIPRank\\x02\\x1d\\x00\\x00\\x00\\x05\\x00\\x00\\x00myidx\\x00\\x01\\x00\\x00\\x001\\x04\\x00\\x00\\x00\\x08\\x00\\x00\\x00_CIPRank\\x02\\x15\\x00\\x00\\x00\\x12\\x00\\x00\\x00_ChiralityPossible\\x01\\x01\\x00\\x00\\x00\\x08\\x00\\x00\\x00_CIPCode\\x00\\x01\\x00\\x00\\x00S\\x05\\x00\\x00\\x00myidx\\x00\\x01\\x00\\x00\\x002\\x02\\x00\\x00\\x00\\x08\\x00\\x00\\x00_CIPRank\\x02\\x00\\x00\\x00\\x00\\x05\\x00\\x00\\x00myidx\\x00\\x01\\x00\\x00\\x003\\x02\\x00\\x00\\x00\\x08\\x00\\x00\\x00_CIPRank\\x02\\x1a\\x00\\x00\\x00\\x05\\x00\\x00\\x00myidx\\x00\\x01\\x00\\x00\\x004\\x02\\x00\\x00\\x00\\x08\\x00\\x00\\x00_CIPRank\\x02"\\x00\\x00\\x00\\x05\\x00\\x00\\x00myidx\\x00\\x01\\x00\\x00\\x005\\x02\\x00\\x00\\x00\\x08\\x00\\x00\\x00_CIPRank\\x02\\x1f\\x00\\x00\\x00\\x05\\x00\\x00\\x00myidx\\x00\\x01\\x00\\x00\\x006\\x04\\x00\\x00\\x00\\x08\\x00\\x00\\x00_CIPRank\\x02\\x16\\x00\\x00\\x00\\x12\\x00\\x00\\x00_ChiralityPossible\\x01\\x01\\x00\\x00\\x00\\x08\\x00\\x00\\x00_CIPCode\\x00\\x01\\x00\\x00\\x00S\\x05\\x00\\x00\\x00myidx\\x00\\x01\\x00\\x00\\x007\\x02\\x00\\x00\\x00\\x08\\x00\\x00\\x00_CIPRank\\x02\\x1c\\x00\\x00\\x00\\x05\\x00\\x00\\x00myidx\\x00\\x01\\x00\\x00\\x008\\x02\\x00\\x00\\x00\\x08\\x00\\x00\\x00_CIPRank\\x02$\\x00\\x00\\x00\\x05\\x00\\x00\\x00myidx\\x00\\x01\\x00\\x00\\x009\\x02\\x00\\x00\\x00\\x08\\x00\\x00\\x00_CIPRank\\x02 \\x00\\x00\\x00\\x05\\x00\\x00\\x00myidx\\x00\\x02\\x00\\x00\\x0010\\x02\\x00\\x00\\x00\\x08\\x00\\x00\\x00_CIPRank\\x02\\x13\\x00\\x00\\x00\\x05\\x00\\x00\\x00myidx\\x00\\x02\\x00\\x00\\x0011\\x04\\x00\\x00\\x00\\x08\\x00\\x00\\x00_CIPRank\\x02\\x18\\x00\\x00\\x00\\x12\\x00\\x00\\x00_ChiralityPossible\\x01\\x01\\x00\\x00\\x00\\x08\\x00\\x00\\x00_CIPCode\\x00\\x01\\x00\\x00\\x00S\\x05\\x00\\x00\\x00myidx\\x00\\x02\\x00\\x00\\x0012\\x02\\x00\\x00\\x00\\x08\\x00\\x00\\x00_CIPRank\\x02!\\x00\\x00\\x00\\x05\\x00\\x00\\x00myidx\\x00\\x02\\x00\\x00\\x0013\\x02\\x00\\x00\\x00\\x08\\x00\\x00\\x00_CIPRank\\x02\\x19\\x00\\x00\\x00\\x05\\x00\\x00\\x00myidx\\x00\\x02\\x00\\x00\\x0014\\x02\\x00\\x00\\x00\\x08\\x00\\x00\\x00_CIPRank\\x02\\x0f\\x00\\x00\\x00\\x05\\x00\\x00\\x00myidx\\x00\\x02\\x00\\x00\\x0015\\x02\\x00\\x00\\x00\\x08\\x00\\x00\\x00_CIPRank\\x02\\x0b\\x00\\x00\\x00\\x05\\x00\\x00\\x00myidx\\x00\\x02\\x00\\x00\\x0016\\x02\\x00\\x00\\x00\\x08\\x00\\x00\\x00_CIPRank\\x02\\x08\\x00\\x00\\x00\\x05\\x00\\x00\\x00myidx\\x00\\x02\\x00\\x00\\x0017\\x02\\x00\\x00\\x00\\x08\\x00\\x00\\x00_CIPRank\\x02\\x0b\\x00\\x00\\x00\\x05\\x00\\x00\\x00myidx\\x00\\x02\\x00\\x00\\x0018\\x02\\x00\\x00\\x00\\x08\\x00\\x00\\x00_CIPRank\\x02\\x0f\\x00\\x00\\x00\\x05\\x00\\x00\\x00myidx\\x00\\x02\\x00\\x00\\x0019\\x02\\x00\\x00\\x00\\x08\\x00\\x00\\x00_CIPRank\\x02\\x07\\x00\\x00\\x00\\x05\\x00\\x00\\x00myidx\\x00\\x02\\x00\\x00\\x0020\\x04\\x00\\x00\\x00\\x08\\x00\\x00\\x00_CIPRank\\x02\\x17\\x00\\x00\\x00\\x12\\x00\\x00\\x00_ChiralityPossible\\x01\\x01\\x00\\x00\\x00\\x08\\x00\\x00\\x00_CIPCode\\x00\\x01\\x00\\x00\\x00S\\x05\\x00\\x00\\x00myidx\\x00\\x02\\x00\\x00\\x0021\\x02\\x00\\x00\\x00\\x08\\x00\\x00\\x00_CIPRank\\x02\\x1b\\x00\\x00\\x00\\x05\\x00\\x00\\x00myidx\\x00\\x02\\x00\\x00\\x0022\\x02\\x00\\x00\\x00\\x08\\x00\\x00\\x00_CIPRank\\x02#\\x00\\x00\\x00\\x05\\x00\\x00\\x00myidx\\x00\\x02\\x00\\x00\\x0023\\x02\\x00\\x00\\x00\\x08\\x00\\x00\\x00_CIPRank\\x02\\x1e\\x00\\x00\\x00\\x05\\x00\\x00\\x00myidx\\x00\\x02\\x00\\x00\\x0024\\x04\\x00\\x00\\x00\\x08\\x00\\x00\\x00_CIPRank\\x02\\x14\\x00\\x00\\x00\\x12\\x00\\x00\\x00_ChiralityPossible\\x01\\x01\\x00\\x00\\x00\\x08\\x00\\x00\\x00_CIPCode\\x00\\x01\\x00\\x00\\x00R\\x05\\x00\\x00\\x00myidx\\x00\\x02\\x00\\x00\\x0025\\x02\\x00\\x00\\x00\\x08\\x00\\x00\\x00_CIPRank\\x02\\x06\\x00\\x00\\x00\\x05\\x00\\x00\\x00myidx\\x00\\x02\\x00\\x00\\x0026\\x02\\x00\\x00\\x00\\x08\\x00\\x00\\x00_CIPRank\\x02\\x03\\x00\\x00\\x00\\x05\\x00\\x00\\x00myidx\\x00\\x02\\x00\\x00\\x0027\\x02\\x00\\x00\\x00\\x08\\x00\\x00\\x00_CIPRank\\x02\\x05\\x00\\x00\\x00\\x05\\x00\\x00\\x00myidx\\x00\\x02\\x00\\x00\\x0028\\x02\\x00\\x00\\x00\\x08\\x00\\x00\\x00_CIPRank\\x02\\x10\\x00\\x00\\x00\\x05\\x00\\x00\\x00myidx\\x00\\x02\\x00\\x00\\x0029\\x02\\x00\\x00\\x00\\x08\\x00\\x00\\x00_CIPRank\\x02\\x0c\\x00\\x00\\x00\\x05\\x00\\x00\\x00myidx\\x00\\x02\\x00\\x00\\x0030\\x02\\x00\\x00\\x00\\x08\\x00\\x00\\x00_CIPRank\\x02\\t\\x00\\x00\\x00\\x05\\x00\\x00\\x00myidx\\x00\\x02\\x00\\x00\\x0031\\x02\\x00\\x00\\x00\\x08\\x00\\x00\\x00_CIPRank\\x02\\n\\x00\\x00\\x00\\x05\\x00\\x00\\x00myidx\\x00\\x02\\x00\\x00\\x0032\\x02\\x00\\x00\\x00\\x08\\x00\\x00\\x00_CIPRank\\x02\\r\\x00\\x00\\x00\\x05\\x00\\x00\\x00myidx\\x00\\x02\\x00\\x00\\x0033\\x02\\x00\\x00\\x00\\x08\\x00\\x00\\x00_CIPRank\\x02\\x11\\x00\\x00\\x00\\x05\\x00\\x00\\x00myidx\\x00\\x02\\x00\\x00\\x0034\\x02\\x00\\x00\\x00\\x08\\x00\\x00\\x00_CIPRank\\x02\\x0e\\x00\\x00\\x00\\x05\\x00\\x00\\x00myidx\\x00\\x02\\x00\\x00\\x0035\\x02\\x00\\x00\\x00\\x08\\x00\\x00\\x00_CIPRank\\x02\\x04\\x00\\x00\\x00\\x05\\x00\\x00\\x00myidx\\x00\\x02\\x00\\x00\\x0036\\x02\\x00\\x00\\x00\\x08\\x00\\x00\\x00_CIPRank\\x02\\x02\\x00\\x00\\x00\\x05\\x00\\x00\\x00myidx\\x00\\x02\\x00\\x00\\x0037\\x02\\x00\\x00\\x00\\x08\\x00\\x00\\x00_CIPRank\\x02\\x01\\x00\\x00\\x00\\x05\\x00\\x00\\x00myidx\\x00\\x02\\x00\\x00\\x0038\\x02\\x00\\x00\\x00\\x08\\x00\\x00\\x00_CIPRank\\x02\\x02\\x00\\x00\\x00\\x05\\x00\\x00\\x00myidx\\x00\\x02\\x00\\x00\\x0039\\x02\\x00\\x00\\x00\\x08\\x00\\x00\\x00_CIPRank\\x02\\x04\\x00\\x00\\x00\\x05\\x00\\x00\\x00myidx\\x00\\x02\\x00\\x00\\x0040\\x13\\x16\'\np1\ntp2\nRp3\n.' from rdkit.six.moves import cPickle # bonds were broken in v1 m2 = cPickle.loads(data.encode("utf-8"), encoding='bytes') self.assertEqual(m2.GetProp("foo"), "bar") for atom in m2.GetAtoms(): self.assertEqual(atom.GetProp("myidx"), str(atom.GetIdx())) self.assertEqual( Chem.MolToSmiles(m2, True), Chem.MolToSmiles( Chem.MolFromSmiles( "CN[C@@H](C)C(=O)N[C@H](C(=O)N1C[C@@H](Oc2ccccc2)C[C@H]1C(=O)N[C@@H]1CCCc2ccccc21)C1CCCCC1" ), True)) def testGithub1461(self): # this is simple, it should throw a precondition and not seg fault m = Chem.RWMol() try: m.AddBond(0, 1, Chem.BondType.SINGLE) self.assertFalse(True) # shouldn't get here except RuntimeError: pass def testMolBundles1(self): b = Chem.MolBundle() smis = ('CC(Cl)(F)CC(F)(Br)', 'C[C@](Cl)(F)C[C@H](F)(Br)', 'C[C@](Cl)(F)C[C@@H](F)(Br)') for smi in smis: b.AddMol(Chem.MolFromSmiles(smi)) self.assertEqual(len(b), 3) self.assertEqual(b.Size(), 3) self.assertRaises(IndexError, lambda: b[4]) self.assertEqual( Chem.MolToSmiles(b[1], isomericSmiles=True), Chem.MolToSmiles(Chem.MolFromSmiles(smis[1]), isomericSmiles=True)) self.failUnless( b.HasSubstructMatch(Chem.MolFromSmiles('CC(Cl)(F)CC(F)(Br)'), useChirality=True)) self.failUnless( b.HasSubstructMatch(Chem.MolFromSmiles('C[C@](Cl)(F)C[C@@H](F)(Br)'), useChirality=True)) self.failUnless( b.HasSubstructMatch(Chem.MolFromSmiles('C[C@@](Cl)(F)C[C@@H](F)(Br)'), useChirality=False)) self.failIf( b.HasSubstructMatch(Chem.MolFromSmiles('C[C@@](Cl)(F)C[C@@H](F)(Br)'), useChirality=True)) self.assertEqual( len(b.GetSubstructMatch(Chem.MolFromSmiles('CC(Cl)(F)CC(F)(Br)'), useChirality=True)), 8) self.assertEqual( len(b.GetSubstructMatch(Chem.MolFromSmiles('C[C@](Cl)(F)C[C@@H](F)(Br)'), useChirality=True)), 8) self.assertEqual( len( b.GetSubstructMatch(Chem.MolFromSmiles('C[C@@](Cl)(F)C[C@@H](F)(Br)'), useChirality=False)), 8) self.assertEqual( len( b.GetSubstructMatch(Chem.MolFromSmiles('C[C@@](Cl)(F)C[C@@H](F)(Br)'), useChirality=True)), 0) self.assertEqual( len(b.GetSubstructMatches(Chem.MolFromSmiles('CC(Cl)(F)CC(F)(Br)'), useChirality=True)), 1) self.assertEqual( len( b.GetSubstructMatches(Chem.MolFromSmiles('C[C@](Cl)(F)C[C@@H](F)(Br)'), useChirality=True)), 1) self.assertEqual( len( b.GetSubstructMatches( Chem.MolFromSmiles('C[C@@](Cl)(F)C[C@@H](F)(Br)'), useChirality=False)), 1) self.assertEqual( len( b.GetSubstructMatches(Chem.MolFromSmiles('C[C@@](Cl)(F)C[C@@H](F)(Br)'), useChirality=True)), 0) self.assertEqual( len(b.GetSubstructMatches(Chem.MolFromSmiles('CC(Cl)(F)CC(F)(Br)'), useChirality=True)[0]), 8) self.assertEqual( len( b.GetSubstructMatches(Chem.MolFromSmiles('C[C@](Cl)(F)C[C@@H](F)(Br)'), useChirality=True)[0]), 8) self.assertEqual( len( b.GetSubstructMatches( Chem.MolFromSmiles('C[C@@](Cl)(F)C[C@@H](F)(Br)'), useChirality=False)[0]), 8) def testMolBundles2(self): b = Chem.MolBundle() smis = ('Fc1c(Cl)cccc1', 'Fc1cc(Cl)ccc1', 'Fc1ccc(Cl)cc1') for smi in smis: b.AddMol(Chem.MolFromSmiles(smi)) self.assertEqual(len(b), 3) self.assertEqual(b.Size(), 3) self.failUnless(Chem.MolFromSmiles('Fc1c(Cl)cccc1').HasSubstructMatch(b)) self.failUnless(Chem.MolFromSmiles('Fc1cc(Cl)ccc1').HasSubstructMatch(b)) self.failUnless(Chem.MolFromSmiles('Fc1c(Cl)cccc1C').HasSubstructMatch(b)) self.failUnless(Chem.MolFromSmiles('Fc1cc(Cl)ccc1C').HasSubstructMatch(b)) self.failIf(Chem.MolFromSmiles('Fc1c(Br)cccc1').HasSubstructMatch(b)) self.assertEqual(len(Chem.MolFromSmiles('Fc1c(Cl)cccc1').GetSubstructMatch(b)), 8) self.assertEqual(len(Chem.MolFromSmiles('Fc1c(Cl)cccc1').GetSubstructMatches(b)), 1) self.assertEqual(len(Chem.MolFromSmiles('Fc1c(Cl)cccc1').GetSubstructMatches(b)[0]), 8) self.assertEqual(len(Chem.MolFromSmiles('Fc1ccc(Cl)cc1').GetSubstructMatches(b)), 1) self.assertEqual( len(Chem.MolFromSmiles('Fc1ccc(Cl)cc1').GetSubstructMatches(b, uniquify=False)), 2) self.assertEqual(len(Chem.MolFromSmiles('Fc1c(C)cccc1').GetSubstructMatch(b)), 0) self.assertEqual(len(Chem.MolFromSmiles('Fc1c(C)cccc1').GetSubstructMatches(b)), 0) def testGithub1622(self): nonaromatics = ( "C1=C[N]C=C1", # radicals are not two electron donors "O=C1C=CNC=C1", # exocyclic double bonds don't steal electrons "C1=CS(=O)C=C1", # not sure how to classify this example from the # OEChem docs "C1#CC=CC=C1" # benzyne # 5-membered heterocycles "C1=COC=C1", # furan "C1=CSC=C1", # thiophene "C1=CNC=C1", #pyrrole "C1=COC=N1", # oxazole "C1=CSC=N1", # thiazole "C1=CNC=N1", # imidzole "C1=CNN=C1", # pyrazole "C1=CON=C1", # isoxazole "C1=CSN=C1", # isothiazole "C1=CON=N1", # 1,2,3-oxadiazole "C1=CNN=N1", # 1,2,3-triazole "N1=CSC=N1", # 1,3,4-thiadiazole # not outside the second rows "C1=CC=C[Si]=C1", "C1=CC=CC=P1", # 5-membered heterocycles outside the second row "C1=C[Se]C=C1", 'C1=C[Te]C=C1') for smi in nonaromatics: m = Chem.MolFromSmiles(smi, sanitize=False) Chem.SanitizeMol(m, Chem.SANITIZE_ALL ^ Chem.SANITIZE_SETAROMATICITY) Chem.SetAromaticity(m, Chem.AROMATICITY_MDL) self.assertFalse(m.GetAtomWithIdx(0).GetIsAromatic()) aromatics = ( "C1=CC=CC=C1", # benzene, of course # hetrocyclics "N1=CC=CC=C1", # pyridine "N1=CC=CC=N1", # pyridazine "N1=CC=CN=C1", # pyrimidine "N1=CC=NC=C1", # pyrazine "N1=CN=CN=C1", # 1,3,5-triazine # polycyclic aromatics "C1=CC2=CC=CC=CC2=C1", # azulene "C1=CC=CC2=CC=CC=C12", "C1=CC2=CC=CC=CC=C12", "C1=CC=C2C(=C1)N=CC=N2", "C1=CN=CC2C=CC=CC1=2", "C1=CC=C2C(=C1)N=C3C=CC=CC3=N2", "C1=CN=NC2C=CC=CC1=2", # macrocycle aromatics "C1=CC=CC=CC=CC=C1", "C1=CC=CC=CC=CC=CC=CC=CC=CC=C1", "N1=CN=NC=CC=CC=CC=CC=CC=CC=CC=CC=CC=CC=CC=CC=C1") for smi in aromatics: m = Chem.MolFromSmiles(smi, sanitize=False) Chem.SanitizeMol(m, Chem.SANITIZE_ALL ^ Chem.SANITIZE_SETAROMATICITY) Chem.SetAromaticity(m, Chem.AROMATICITY_MDL) self.assertTrue(m.GetAtomWithIdx(0).GetIsAromatic()) def testMolBlockChirality(self): m = Chem.MolFromSmiles('C[C@H](Cl)Br') mb = Chem.MolToMolBlock(m) m2 = Chem.MolFromMolBlock(mb) csmi1 = Chem.MolToSmiles(m, isomericSmiles=True) csmi2 = Chem.MolToSmiles(m2, isomericSmiles=True) self.assertEqual(csmi1, csmi2) def testIssue1735(self): # this shouldn't seg fault... m = Chem.RWMol() ranks = Chem.CanonicalRankAtoms(m, breakTies=False) ranks = Chem.CanonicalRankAtoms(m, breakTies=True) def testGithub1615(self): mb = """Issue399a.mol ChemDraw04050615582D 4 4 0 0 0 0 0 0 0 0999 V2000 -0.7697 0.0000 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 0.0553 0.0000 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 0.7697 0.4125 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 0.7697 -0.4125 0.0000 O 0 0 0 0 0 0 0 0 0 0 0 0 2 1 1 0 2 3 1 0 3 4 1 0 2 4 1 0 M END""" m = Chem.MolFromMolBlock(mb) self.assertFalse(m.GetAtomWithIdx(1).HasProp("_CIPCode")) self.assertEqual(m.GetBondWithIdx(0).GetBondDir(), Chem.BondDir.NONE) self.assertEqual(m.GetAtomWithIdx(1).GetChiralTag(), Chem.ChiralType.CHI_UNSPECIFIED) m.GetAtomWithIdx(1).SetChiralTag(Chem.ChiralType.CHI_TETRAHEDRAL_CW) Chem.AssignStereochemistry(m, force=True) self.assertTrue(m.GetAtomWithIdx(1).HasProp("_CIPCode")) self.assertEqual(m.GetAtomWithIdx(1).GetProp("_CIPCode"), "S") self.assertEqual(m.GetBondWithIdx(0).GetBondDir(), Chem.BondDir.NONE) Chem.WedgeBond(m.GetBondWithIdx(0), 1, m.GetConformer()) self.assertEqual(m.GetBondWithIdx(0).GetBondDir(), Chem.BondDir.BEGINWEDGE) def testSmilesToAtom(self): a = Chem.AtomFromSmiles("C") self.assertEqual(a.GetAtomicNum(), 6) b = Chem.BondFromSmiles("=") self.assertEqual(b.GetBondType(), Chem.BondType.DOUBLE) a = Chem.AtomFromSmiles("error") self.assertIs(a, None) b = Chem.BondFromSmiles("d") self.assertIs(b, None) a = Chem.AtomFromSmarts("C") self.assertEqual(a.GetAtomicNum(), 6) b = Chem.BondFromSmarts("=") self.assertEqual(b.GetBondType(), Chem.BondType.DOUBLE) a = Chem.AtomFromSmarts("error") self.assertIs(a, None) b = Chem.BondFromSmarts("d") self.assertIs(b, None) def testSVGParsing(self): svg = """<?xml version='1.0' encoding='iso-8859-1'?> <svg version='1.1' baseProfile='full' xmlns='http://www.w3.org/2000/svg' xmlns:rdkit='http://www.rdkit.org/xml' xmlns:xlink='http://www.w3.org/1999/xlink' xml:space='preserve' width='200px' height='200px' > <rect style='opacity:1.0;fill:#FFFFFF;stroke:none' width='200' height='200' x='0' y='0'> </rect> <path d='M 9.09091,89.4974 24.2916,84.7462' style='fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:2px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1' /> <path d='M 24.2916,84.7462 39.4923,79.9949' style='fill:none;fill-rule:evenodd;stroke:#0000FF;stroke-width:2px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1' /> <path d='M 86.2908,106.814 75.1709,93.4683 72.0765,96.8285 86.2908,106.814' style='fill:#000000;fill-rule:evenodd;stroke:#000000;stroke-width:2px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1' /> <path d='M 75.1709,93.4683 57.8622,86.8431 64.051,80.1229 75.1709,93.4683' style='fill:#0000FF;fill-rule:evenodd;stroke:#0000FF;stroke-width:2px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1' /> <path d='M 75.1709,93.4683 72.0765,96.8285 57.8622,86.8431 75.1709,93.4683' style='fill:#0000FF;fill-rule:evenodd;stroke:#0000FF;stroke-width:2px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1' /> <path d='M 86.2908,106.814 82.1459,125.293' style='fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:2px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1' /> <path d='M 82.1459,125.293 78.0009,143.772' style='fill:none;fill-rule:evenodd;stroke:#00CC00;stroke-width:2px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1' /> <path d='M 86.2908,106.814 129.89,93.1862' style='fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:2px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1' /> <path d='M 134.347,94.186 138.492,75.7069' style='fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:2px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1' /> <path d='M 138.492,75.7069 142.637,57.2277' style='fill:none;fill-rule:evenodd;stroke:#FF0000;stroke-width:2px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1' /> <path d='M 125.432,92.1865 129.577,73.7074' style='fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:2px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1' /> <path d='M 129.577,73.7074 133.722,55.2282' style='fill:none;fill-rule:evenodd;stroke:#FF0000;stroke-width:2px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1' /> <path d='M 129.89,93.1862 142.557,104.852' style='fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:2px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1' /> <path d='M 142.557,104.852 155.224,116.517' style='fill:none;fill-rule:evenodd;stroke:#FF0000;stroke-width:2px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1' /> <text x='39.4923' y='83.483' style='font-size:15px;font-style:normal;font-weight:normal;fill-opacity:1;stroke:none;font-family:sans-serif;text-anchor:start;fill:#0000FF' ><tspan>NH</tspan></text> <text x='67.6656' y='158.998' style='font-size:15px;font-style:normal;font-weight:normal;fill-opacity:1;stroke:none;font-family:sans-serif;text-anchor:start;fill:#00CC00' ><tspan>Cl</tspan></text> <text x='132.777' y='56.228' style='font-size:15px;font-style:normal;font-weight:normal;fill-opacity:1;stroke:none;font-family:sans-serif;text-anchor:start;fill:#FF0000' ><tspan>O</tspan></text> <text x='149.782' y='131.743' style='font-size:15px;font-style:normal;font-weight:normal;fill-opacity:1;stroke:none;font-family:sans-serif;text-anchor:start;fill:#FF0000' ><tspan>OH</tspan></text> <text x='89.9952' y='194' style='font-size:12px;font-style:normal;font-weight:normal;fill-opacity:1;stroke:none;font-family:sans-serif;text-anchor:start;fill:#000000' ><tspan>m1</tspan></text> <metadata> <rdkit:mol xmlns:rdkit = "http://www.rdkit.org/xml" version="0.9"> <rdkit:atom idx="1" atom-smiles="[CH3]" drawing-x="9.09091" drawing-y="89.4974" x="-2.78651" y="0.295614" z="0" /> <rdkit:atom idx="2" atom-smiles="[NH]" drawing-x="52.6897" drawing-y="75.8699" x="-1.35482" y="0.743114" z="0" /> <rdkit:atom idx="3" atom-smiles="[C@H]" drawing-x="86.2908" drawing-y="106.814" x="-0.251428" y="-0.273019" z="0" /> <rdkit:atom idx="4" atom-smiles="[Cl]" drawing-x="76.2932" drawing-y="151.385" x="-0.579728" y="-1.73665" z="0" /> <rdkit:atom idx="5" atom-smiles="[C]" drawing-x="129.89" drawing-y="93.1862" x="1.18027" y="0.174481" z="0" /> <rdkit:atom idx="6" atom-smiles="[O]" drawing-x="139.887" drawing-y="48.6148" x="1.50857" y="1.63811" z="0" /> <rdkit:atom idx="7" atom-smiles="[OH]" drawing-x="163.491" drawing-y="124.13" x="2.28366" y="-0.841652" z="0" /> <rdkit:bond idx="1" begin-atom-idx="1" end-atom-idx="2" bond-smiles="-" /> <rdkit:bond idx="2" begin-atom-idx="2" end-atom-idx="3" bond-smiles="-" /> <rdkit:bond idx="3" begin-atom-idx="3" end-atom-idx="4" bond-smiles="-" /> <rdkit:bond idx="4" begin-atom-idx="3" end-atom-idx="5" bond-smiles="-" /> <rdkit:bond idx="5" begin-atom-idx="5" end-atom-idx="6" bond-smiles="=" /> <rdkit:bond idx="6" begin-atom-idx="5" end-atom-idx="7" bond-smiles="-" /> </rdkit:mol></metadata> </svg>""" mol = Chem.MolFromRDKitSVG(svg) self.failUnlessEqual(mol.GetNumAtoms(), 7) self.failUnlessEqual(Chem.MolToSmiles(mol), 'CN[C@H](Cl)C(=O)O') svg2 = """<?xml version='1.0' encoding='iso-8859-1'?> <svg version='1.1' baseProfile='full' xmlns='http://www.w3.org/2000/svg' xmlns:rdkit='http://www.rdkit.org/xml' xmlns:xlink='http://www.w3.org/1999/xlink' xml:space='preserve' width='200px' height='200px' > <rect style='opacity:1.0;fill:#FFFFFF;stroke:none' width='200' height='200' x='0' y='0'> </rect> <path d='M 9.09091,89.4974 24.2916,84.7462' style='fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:2px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1' /> <path d='M 24.2916,84.7462 39.4923,79.9949' style='fill:none;fill-rule:evenodd;stroke:#0000FF;stroke-width:2px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1' /> <path d='M 86.2908,106.814 75.1709,93.4683 72.0765,96.8285 86.2908,106.814' style='fill:#000000;fill-rule:evenodd;stroke:#000000;stroke-width:2px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1' /> <path d='M 75.1709,93.4683 57.8622,86.8431 64.051,80.1229 75.1709,93.4683' style='fill:#0000FF;fill-rule:evenodd;stroke:#0000FF;stroke-width:2px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1' /> <path d='M 75.1709,93.4683 72.0765,96.8285 57.8622,86.8431 75.1709,93.4683' style='fill:#0000FF;fill-rule:evenodd;stroke:#0000FF;stroke-width:2px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1' /> <path d='M 86.2908,106.814 82.1459,125.293' style='fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:2px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1' /> <path d='M 82.1459,125.293 78.0009,143.772' style='fill:none;fill-rule:evenodd;stroke:#00CC00;stroke-width:2px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1' /> <path d='M 86.2908,106.814 129.89,93.1862' style='fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:2px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1' /> <path d='M 134.347,94.186 138.492,75.7069' style='fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:2px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1' /> <path d='M 138.492,75.7069 142.637,57.2277' style='fill:none;fill-rule:evenodd;stroke:#FF0000;stroke-width:2px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1' /> <path d='M 125.432,92.1865 129.577,73.7074' style='fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:2px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1' /> <path d='M 129.577,73.7074 133.722,55.2282' style='fill:none;fill-rule:evenodd;stroke:#FF0000;stroke-width:2px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1' /> <path d='M 129.89,93.1862 142.557,104.852' style='fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:2px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1' /> <path d='M 142.557,104.852 155.224,116.517' style='fill:none;fill-rule:evenodd;stroke:#FF0000;stroke-width:2px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1' /> <text x='39.4923' y='83.483' style='font-size:15px;font-style:normal;font-weight:normal;fill-opacity:1;stroke:none;font-family:sans-serif;text-anchor:start;fill:#0000FF' ><tspan>NH</tspan></text> <text x='67.6656' y='158.998' style='font-size:15px;font-style:normal;font-weight:normal;fill-opacity:1;stroke:none;font-family:sans-serif;text-anchor:start;fill:#00CC00' ><tspan>Cl</tspan></text> <text x='132.777' y='56.228' style='font-size:15px;font-style:normal;font-weight:normal;fill-opacity:1;stroke:none;font-family:sans-serif;text-anchor:start;fill:#FF0000' ><tspan>O</tspan></text> <text x='149.782' y='131.743' style='font-size:15px;font-style:normal;font-weight:normal;fill-opacity:1;stroke:none;font-family:sans-serif;text-anchor:start;fill:#FF0000' ><tspan>OH</tspan></text> <text x='89.9952' y='194' style='font-size:12px;font-style:normal;font-weight:normal;fill-opacity:1;stroke:none;font-family:sans-serif;text-anchor:start;fill:#000000' ><tspan>m1</tspan></text> </svg>""" mol = Chem.MolFromRDKitSVG(svg2) self.failUnless(mol is None) with self.assertRaises(RuntimeError): mol = Chem.MolFromRDKitSVG("bad svg") def testAssignStereochemistryFrom3D(self): def _stereoTester(mol,expectedCIP,expectedStereo): mol.UpdatePropertyCache() self.assertEqual(mol.GetNumAtoms(),9) self.assertFalse(mol.GetAtomWithIdx(1).HasProp("_CIPCode")) self.assertEqual(mol.GetBondWithIdx(3).GetStereo(),Chem.BondStereo.STEREONONE) for bond in mol.GetBonds(): bond.SetBondDir(Chem.BondDir.NONE) Chem.AssignStereochemistryFrom3D(mol) self.assertTrue(mol.GetAtomWithIdx(1).HasProp("_CIPCode")) self.assertEqual(mol.GetAtomWithIdx(1).GetProp("_CIPCode"),expectedCIP) self.assertEqual(mol.GetBondWithIdx(3).GetStereo(),expectedStereo) fileN = os.path.join(RDConfig.RDBaseDir, 'Code', 'GraphMol', 'test_data', 'stereochem.sdf') suppl = Chem.SDMolSupplier(fileN, sanitize=False) expected = ( ("R",Chem.BondStereo.STEREOZ), ("R",Chem.BondStereo.STEREOE), ("S",Chem.BondStereo.STEREOZ), ("S",Chem.BondStereo.STEREOE), ) for i,mol in enumerate(suppl): cip,stereo = expected[i] _stereoTester(mol,cip,stereo) def testGitHub2082(self): ctab=""" MJ150720 9 9 0 0 0 0 0 0 0 0999 V2000 2.5687 -0.7144 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 2.1562 0.0000 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 2.5687 0.7144 0.0000 O 0 0 0 0 0 0 0 0 0 0 0 0 1.3312 0.0000 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 0.9187 -0.7144 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 0.0937 -0.7144 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 -0.3187 0.0000 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 0.0937 0.7144 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 0.9187 0.7144 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 2 1 1 6 2 3 1 0 2 4 1 0 4 5 2 0 5 6 1 0 6 7 2 0 7 8 1 0 8 9 2 0 9 4 1 0 M END """ mol = Chem.MolFromMolBlock(ctab) self.assertFalse(mol.GetConformer().Is3D()) self.assertTrue("@" in Chem.MolToSmiles(mol,True)) def testGitHub2082_2(self): # test a mol block that lies is 3D but labelled 2D ofile = os.path.join(RDConfig.RDBaseDir, 'Code', 'GraphMol', 'Wrap', 'test_data', 'issue2082.mol') ctab = open(ofile).read() m = Chem.MolFromMolBlock(ctab) self.assertTrue(m.GetConformer().Is3D()) def testSetQuery(self): from rdkit.Chem import rdqueries pat = Chem.MolFromSmarts("[C]") self.assertFalse(Chem.MolFromSmiles("c1ccccc1").HasSubstructMatch(pat)) q = rdqueries.AtomNumEqualsQueryAtom(6) for atom in pat.GetAtoms(): atom.SetQuery(q) self.assertTrue(Chem.MolFromSmiles("c1ccccc1").HasSubstructMatch(pat)) def testGitHub1985(self): # simple check, this used to throw an exception try: Chem.MolToSmarts(Chem.MolFromSmarts("[C@]")) except: self.fail("[C@] caused an exception when roundtripping smarts") def testGetEnhancedStereo(self): rdbase = os.environ['RDBASE'] filename = os.path.join(rdbase, 'Code/GraphMol/FileParsers/test_data/two_centers_or.mol') m = Chem.MolFromMolFile(filename) sg = m.GetStereoGroups() self.assertEqual(len(sg), 2) group1 = sg[1] self.assertEqual(group1.GetGroupType(), Chem.StereoGroupType.STEREO_OR) stereo_atoms = group1.GetAtoms() self.assertEqual(len(stereo_atoms), 2) # file is 1 indexed and says 5 self.assertEqual(stereo_atoms[1].GetIdx(), 4) def testEnhancedStereoPreservesMol(self): """ Check that the stereo group (and the atoms therein) preserve the lifetime of the associated mol. """ rdbase = os.environ['RDBASE'] filename = os.path.join(rdbase, 'Code/GraphMol/FileParsers/test_data/two_centers_or.mol') m = Chem.MolFromMolFile(filename) sg = m.GetStereoGroups() m = None gc.collect() self.assertEqual(len(sg), 2) group1 = sg[1] stereo_atoms = group1.GetAtoms() sg = None gc.collect() self.assertEqual(stereo_atoms[1].GetIdx(), 4) self.assertEqual(stereo_atoms[1].GetOwningMol().GetNumAtoms(),8) if __name__ == '__main__': if "RDTESTCASE" in os.environ: suite = unittest.TestSuite() testcases = os.environ["RDTESTCASE"] for name in testcases.split(':'): suite.addTest(TestCase(name)) runner = unittest.TextTestRunner() runner.run(suite) else: unittest.main()
1
18,866
@greglandrum Is this test sufficient?
rdkit-rdkit
cpp
@@ -1,2 +1 @@ -GITHUB_USER = ENV['GITHUB_USER'] -GITHUB_PASSWORD = ENV['GITHUB_PASSWORD'] +GITHUB_ACCESS_TOKEN = ENV['GITHUB_ACCESS_TOKEN']
1
GITHUB_USER = ENV['GITHUB_USER'] GITHUB_PASSWORD = ENV['GITHUB_PASSWORD']
1
17,502
Prefer double-quoted strings unless you need single quotes to avoid extra backslashes for escaping.
thoughtbot-upcase
rb
@@ -0,0 +1,5 @@ +class MakePlansPolymorphic < ActiveRecord::Migration + def change + add_column :subscriptions, :plan_type, :string, null: false + end +end
1
1
8,009
I think Rails complains about the `null: false` part if we ever decide to roll this migration back. Might need to split this up into separate `up/down` methods to handle that.
thoughtbot-upcase
rb
@@ -618,8 +618,8 @@ func (mtask *managedTask) progressContainers() { // We've kicked off one or more transitions, wait for them to // complete, but keep reading events as we do. in fact, we have to for // transitions to complete - mtask.waitForContainerTransitions(transitions, transitionChange, transitionChangeContainer) - seelog.Debugf("Managed task [%s]: done transitioning all containers", mtask.Arn) + mtask.waitForContainerTransition(transitions, transitionChange, transitionChangeContainer) + seelog.Debugf("Managed task [%s]: wait for container transition done", mtask.Arn) // update the task status changed := mtask.UpdateStatus()
1
// Copyright 2014-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). You may // not use this file except in compliance with the License. A copy of the // License is located at // // http://aws.amazon.com/apache2.0/ // // or in the "license" file accompanying this file. This file is distributed // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either // express or implied. See the License for the specific language governing // permissions and limitations under the License. package engine import ( "context" "sync" "time" "github.com/aws/amazon-ecs-agent/agent/api" "github.com/aws/amazon-ecs-agent/agent/config" "github.com/aws/amazon-ecs-agent/agent/credentials" "github.com/aws/amazon-ecs-agent/agent/ecscni" "github.com/aws/amazon-ecs-agent/agent/engine/dependencygraph" "github.com/aws/amazon-ecs-agent/agent/eventstream" "github.com/aws/amazon-ecs-agent/agent/resources" "github.com/aws/amazon-ecs-agent/agent/statechange" "github.com/aws/amazon-ecs-agent/agent/statemanager" utilsync "github.com/aws/amazon-ecs-agent/agent/utils/sync" "github.com/aws/amazon-ecs-agent/agent/utils/ttime" "github.com/cihub/seelog" ) const ( // waitForPullCredentialsTimeout is the timeout agent trying to wait for pull // credentials from acs, after the timeout it will check the credentials manager // and start processing the task or start another round of waiting waitForPullCredentialsTimeout = 1 * time.Minute steadyStateTaskVerifyInterval = 5 * time.Minute stoppedSentWaitInterval = 30 * time.Second maxStoppedWaitTimes = 72 * time.Hour / stoppedSentWaitInterval taskUnableToTransitionToStoppedReason = "TaskStateError: Agent could not progress task's state to stopped" taskUnableToCreatePlatformResources = "TaskStateError: Agent could not create task's platform resources" ) var ( _stoppedSentWaitInterval = stoppedSentWaitInterval _maxStoppedWaitTimes = int(maxStoppedWaitTimes) ) type acsTaskUpdate struct { api.TaskStatus } type dockerContainerChange struct { container *api.Container event DockerContainerChangeEvent } type acsTransition struct { seqnum int64 desiredStatus api.TaskStatus } // containerTransition defines the struct for a container to transition type containerTransition struct { nextState api.ContainerStatus actionRequired bool reason error } // managedTask is a type that is meant to manage the lifecycle of a task. // There should be only one managed task construct for a given task arn and the // managed task should be the only thing to modify the task's known or desired statuses. // // The managedTask should run serially in a single goroutine in which it reads // messages from the two given channels and acts upon them. // This design is chosen to allow a safe level if isolation and avoid any race // conditions around the state of a task. // The data sources (e.g. docker, acs) that write to the task's channels may // block and it is expected that the managedTask listen to those channels // almost constantly. // The general operation should be: // 1) Listen to the channels // 2) On an event, update the status of the task and containers (known/desired) // 3) Figure out if any action needs to be done. If so, do it // 4) GOTO 1 // Item '3' obviously might lead to some duration where you are not listening // to the channels. However, this can be solved by kicking off '3' as a // goroutine and then only communicating the result back via the channels // (obviously once you kick off a goroutine you give up the right to write the // task's statuses yourself) type managedTask struct { *api.Task ctx context.Context cancel context.CancelFunc engine *DockerTaskEngine cfg *config.Config saver statemanager.Saver credentialsManager credentials.Manager cniClient ecscni.CNIClient taskStopWG *utilsync.SequentialWaitGroup acsMessages chan acsTransition dockerMessages chan dockerContainerChange stateChangeEvents chan statechange.Event containerChangeEventStream *eventstream.EventStream // unexpectedStart is a once that controls stopping a container that // unexpectedly started one time. // This exists because a 'start' after a container is meant to be stopped is // possible under some circumstances (e.g. a timeout). However, if it // continues to 'start' when we aren't asking it to, let it go through in // case it's a user trying to debug it or in case we're fighting with another // thing managing the container. unexpectedStart sync.Once _time ttime.Time _timeOnce sync.Once resource resources.Resource } // newManagedTask is a method on DockerTaskEngine to create a new managedTask. // This method must only be called when the engine.processTasks write lock is // already held. func (engine *DockerTaskEngine) newManagedTask(task *api.Task) *managedTask { ctx, cancel := context.WithCancel(engine.ctx) t := &managedTask{ ctx: ctx, cancel: cancel, Task: task, acsMessages: make(chan acsTransition), dockerMessages: make(chan dockerContainerChange), engine: engine, resource: engine.resource, cfg: engine.cfg, stateChangeEvents: engine.stateChangeEvents, containerChangeEventStream: engine.containerChangeEventStream, saver: engine.saver, credentialsManager: engine.credentialsManager, cniClient: engine.cniClient, taskStopWG: engine.taskStopGroup, } engine.managedTasks[task.Arn] = t return t } // overseeTask is the main goroutine of the managedTask. It runs an infinite // loop of receiving messages and attempting to take action based on those // messages. func (mtask *managedTask) overseeTask() { // Do a single updatestatus at the beginning to create the container // `desiredstatus`es which are a construct of the engine used only here, // not present on the backend mtask.UpdateStatus() // If this was a 'state restore', send all unsent statuses mtask.emitCurrentStatus() // Wait for host resources required by this task to become available mtask.waitForHostResources() // Main infinite loop. This is where we receive messages and dispatch work. for { // If it's steadyState, just spin until we need to do work for mtask.steadyState() { mtask.waitSteady() } if !mtask.GetKnownStatus().Terminal() { // If we aren't terminal and we aren't steady state, we should be // able to move some containers along. seelog.Debugf("Managed task [%s]: task not steady state or terminal; progressing it", mtask.Arn) // TODO: Add new resource provisioned state ? if mtask.cfg.TaskCPUMemLimit.Enabled() { err := mtask.resource.Setup(mtask.Task) if err != nil { seelog.Criticalf("Managed task [%s]: unable to setup platform resources: %v", mtask.Arn, err) mtask.SetDesiredStatus(api.TaskStopped) mtask.emitTaskEvent(mtask.Task, taskUnableToCreatePlatformResources) } seelog.Infof("Managed task [%s]: Cgroup resource set up for task complete", mtask.Arn) } mtask.progressContainers() } // If we reach this point, we've changed the task in some way. // Conversely, for it to spin in steady state it will have to have been // loaded in steady state or progressed through here, so saving here should // be sufficient to capture state changes. err := mtask.saver.Save() if err != nil { seelog.Warnf("Managed task [%s]: unable to checkpoint task's states to disk: %v", mtask.Arn, err) } if mtask.GetKnownStatus().Terminal() { break } } // We only break out of the above if this task is known to be stopped. Do // onetime cleanup here, including removing the task after a timeout seelog.Debugf("Managed task [%s]: Task has reached stopped. Waiting for container cleanup", mtask.Arn) mtask.cleanupCredentials() if mtask.StopSequenceNumber != 0 { seelog.Debugf("Managed task [%s]: Marking done for this sequence: %d", mtask.Arn, mtask.StopSequenceNumber) mtask.taskStopWG.Done(mtask.StopSequenceNumber) } // TODO: make this idempotent on agent restart go mtask.releaseIPInIPAM() mtask.cleanupTask(mtask.cfg.TaskCleanupWaitDuration) } // emitCurrentStatus emits a container event for every container and a task // event for the task func (mtask *managedTask) emitCurrentStatus() { for _, container := range mtask.Containers { mtask.emitContainerEvent(mtask.Task, container, "") } mtask.emitTaskEvent(mtask.Task, "") } // waitForHostResources waits for host resources to become available to start // the task. This involves waiting for previous stops to complete so the // resources become free. func (mtask *managedTask) waitForHostResources() { if mtask.StartSequenceNumber == 0 { // This is the first transition on this host. No need to wait return } if mtask.GetDesiredStatus().Terminal() { // Task's desired status is STOPPED. No need to wait in this case either return } seelog.Infof("Managed task [%s]: waiting for any previous stops to complete. Sequence number: %d", mtask.Arn, mtask.StartSequenceNumber) othersStoppedCtx, cancel := context.WithCancel(mtask.ctx) defer cancel() go func() { mtask.taskStopWG.Wait(mtask.StartSequenceNumber) cancel() }() for !mtask.waitEvent(othersStoppedCtx.Done()) { if mtask.GetDesiredStatus().Terminal() { // If we end up here, that means we received a start then stop for this // task before a task that was expected to stop before it could // actually stop break } } seelog.Infof("Managed task [%s]: wait over; ready to move towards status: %s", mtask.Arn, mtask.GetDesiredStatus().String()) } // waitSteady waits for a task to leave steady-state by waiting for a new // event, or a timeout. func (mtask *managedTask) waitSteady() { seelog.Debugf("Managed task [%s]: task at steady state: %s", mtask.Arn, mtask.GetKnownStatus().String()) timeoutCtx, cancel := context.WithTimeout(mtask.ctx, steadyStateTaskVerifyInterval) defer cancel() timedOut := mtask.waitEvent(timeoutCtx.Done()) if timedOut { seelog.Debugf("Managed task [%s]: checking to make sure it's still at steadystate", mtask.Arn) go mtask.engine.CheckTaskState(mtask.Task) } } // steadyState returns if the task is in a steady state. Steady state is when task's desired // and known status are both RUNNING func (mtask *managedTask) steadyState() bool { taskKnownStatus := mtask.GetKnownStatus() return taskKnownStatus == api.TaskRunning && taskKnownStatus >= mtask.GetDesiredStatus() } // cleanupCredentials removes credentials for a stopped task func (mtask *managedTask) cleanupCredentials() { taskCredentialsID := mtask.GetCredentialsID() if taskCredentialsID != "" { mtask.credentialsManager.RemoveCredentials(taskCredentialsID) } } // waitEvent waits for any event to occur. If an event occurs, the appropriate // handler is called. Generally the stopWaiting arg is the context's Done // channel. When the Done channel is signalled by the context, waitEvent will // return true. func (mtask *managedTask) waitEvent(stopWaiting <-chan struct{}) bool { seelog.Debugf("Managed task [%s]: waiting for event for task", mtask.Arn) select { case acsTransition := <-mtask.acsMessages: seelog.Debugf("Managed task [%s]: got acs event", mtask.Arn) mtask.handleDesiredStatusChange(acsTransition.desiredStatus, acsTransition.seqnum) return false case dockerChange := <-mtask.dockerMessages: seelog.Debugf("Managed task [%s]: got container [%s] event: [%s]", mtask.Arn, dockerChange.container.Name, dockerChange.event.Status.String()) mtask.handleContainerChange(dockerChange) return false case <-stopWaiting: seelog.Debugf("Managed task [%s]: no longer waiting", mtask.Arn) return true } } // handleDesiredStatusChange updates the desired status on the task. Updates // only occur if the new desired status is "compatible" (farther along than the // current desired state); "redundant" (less-than or equal desired states) are // ignored and dropped. func (mtask *managedTask) handleDesiredStatusChange(desiredStatus api.TaskStatus, seqnum int64) { // Handle acs message changes this task's desired status to whatever // acs says it should be if it is compatible seelog.Debugf("Managed task [%s]: new acs transition to: %s; sequence number: %d; task stop sequence number: %d", mtask.Arn, desiredStatus.String(), seqnum, mtask.StopSequenceNumber) if desiredStatus <= mtask.GetDesiredStatus() { seelog.Debugf("Managed task [%s]: redundant task transition from [%s] to [%s], ignoring", mtask.Arn, mtask.GetDesiredStatus().String(), desiredStatus.String()) return } if desiredStatus == api.TaskStopped && seqnum != 0 && mtask.GetStopSequenceNumber() == 0 { seelog.Debugf("Managed task [%s]: task moving to stopped, adding to stopgroup with sequence number: %d", mtask.Arn, seqnum) mtask.SetStopSequenceNumber(seqnum) mtask.taskStopWG.Add(seqnum, 1) } mtask.SetDesiredStatus(desiredStatus) mtask.UpdateDesiredStatus() } // handleContainerChange updates a container's known status. If the message // contains any interesting information (like exit codes or ports), they are // propagated. func (mtask *managedTask) handleContainerChange(containerChange dockerContainerChange) { // locate the container container := containerChange.container found := mtask.isContainerFound(container) if !found { seelog.Criticalf("Managed task [%s]: state error; invoked with another task's container [%s]!", mtask.Arn, container.Name) return } event := containerChange.event seelog.Debugf("Managed task [%s]: handling container change [%v] for container [%s]", mtask.Arn, event, container.Name) // If this is a backwards transition stopped->running, the first time set it // to be known running so it will be stopped. Subsequently ignore these backward transitions containerKnownStatus := container.GetKnownStatus() mtask.handleStoppedToRunningContainerTransition(event.Status, container) if event.Status <= containerKnownStatus { seelog.Infof("Managed task [%s]: redundant container state change. %s to %s, but already %s", mtask.Arn, container.Name, event.Status.String(), containerKnownStatus.String()) return } // Update the container to be known currentKnownStatus := containerKnownStatus container.SetKnownStatus(event.Status) updateContainerMetadata(&event.DockerContainerMetadata, container, mtask.Task) if event.Error != nil { proceedAnyway := mtask.handleEventError(containerChange, currentKnownStatus) if !proceedAnyway { return } } // Update the container health status if container.HealthStatusShouldBeReported() { container.SetHealthStatus(event.Health) } mtask.RecordExecutionStoppedAt(container) seelog.Debugf("Managed task [%s]: sending container change event to tcs, container: [%s(%s)], status: %s", mtask.Arn, container.Name, event.DockerID, event.Status.String()) err := mtask.containerChangeEventStream.WriteToEventStream(event) if err != nil { seelog.Warnf("Managed task [%s]: failed to write container [%s] change event to tcs event stream: %v", mtask.Arn, container.Name, err) } mtask.emitContainerEvent(mtask.Task, container, "") if mtask.UpdateStatus() { seelog.Debugf("Managed task [%s]: container change also resulted in task change [%s]: [%s]", mtask.Arn, container.Name, mtask.GetDesiredStatus().String()) // If knownStatus changed, let it be known mtask.emitTaskEvent(mtask.Task, "") } seelog.Debugf("Managed task [%s]: container change also resulted in task change [%s]: [%s]", mtask.Arn, container.Name, mtask.GetDesiredStatus().String()) } func (mtask *managedTask) emitTaskEvent(task *api.Task, reason string) { event, err := api.NewTaskStateChangeEvent(task, reason) if err != nil { seelog.Infof("Managed task [%s]: unable to create task state change event [%s]: %v", task.Arn, reason, err) return } seelog.Infof("Managed task [%s]: sending task change event [%s]", mtask.Arn, event.String()) mtask.stateChangeEvents <- event seelog.Infof("Managed task [%s]: sent task change event [%s]", mtask.Arn, event.String()) } // emitContainerEvent passes a given event up through the containerEvents channel if necessary. // It will omit events the backend would not process and will perform best-effort deduplication of events. func (mtask *managedTask) emitContainerEvent(task *api.Task, cont *api.Container, reason string) { event, err := api.NewContainerStateChangeEvent(task, cont, reason) if err != nil { seelog.Debugf("Managed task [%s]: unable to create state change event for container [%s]: %v", task.Arn, cont.Name, err) return } seelog.Infof("Managed task [%s]: sending container change event [%s]: %s", mtask.Arn, cont.Name, event.String()) mtask.stateChangeEvents <- event seelog.Infof("Managed task [%s]: sent container change event [%s]: %s", mtask.Arn, cont.Name, event.String()) } func (mtask *managedTask) isContainerFound(container *api.Container) bool { found := false for _, c := range mtask.Containers { if container == c { found = true break } } return found } // releaseIPInIPAM releases the ip used by the task for awsvpc func (mtask *managedTask) releaseIPInIPAM() { if mtask.ENI == nil { return } seelog.Infof("Managed task [%s]: IPAM releasing ip for task eni", mtask.Arn) cfg, err := mtask.BuildCNIConfig() if err != nil { seelog.Warnf("Managed task [%s]: failed to release ip; unable to build cni configuration: %v", mtask.Arn, err) return } err = mtask.cniClient.ReleaseIPResource(cfg) if err != nil { seelog.Warnf("Managed task [%s]: failed to release ip; IPAM error: %v", mtask.Arn, err) return } } // handleStoppedToRunningContainerTransition detects a "backwards" container // transition where a known-stopped container is found to be running again and // handles it. func (mtask *managedTask) handleStoppedToRunningContainerTransition(status api.ContainerStatus, container *api.Container) { containerKnownStatus := container.GetKnownStatus() if status > containerKnownStatus { // Event status is greater than container's known status. // This is not a backward transition, return return } if containerKnownStatus != api.ContainerStopped { // Container's known status is not STOPPED. Nothing to do here. return } if !status.IsRunning() { // Container's 'to' transition was not either of RUNNING or RESOURCES_PROVISIONED // states. Nothing to do in this case as well return } // If the container becomes running after we've stopped it (possibly // because we got an error running it and it ran anyways), the first time // update it to 'known running' so that it will be driven back to stopped mtask.unexpectedStart.Do(func() { seelog.Warnf("Managed task [%s]: stopped container [%s] came back; re-stopping it once", mtask.Arn, container.Name) go mtask.engine.transitionContainer(mtask.Task, container, api.ContainerStopped) // This will not proceed afterwards because status <= knownstatus below }) } // handleEventError handles a container change event error and decides whether // we should proceed to transition the container func (mtask *managedTask) handleEventError(containerChange dockerContainerChange, currentKnownStatus api.ContainerStatus) bool { container := containerChange.container event := containerChange.event if container.ApplyingError == nil { container.ApplyingError = api.NewNamedError(event.Error) } switch event.Status { // event.Status is the desired container transition from container's known status // (* -> event.Status) case api.ContainerPulled: // Container's desired transition was to 'PULLED'. A failure to pull might // not be fatal if e.g. the image already exists. seelog.Errorf("Managed task [%s]: Error while pulling container %s, will try to run anyway: %v", mtask.Arn, container.Name, event.Error) // proceed anyway return true case api.ContainerStopped: // Container's desired transition was to 'STOPPED' return mtask.handleContainerStoppedTransitionError(event, container, currentKnownStatus) case api.ContainerStatusNone: fallthrough case api.ContainerCreated: // No need to explicitly stop containers if this is a * -> NONE/CREATED transition seelog.Warnf("Managed task [%s]: Error creating container [%s]; marking its desired status as STOPPED: %v", mtask.Arn, container.Name, event.Error) container.SetKnownStatus(currentKnownStatus) container.SetDesiredStatus(api.ContainerStopped) return false default: // If this is a * -> RUNNING / RESOURCES_PROVISIONED transition, we need to stop // the container. seelog.Warnf("Managed task [%s]: Error starting/provisioning container[%s]; marking its desired status as STOPPED: %v", mtask.Arn, container.Name, event.Error) container.SetKnownStatus(currentKnownStatus) container.SetDesiredStatus(api.ContainerStopped) errorName := event.Error.ErrorName() if errorName == dockerTimeoutErrorName || errorName == cannotInspectContainerErrorName { // If there's an error with inspecting the container or in case of timeout error, // we'll also assume that the container has transitioned to RUNNING and issue // a stop. See #1043 for details seelog.Warnf("Managed task [%s]: Forcing container [%s] to stop", mtask.Arn, container.Name) go mtask.engine.transitionContainer(mtask.Task, container, api.ContainerStopped) } // Container known status not changed, no need for further processing return false } } // handleContainerStoppedTransitionError handles an error when transitioning a container to // STOPPED. It returns a boolean indicating whether the tak can continue with updating its // state func (mtask *managedTask) handleContainerStoppedTransitionError(event DockerContainerChangeEvent, container *api.Container, currentKnownStatus api.ContainerStatus) bool { // If we were trying to transition to stopped and had a timeout error // from docker, reset the known status to the current status and return // This ensures that we don't emit a containerstopped event; a // terminal container event from docker event stream will instead be // responsible for the transition. Alternatively, the steadyState check // could also trigger the progress and have another go at stopping the // container if event.Error.ErrorName() == dockerTimeoutErrorName { seelog.Infof("Managed task [%s]: '%s' error stopping container [%s]. Ignoring state change: %v", mtask.Arn, dockerTimeoutErrorName, container.Name, event.Error.Error()) container.SetKnownStatus(currentKnownStatus) return false } // If docker returned a transient error while trying to stop a container, // reset the known status to the current status and return cannotStopContainerError, ok := event.Error.(cannotStopContainerError) if ok && cannotStopContainerError.IsRetriableError() { seelog.Infof("Managed task [%s]: Error stopping the container [%s]. Ignoring state change: %v", mtask.Arn, container.Name, cannotStopContainerError.Error()) container.SetKnownStatus(currentKnownStatus) return false } // If we were trying to transition to stopped and had an error, we // clearly can't just continue trying to transition it to stopped // again and again. In this case, assume it's stopped (or close // enough) and get on with it // This can happen in cases where the container we tried to stop // was already stopped or did not exist at all. seelog.Warnf("Managed task [%s]: 'docker stop' for container [%s] returned %s: %s", mtask.Arn, container.Name, event.Error.ErrorName(), event.Error.Error()) container.SetKnownStatus(api.ContainerStopped) container.SetDesiredStatus(api.ContainerStopped) return true } // progressContainers tries to step forwards all containers that are able to be // transitioned in the task's current state. // It will continue listening to events from all channels while it does so, but // none of those changes will be acted upon until this set of requests to // docker completes. // Container changes may also prompt the task status to change as well. func (mtask *managedTask) progressContainers() { seelog.Debugf("Managed task [%s]: progressing containers in task", mtask.Arn) // max number of transitions length to ensure writes will never block on // these and if we exit early transitions can exit the goroutine and it'll // get GC'd eventually transitionChange := make(chan struct{}, len(mtask.Containers)) transitionChangeContainer := make(chan string, len(mtask.Containers)) anyCanTransition, transitions, reasons := mtask.startContainerTransitions( func(container *api.Container, nextStatus api.ContainerStatus) { mtask.engine.transitionContainer(mtask.Task, container, nextStatus) transitionChange <- struct{}{} transitionChangeContainer <- container.Name }) if !anyCanTransition { if !mtask.waitForExecutionCredentialsFromACS(reasons) { mtask.onContainersUnableToTransitionState() } return } // We've kicked off one or more transitions, wait for them to // complete, but keep reading events as we do. in fact, we have to for // transitions to complete mtask.waitForContainerTransitions(transitions, transitionChange, transitionChangeContainer) seelog.Debugf("Managed task [%s]: done transitioning all containers", mtask.Arn) // update the task status changed := mtask.UpdateStatus() if changed { seelog.Debugf("Managed task [%s]: container change also resulted in task change", mtask.Arn) // If knownStatus changed, let it be known mtask.emitTaskEvent(mtask.Task, "") } } // waitForExecutionCredentialsFromACS checks if the container that can't be transitioned // was caused by waiting for credentials and start waiting func (mtask *managedTask) waitForExecutionCredentialsFromACS(reasons []error) bool { for _, reason := range reasons { if reason == dependencygraph.CredentialsNotResolvedErr { seelog.Debugf("Managed task [%s]: waiting for credentials to pull from ECR", mtask.Arn) timeoutCtx, timeoutCancel := context.WithTimeout(mtask.ctx, waitForPullCredentialsTimeout) defer timeoutCancel() timedOut := mtask.waitEvent(timeoutCtx.Done()) if timedOut { seelog.Debugf("Managed task [%s]: timed out waiting for acs credentials message", mtask.Arn) } return true } } return false } // startContainerTransitions steps through each container in the task and calls // the passed transition function when a transition should occur. func (mtask *managedTask) startContainerTransitions(transitionFunc containerTransitionFunc) (bool, map[string]api.ContainerStatus, []error) { anyCanTransition := false var reasons []error transitions := make(map[string]api.ContainerStatus) for _, cont := range mtask.Containers { transition := mtask.containerNextState(cont) if transition.reason != nil { // container can't be transitioned reasons = append(reasons, transition.reason) continue } // At least one container is able to be moved forwards, so we're not deadlocked anyCanTransition = true if !transition.actionRequired { mtask.handleContainerChange(dockerContainerChange{ container: cont, event: DockerContainerChangeEvent{ Status: transition.nextState, }, }) continue } transitions[cont.Name] = transition.nextState go transitionFunc(cont, transition.nextState) } return anyCanTransition, transitions, reasons } type containerTransitionFunc func(container *api.Container, nextStatus api.ContainerStatus) // containerNextState determines the next state a container should go to. // It returns a transition struct including the information: // * container state it should transition to, // * a bool indicating whether any action is required // * an error indicating why this transition can't happen // // 'Stopped, false, ""' -> "You can move it to known stopped, but you don't have to call a transition function" // 'Running, true, ""' -> "You can move it to running and you need to call the transition function" // 'None, false, containerDependencyNotResolved' -> "This should not be moved; it has unresolved dependencies;" // // Next status is determined by whether the known and desired statuses are // equal, the next numerically greater (iota-wise) status, and whether // dependencies are fully resolved. func (mtask *managedTask) containerNextState(container *api.Container) *containerTransition { containerKnownStatus := container.GetKnownStatus() containerDesiredStatus := container.GetDesiredStatus() if containerKnownStatus == containerDesiredStatus { seelog.Debugf("Managed task [%s]: container [%s] at desired status: %s", mtask.Arn, container.Name, containerDesiredStatus.String()) return &containerTransition{ nextState: api.ContainerStatusNone, actionRequired: false, reason: dependencygraph.ContainerPastDesiredStatusErr, } } if containerKnownStatus > containerDesiredStatus { seelog.Debugf("Managed task [%s]: container [%s] has already transitioned beyond desired status(%s): %s", mtask.Arn, container.Name, containerKnownStatus.String(), containerDesiredStatus.String()) return &containerTransition{ nextState: api.ContainerStatusNone, actionRequired: false, reason: dependencygraph.ContainerPastDesiredStatusErr, } } if err := dependencygraph.DependenciesAreResolved(container, mtask.Containers, mtask.Task.GetExecutionCredentialsID(), mtask.credentialsManager); err != nil { seelog.Debugf("Managed task [%s]: can't apply state to container [%s] yet due to unresolved dependencies: %v", mtask.Arn, container.Name, err) return &containerTransition{ nextState: api.ContainerStatusNone, actionRequired: false, reason: err, } } var nextState api.ContainerStatus if container.DesiredTerminal() { nextState = api.ContainerStopped // It's not enough to just check if container is in steady state here // we should really check if >= RUNNING <= STOPPED if !container.IsRunning() { // If it's not currently running we do not need to do anything to make it become stopped. return &containerTransition{ nextState: nextState, actionRequired: false, } } } else { nextState = container.GetNextKnownStateProgression() } return &containerTransition{ nextState: nextState, actionRequired: true, } } func (mtask *managedTask) onContainersUnableToTransitionState() { seelog.Criticalf("Managed task [%s]: task in a bad state; it's not steadystate but no containers want to transition", mtask.Arn) if mtask.GetDesiredStatus().Terminal() { // Ack, really bad. We want it to stop but the containers don't think // that's possible. let's just break out and hope for the best! seelog.Criticalf("Managed task [%s]: The state is so bad that we're just giving up on it", mtask.Arn) mtask.SetKnownStatus(api.TaskStopped) mtask.emitTaskEvent(mtask.Task, taskUnableToTransitionToStoppedReason) // TODO we should probably panic here } else { seelog.Criticalf("Managed task [%s]: voving task to stopped due to bad state", mtask.Arn) mtask.handleDesiredStatusChange(api.TaskStopped, 0) } } func (mtask *managedTask) waitForContainerTransitions(transitions map[string]api.ContainerStatus, transitionChange <-chan struct{}, transitionChangeContainer <-chan string) { for len(transitions) > 0 { if mtask.waitEvent(transitionChange) { changedContainer := <-transitionChangeContainer seelog.Debugf("Managed task [%s]: transition for container[%s] finished", mtask.Arn, changedContainer) delete(transitions, changedContainer) seelog.Debugf("Managed task [%s]: still waiting for: %v", mtask.Arn, transitions) } if mtask.GetDesiredStatus().Terminal() || mtask.GetKnownStatus().Terminal() { allWaitingOnPulled := true for _, desired := range transitions { if desired != api.ContainerPulled { allWaitingOnPulled = false } } if allWaitingOnPulled { // We don't actually care to wait for 'pull' transitions to finish if // we're just heading to stopped since those resources aren't // inherently linked to this task anyways for e.g. gc and so on. seelog.Debugf("Managed task [%s]: all containers are waiting for pulled transition; exiting early: %v", mtask.Arn, transitions) break } } } } func (mtask *managedTask) time() ttime.Time { mtask._timeOnce.Do(func() { if mtask._time == nil { mtask._time = &ttime.DefaultTime{} } }) return mtask._time } func (mtask *managedTask) cleanupTask(taskStoppedDuration time.Duration) { cleanupTimeDuration := mtask.GetKnownStatusTime().Add(taskStoppedDuration).Sub(ttime.Now()) // There is a potential deadlock here if cleanupTime is negative. Ignore the computed // value in this case in favor of the default config value. if cleanupTimeDuration < 0 { seelog.Debugf("Managed task [%s]: Cleanup Duration is too short. Resetting to: %s", mtask.Arn, config.DefaultTaskCleanupWaitDuration.String()) cleanupTimeDuration = config.DefaultTaskCleanupWaitDuration } cleanupTime := mtask.time().After(cleanupTimeDuration) cleanupTimeBool := make(chan struct{}) go func() { <-cleanupTime cleanupTimeBool <- struct{}{} close(cleanupTimeBool) }() // wait for the cleanup time to elapse, signalled by cleanupTimeBool for !mtask.waitEvent(cleanupTimeBool) { } // wait for api.TaskStopped to be sent ok := mtask.waitForStopReported() if !ok { seelog.Errorf("Managed task [%s]: Aborting cleanup for task as it is not reported as stopped. SentStatus: %s", mtask.Arn, mtask.GetSentStatus().String()) return } seelog.Infof("Managed task [%s]: cleaning up task's containers and data", mtask.Arn) // For the duration of this, simply discard any task events; this ensures the // speedy processing of other events for other tasks handleCleanupDone := make(chan struct{}) // discard events while the task is being removed from engine state go mtask.discardEventsUntil(handleCleanupDone) mtask.engine.sweepTask(mtask.Task) mtask.engine.deleteTask(mtask.Task, handleCleanupDone) // Cleanup any leftover messages before closing their channels. No new // messages possible because we deleted ourselves from managedTasks, so this // removes all stale ones mtask.discardPendingMessages() close(mtask.dockerMessages) close(mtask.acsMessages) } func (mtask *managedTask) discardEventsUntil(done chan struct{}) { for { select { case <-mtask.dockerMessages: case <-mtask.acsMessages: case <-done: return } } } func (mtask *managedTask) discardPendingMessages() { for { select { case <-mtask.dockerMessages: case <-mtask.acsMessages: default: return } } } // waitForStopReported will wait for the task to be reported stopped and return true, or will time-out and return false. // Messages on the mtask.dockerMessages and mtask.acsMessages channels will be handled while this function is waiting. func (mtask *managedTask) waitForStopReported() bool { stoppedSentBool := make(chan struct{}) taskStopped := false go func() { for i := 0; i < _maxStoppedWaitTimes; i++ { // ensure that we block until api.TaskStopped is actually sent sentStatus := mtask.GetSentStatus() if sentStatus >= api.TaskStopped { taskStopped = true break } seelog.Warnf("Managed task [%s]: Blocking cleanup until the task has been reported stopped. SentStatus: %s (%d/%d)", mtask.Arn, sentStatus.String(), i+1, _maxStoppedWaitTimes) mtask._time.Sleep(_stoppedSentWaitInterval) } stoppedSentBool <- struct{}{} close(stoppedSentBool) }() // wait for api.TaskStopped to be sent for !mtask.waitEvent(stoppedSentBool) { } return taskStopped }
1
19,274
I don't think we need this line. You're logging in `waitForContainerTransition()` anyway
aws-amazon-ecs-agent
go
@@ -13,7 +13,7 @@ return [ 'accepted' => ':attribute ला स्वीकार केला गेला पाहिजे.', - 'accepted_if' => 'The :attribute must be accepted when :other is :value.', + 'accepted_if' => ':other हे :value असेल तेव्हा हे फील्ड स्वीकारणे आवश्यक आहे.', 'active_url' => ':attribute हा एक बरोबर URL नाही आहे.', 'after' => ':attribute, :date नंतरची एक तारीख पाहिजे.', 'after_or_equal' => ':attribute, :date हि किंवा त्या नंतरची एक तारीख पाहिजे.',
1
<?php /* |-------------------------------------------------------------------------- | Validation Language Lines |-------------------------------------------------------------------------- | | The following language lines contain the default error messages used by | the validator class. Some of these rules have multiple versions such | as the size rules. Feel free to tweak each of these messages here. | */ return [ 'accepted' => ':attribute ला स्वीकार केला गेला पाहिजे.', 'accepted_if' => 'The :attribute must be accepted when :other is :value.', 'active_url' => ':attribute हा एक बरोबर URL नाही आहे.', 'after' => ':attribute, :date नंतरची एक तारीख पाहिजे.', 'after_or_equal' => ':attribute, :date हि किंवा त्या नंतरची एक तारीख पाहिजे.', 'alpha' => ':attribute मध्ये फक्त अक्षरे वैध आहेत.', 'alpha_dash' => ':attribute मध्ये फक्त अक्षरे, संख्या आणि डॅश वैध आहेत.', 'alpha_num' => ':attribute मध्ये फक्त अक्षरे आणि संख्या वैध आहेत.', 'array' => ':attribute साठी फक्त सूची वैध आहे.', 'attached' => 'या :attribute आधीच संलग्न आहे.', 'before' => ':attribute, :date आधीची एक तारीख पाहिजे.', 'before_or_equal' => ':attribute, :date हि किंवा त्या आधीची एक तारीख पाहिजे.', 'between' => [ 'array' => ':attribute, :min किंवा :max संख्या यामध्ये असावी.', 'file' => ':attribute, :min किंवा :max किलोबाइट यामध्ये असावी.', 'numeric' => ':attribute, :min किंवा :max यामध्ये असावी.', 'string' => ':attribute, :min किंवा :max शब्द यामध्ये असावी.', ], 'boolean' => ':attribute फील्ड योग्य किंवा चुकीचे असावे.', 'confirmed' => ':attribute पुष्टीकरण जुळत नाही.', 'current_password' => 'The password is incorrect.', 'date' => ':attribute वैध तारीख नाही.', 'date_equals' => ':attribute, :date तारीख समान असणे आवश्यक आहे.', 'date_format' => ':attribute फॉर्मेट :format शी जुळत नाही.', 'different' => ':attribute आणि :other वेगळे असावे.', 'digits' => ':attribute, :digits अंक असणे आवश्यक आहे.', 'digits_between' => ':attribute, :min आणि :max अंक दरम्यान असणे आवश्यक आहे.', 'dimensions' => ':attribute अयोग्य माप आहे.', 'distinct' => ':attribute वेगवेगळे असावेत.', 'email' => ':attribute एक वैध ईमेल पत्ता असणे आवश्यक आहे.', 'ends_with' => 'द :attribute खालील एक समाप्त करणे आवश्यक आहे: :values.', 'exists' => 'निवडलेेलेे :attribute वैध नाही.', 'file' => ':attribute एक फ़ाइल असावी.', 'filled' => ':attribute फील्ड आवश्यक आहे.', 'gt' => [ 'array' => ':attribute, :value संख्या पेक्षा जास्त असावी.', 'file' => ':attribute, :value किलो बाईट पेक्षा जास्त असावी.', 'numeric' => ':attribute, :value पेक्षा जास्त असावी.', 'string' => ':attribute, :value characters पेक्षा जास्त असावी.', ], 'gte' => [ 'array' => ':attribute, :value संख्या पेक्षा मोठे किंवा समान असणे आवश्यक आहे.', 'file' => ':attribute, :value किलोबाईट पेक्षा मोठे किंवा समान असणे आवश्यक आहे.', 'numeric' => ':attribute, :value पेक्षा मोठे किंवा समान असणे आवश्यक आहे.', 'string' => ':attribute, :value शब्दांपेक्षा मोठे किंवा समान असणे आवश्यक आहे.', ], 'image' => ':attribute एक प्रतिमा असावी.', 'in' => ':attribute अमान्य आहे.', 'in_array' => ':attribute फील्ड, :other अस्तित्वात नाही.', 'integer' => ':attribute एक पूर्णांक असणे आवश्यक आहे.', 'ip' => ':attribute एक वैध IP address असावा.', 'ipv4' => ':attribute एक वैध IPv4 address असावा.', 'ipv6' => ':attribute एक वैध IPv6 address असावा.', 'json' => ':attribute एक वैध JSON स्ट्रिंग असावा.', 'lt' => [ 'array' => ':attribute, :value संख्या पेक्षा कमी असावी.', 'file' => ':attribute, :value किलो बाईट पेक्षा कमी असावी.', 'numeric' => ':attribute, :value पेक्षा कमी असावी.', 'string' => ':attribute, :value characters पेक्षा कमी असावी.', ], 'lte' => [ 'array' => ':attribute, :value संख्या पेक्षा कमी किंवा समान असणे आवश्यक आहे.', 'file' => ':attribute, :value किलोबाईट पेक्षा कमी किंवा समान असणे आवश्यक आहे.', 'numeric' => ':attribute, :value पेक्षा कमी किंवा समान असणे आवश्यक आहे.', 'string' => ':attribute, :value शब्दांपेक्षा कमी किंवा समान असणे आवश्यक आहे.', ], 'max' => [ 'array' => ':attribute, :value संख्या पेक्षा कमी असणे आवश्यक आहे.', 'file' => ':attribute, :value किलोबाईट पेक्षा कमी असणे आवश्यक आहे.', 'numeric' => ':attribute, :value पेक्षा कमी असणे आवश्यक आहे.', 'string' => ':attribute, :value शब्दांपेक्षा कमी असणे आवश्यक आहे.', ], 'mimes' => ':attribute एक प्रकार ची फ़ाइल: :values असावी.', 'mimetypes' => ':attribute एक प्रकार ची फ़ाइल: :values असावी.', 'min' => [ 'array' => ':attribute कमीत कमी :min आइटम असावी.', 'file' => ':attribute कमीत कमी :min किलोबाइट असावी.', 'numeric' => ':attribute कमीत कमी :min असावी.', 'string' => ':attribute कमीत कमी :min शब्द असावी.', ], 'multiple_of' => 'द :attribute अनेक असणे आवश्यक आहे :value', 'not_in' => 'घेतलेला :attribute वैध नाही.', 'not_regex' => ':attribute प्रारूप वैध नाही.', 'numeric' => ':attribute एक संख्या असावी.', 'password' => 'गुप्तशब्द अयोग्य आहे.', 'present' => ':attribute फील्ड उपस्थित असावी.', 'prohibited' => ':attribute फील्ड प्रतिबंधित आहे.', 'prohibited_if' => 'इ. स.:attribute फील्ड :other :value असते तेव्हा प्रतिबंधित आहे.', 'prohibited_unless' => 'अगोदर निर्देश केलेल्या बाबीसंबंधी बोलताना :attribute क्षेत्रात प्रतिबंधित आहे :other :values आहे तोपर्यंत.', 'regex' => ':attribute फॉर्मेट वैध नाही.', 'relatable' => 'या :attribute या संसाधन संबंधित जाऊ शकत नाही.', 'required' => ':attribute फील्ड आवश्यक आहे.', 'required_if' => 'जर :other :value असेल तर :attribute फ़ील्ड आवश्यक आहे.', 'required_unless' => 'जर :other :value नसेल तर :attribute फ़ील्ड आवश्यक आहे.', 'required_with' => ':values सोबत :attribute फ़ील्ड आवश्यक आहे.', 'required_with_all' => 'सर्व :values सोबत :attribute फ़ील्ड आवश्यक आहे.', 'required_without' => ':values खेरीज :attribute फ़ील्ड आवश्यक आहे.', 'required_without_all' => 'सर्व :values खेरीज :attribute फ़ील्ड आवश्यक आहे.', 'same' => ':attribute आणि :other सामान असावेत.', 'size' => [ 'array' => ':attribute में :size आइटम असावी.', 'file' => ':attribute, :size किलोबाइट असावी.', 'numeric' => ':attribute, :size असावी.', 'string' => ':attribute, :size शब्द असावी.', ], 'starts_with' => ':attribute खालीलपैकी कोणत्याही अक्षराने सुरूवात करावी: :values', 'string' => ':attribute एक वाक्य असावे.', 'timezone' => ':attribute एक वेळ क्षेत्र असावे.', 'unique' => ':attribute आधी वापरले गेले आहे.', 'uploaded' => ':attribute अपलोड करण्यात अयशस्वी.', 'url' => ':attribute फॉर्मेट अमान्य आहे.', 'uuid' => ':attribute एक वैध UUID असावी.', 'custom' => [ 'attribute-name' => [ 'rule-name' => 'नियम-संदेश', ], ], 'attributes' => [ 'image' => 'प्रतिमा', 'result_text_under_image' => 'प्रतिमेच्या खाली त्याचे परिणाम', 'short_text' => 'संक्षिप्त सारांश', 'test_description' => 'चाचणी चा सारांश.', 'test_locale' => 'भाषा', 'test_name' => 'चाचणी चे नाव.', ], ];
1
9,247
Shouldn't the `:attribute` placeholder appear?
Laravel-Lang-lang
php
@@ -78,8 +78,8 @@ public class ResidualEvaluator implements Serializable { private class ResidualVisitor extends ExpressionVisitors.BoundExpressionVisitor<Expression> { private StructLike struct; - private Expression eval(StructLike struct) { - this.struct = struct; + private Expression eval(StructLike arg) { + this.struct = arg; return ExpressionVisitors.visit(expr, this); }
1
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.iceberg.expressions; import java.io.Serializable; import java.util.Comparator; import org.apache.iceberg.PartitionField; import org.apache.iceberg.PartitionSpec; import org.apache.iceberg.StructLike; import org.apache.iceberg.transforms.Transform; /** * Finds the residuals for an {@link Expression} the partitions in the given {@link PartitionSpec}. * <p> * A residual expression is made by partially evaluating an expression using partition values. For * example, if a table is partitioned by day(utc_timestamp) and is read with a filter expression * utc_timestamp &gt;= a and utc_timestamp &lt;= b, then there are 4 possible residuals expressions * for the partition data, d: * <ul> * <li>If d &gt; day(a) and d &lt; day(b), the residual is always true</li> * <li>If d == day(a) and d != day(b), the residual is utc_timestamp &gt;= a</li> * <li>if d == day(b) and d != day(a), the residual is utc_timestamp &lt;= b</li> * <li>If d == day(a) == day(b), the residual is utc_timestamp &gt;= a and utc_timestamp &lt;= b * </li> * </ul> * <p> * Partition data is passed using {@link StructLike}. Residuals are returned by * {@link #residualFor(StructLike)}. * <p> * This class is thread-safe. */ public class ResidualEvaluator implements Serializable { private final PartitionSpec spec; private final Expression expr; private final boolean caseSensitive; private transient ThreadLocal<ResidualVisitor> visitors = null; private ResidualVisitor visitor() { if (visitors == null) { this.visitors = ThreadLocal.withInitial(ResidualVisitor::new); } return visitors.get(); } public ResidualEvaluator(PartitionSpec spec, Expression expr, boolean caseSensitive) { this.spec = spec; this.expr = expr; this.caseSensitive = caseSensitive; } /** * Returns a residual expression for the given partition values. * * @param partitionData partition data values * @return the residual of this evaluator's expression from the partition values */ public Expression residualFor(StructLike partitionData) { return visitor().eval(partitionData); } private class ResidualVisitor extends ExpressionVisitors.BoundExpressionVisitor<Expression> { private StructLike struct; private Expression eval(StructLike struct) { this.struct = struct; return ExpressionVisitors.visit(expr, this); } @Override public Expression alwaysTrue() { return Expressions.alwaysTrue(); } @Override public Expression alwaysFalse() { return Expressions.alwaysFalse(); } @Override public Expression not(Expression result) { return Expressions.not(result); } @Override public Expression and(Expression leftResult, Expression rightResult) { return Expressions.and(leftResult, rightResult); } @Override public Expression or(Expression leftResult, Expression rightResult) { return Expressions.or(leftResult, rightResult); } @Override public <T> Expression isNull(BoundReference<T> ref) { return (ref.get(struct) == null) ? alwaysTrue() : alwaysFalse(); } @Override public <T> Expression notNull(BoundReference<T> ref) { return (ref.get(struct) != null) ? alwaysTrue() : alwaysFalse(); } @Override public <T> Expression lt(BoundReference<T> ref, Literal<T> lit) { Comparator<T> cmp = lit.comparator(); return (cmp.compare(ref.get(struct), lit.value()) < 0) ? alwaysTrue() : alwaysFalse(); } @Override public <T> Expression ltEq(BoundReference<T> ref, Literal<T> lit) { Comparator<T> cmp = lit.comparator(); return (cmp.compare(ref.get(struct), lit.value()) <= 0) ? alwaysTrue() : alwaysFalse(); } @Override public <T> Expression gt(BoundReference<T> ref, Literal<T> lit) { Comparator<T> cmp = lit.comparator(); return (cmp.compare(ref.get(struct), lit.value()) > 0) ? alwaysTrue() : alwaysFalse(); } @Override public <T> Expression gtEq(BoundReference<T> ref, Literal<T> lit) { Comparator<T> cmp = lit.comparator(); return (cmp.compare(ref.get(struct), lit.value()) >= 0) ? alwaysTrue() : alwaysFalse(); } @Override public <T> Expression eq(BoundReference<T> ref, Literal<T> lit) { Comparator<T> cmp = lit.comparator(); return (cmp.compare(ref.get(struct), lit.value()) == 0) ? alwaysTrue() : alwaysFalse(); } @Override public <T> Expression notEq(BoundReference<T> ref, Literal<T> lit) { Comparator<T> cmp = lit.comparator(); return (cmp.compare(ref.get(struct), lit.value()) != 0) ? alwaysTrue() : alwaysFalse(); } @Override @SuppressWarnings("unchecked") public <T> Expression predicate(BoundPredicate<T> pred) { // Get the strict projection of this predicate in partition data, then use it to determine // whether to return the original predicate. The strict projection returns true iff the // original predicate would have returned true, so the predicate can be eliminated if the // strict projection evaluates to true. // // If there is no strict projection or if it evaluates to false, then return the predicate. PartitionField part = spec.getFieldBySourceId(pred.ref().fieldId()); if (part == null) { return pred; // not associated inclusive a partition field, can't be evaluated } UnboundPredicate<?> strictProjection = ((Transform<T, ?>) part.transform()) .projectStrict(part.name(), pred); if (strictProjection != null) { Expression bound = strictProjection.bind(spec.partitionType(), caseSensitive); if (bound instanceof BoundPredicate) { // the predicate methods will evaluate and return alwaysTrue or alwaysFalse return super.predicate((BoundPredicate<?>) bound); } return bound; // use the non-predicate residual (e.g. alwaysTrue) } // if the predicate could not be projected, it must be in the residual return pred; } @Override public <T> Expression predicate(UnboundPredicate<T> pred) { Expression bound = pred.bind(spec.schema().asStruct(), caseSensitive); if (bound instanceof BoundPredicate) { Expression boundResidual = predicate((BoundPredicate<?>) bound); if (boundResidual instanceof Predicate) { return pred; // replace inclusive original unbound predicate } return boundResidual; // use the non-predicate residual (e.g. alwaysTrue) } // if binding didn't result in a Predicate, return the expression return bound; } } }
1
13,106
Could you update this to `structLike` instead of `arg`?
apache-iceberg
java
@@ -0,0 +1,14 @@ +// +build darwin linux,!baremetal freebsd,!baremetal + +// +build gc.conservative gc.leaking + +package runtime + +const heapSize = 1 * 1024 * 1024 // 1MB to start + +var heapStart, heapEnd uintptr + +func preinit() { + heapStart = uintptr(malloc(heapSize)) + heapEnd = heapStart + heapSize +}
1
1
9,182
I only now spot this `freebsd,!baremetal` in the code, which doesn't make a lot of sense. The fact that there is `linux,!baremetal` is because baremetal targets pretend to be linux/arm to get the standard library to compile. Such a `!baremetal` exclusion is not necessary for FreeBSD. But this is not something that needs fixing in this PR.
tinygo-org-tinygo
go
@@ -455,7 +455,7 @@ get_unpacked_unlinked_content (OstreeRepo *repo, GError **error) { gboolean ret = FALSE; - g_autofree char *tmpname = g_strdup ("tmpostree-deltaobj-XXXXXX"); + g_autofree char *tmpname = g_strdup ("/var/tmp/tmpostree-deltaobj-XXXXXX"); glnx_fd_close int fd = -1; g_autoptr(GBytes) ret_content = NULL; g_autoptr(GInputStream) istream = NULL;
1
/* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- * * Copyright (C) 2013,2014 Colin Walters <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #include "config.h" #include <string.h> #include <stdlib.h> #include <gio/gunixoutputstream.h> #include <gio/gmemoryoutputstream.h> #include "ostree-core-private.h" #include "ostree-repo-private.h" #include "ostree-lzma-compressor.h" #include "ostree-repo-static-delta-private.h" #include "ostree-diff.h" #include "ostree-rollsum.h" #include "otutil.h" #include "ostree-varint.h" #include "bsdiff/bsdiff.h" #define CONTENT_SIZE_SIMILARITY_THRESHOLD_PERCENT (30) typedef struct { guint64 uncompressed_size; GPtrArray *objects; GString *payload; GString *operations; GHashTable *mode_set; /* GVariant(uuu) -> offset */ GPtrArray *modes; GHashTable *xattr_set; /* GVariant(ayay) -> offset */ GPtrArray *xattrs; } OstreeStaticDeltaPartBuilder; typedef struct { GPtrArray *parts; GPtrArray *fallback_objects; guint64 loose_compressed_size; guint64 min_fallback_size_bytes; guint64 max_bsdiff_size_bytes; guint64 max_chunk_size_bytes; guint64 rollsum_size; guint n_rollsum; guint n_bsdiff; guint n_fallback; gboolean swap_endian; } OstreeStaticDeltaBuilder; typedef enum { DELTAOPT_FLAG_NONE = (1 << 0), DELTAOPT_FLAG_DISABLE_BSDIFF = (1 << 1), DELTAOPT_FLAG_VERBOSE = (1 << 2) } DeltaOpts; static void ostree_static_delta_part_builder_unref (OstreeStaticDeltaPartBuilder *part_builder) { if (part_builder->objects) g_ptr_array_unref (part_builder->objects); if (part_builder->payload) g_string_free (part_builder->payload, TRUE); if (part_builder->operations) g_string_free (part_builder->operations, TRUE); g_hash_table_unref (part_builder->mode_set); g_ptr_array_unref (part_builder->modes); g_hash_table_unref (part_builder->xattr_set); g_ptr_array_unref (part_builder->xattrs); g_free (part_builder); } static guint mode_chunk_hash (const void *vp) { GVariant *v = (GVariant*)vp; guint uid, gid, mode; g_variant_get (v, "(uuu)", &uid, &gid, &mode); return uid + gid + mode; } static gboolean mode_chunk_equals (const void *one, const void *two) { GVariant *v1 = (GVariant*)one; GVariant *v2 = (GVariant*)two; guint uid1, gid1, mode1; guint uid2, gid2, mode2; g_variant_get (v1, "(uuu)", &uid1, &gid1, &mode1); g_variant_get (v2, "(uuu)", &uid2, &gid2, &mode2); return uid1 == uid2 && gid1 == gid2 && mode1 == mode2; } static guint bufhash (const void *b, gsize len) { const signed char *p, *e; guint32 h = 5381; for (p = (signed char *)b, e = (signed char *)b + len; p != e; p++) h = (h << 5) + h + *p; return h; } static guint xattr_chunk_hash (const void *vp) { GVariant *v = (GVariant*)vp; gsize n = g_variant_n_children (v); guint i; guint32 h = 5381; for (i = 0; i < n; i++) { const guint8* name; const guint8* value_data; GVariant *value = NULL; gsize value_len; g_variant_get_child (v, i, "(^&ay@ay)", &name, &value); value_data = g_variant_get_fixed_array (value, &value_len, 1); h += g_str_hash (name); h += bufhash (value_data, value_len); } return h; } static gboolean xattr_chunk_equals (const void *one, const void *two) { GVariant *v1 = (GVariant*)one; GVariant *v2 = (GVariant*)two; gsize l1 = g_variant_get_size (v1); gsize l2 = g_variant_get_size (v2); if (l1 != l2) return FALSE; return memcmp (g_variant_get_data (v1), g_variant_get_data (v2), l1) == 0; } static OstreeStaticDeltaPartBuilder * allocate_part (OstreeStaticDeltaBuilder *builder) { OstreeStaticDeltaPartBuilder *part = g_new0 (OstreeStaticDeltaPartBuilder, 1); part->objects = g_ptr_array_new_with_free_func ((GDestroyNotify)g_variant_unref); part->payload = g_string_new (NULL); part->operations = g_string_new (NULL); part->uncompressed_size = 0; part->mode_set = g_hash_table_new_full (mode_chunk_hash, mode_chunk_equals, (GDestroyNotify)g_variant_unref, NULL); part->modes = g_ptr_array_new (); part->xattr_set = g_hash_table_new_full (xattr_chunk_hash, xattr_chunk_equals, (GDestroyNotify)g_variant_unref, NULL); part->xattrs = g_ptr_array_new (); g_ptr_array_add (builder->parts, part); return part; } static gsize allocate_part_buffer_space (OstreeStaticDeltaPartBuilder *current_part, guint len) { gsize empty_space; gsize old_len; old_len = current_part->payload->len; empty_space = current_part->payload->allocated_len - current_part->payload->len; if (empty_space < len) { gsize origlen; origlen = current_part->payload->len; g_string_set_size (current_part->payload, current_part->payload->allocated_len + (len - empty_space)); current_part->payload->len = origlen; } return old_len; } static gsize write_unique_variant_chunk (OstreeStaticDeltaPartBuilder *current_part, GHashTable *hash, GPtrArray *ordered, GVariant *key) { gpointer target_offsetp; gsize offset; if (g_hash_table_lookup_extended (hash, key, NULL, &target_offsetp)) return GPOINTER_TO_UINT (target_offsetp); offset = ordered->len; target_offsetp = GUINT_TO_POINTER (offset); g_hash_table_insert (hash, g_variant_ref (key), target_offsetp); g_ptr_array_add (ordered, key); return offset; } static GBytes * objtype_checksum_array_new (GPtrArray *objects) { guint i; GByteArray *ret = g_byte_array_new (); for (i = 0; i < objects->len; i++) { GVariant *serialized_key = objects->pdata[i]; OstreeObjectType objtype; const char *checksum; guint8 csum[OSTREE_SHA256_DIGEST_LEN]; guint8 objtype_v; ostree_object_name_deserialize (serialized_key, &checksum, &objtype); objtype_v = (guint8) objtype; ostree_checksum_inplace_to_bytes (checksum, csum); g_byte_array_append (ret, &objtype_v, 1); g_byte_array_append (ret, csum, sizeof (csum)); } return g_byte_array_free_to_bytes (ret); } static gboolean splice_stream_to_payload (OstreeStaticDeltaPartBuilder *current_part, GInputStream *istream, GCancellable *cancellable, GError **error) { gboolean ret = FALSE; const guint readlen = 4096; gsize bytes_read; while (TRUE) { allocate_part_buffer_space (current_part, readlen); if (!g_input_stream_read_all (istream, current_part->payload->str + current_part->payload->len, readlen, &bytes_read, cancellable, error)) goto out; if (bytes_read == 0) break; current_part->payload->len += bytes_read; } ret = TRUE; out: return ret; } static void write_content_mode_xattrs (OstreeRepo *repo, OstreeStaticDeltaPartBuilder *current_part, GFileInfo *content_finfo, GVariant *content_xattrs, gsize *out_mode_offset, gsize *out_xattr_offset) { guint32 uid = g_file_info_get_attribute_uint32 (content_finfo, "unix::uid"); guint32 gid = g_file_info_get_attribute_uint32 (content_finfo, "unix::gid"); guint32 mode = g_file_info_get_attribute_uint32 (content_finfo, "unix::mode"); g_autoptr(GVariant) modev = g_variant_ref_sink (g_variant_new ("(uuu)", GUINT32_TO_BE (uid), GUINT32_TO_BE (gid), GUINT32_TO_BE (mode))); *out_mode_offset = write_unique_variant_chunk (current_part, current_part->mode_set, current_part->modes, modev); *out_xattr_offset = write_unique_variant_chunk (current_part, current_part->xattr_set, current_part->xattrs, content_xattrs); } static gboolean process_one_object (OstreeRepo *repo, OstreeStaticDeltaBuilder *builder, OstreeStaticDeltaPartBuilder **current_part_val, const char *checksum, OstreeObjectType objtype, GCancellable *cancellable, GError **error) { gboolean ret = FALSE; guint64 content_size; g_autoptr(GInputStream) content_stream = NULL; g_autoptr(GFileInfo) content_finfo = NULL; g_autoptr(GVariant) content_xattrs = NULL; guint64 compressed_size; OstreeStaticDeltaPartBuilder *current_part = *current_part_val; if (OSTREE_OBJECT_TYPE_IS_META (objtype)) { if (!ostree_repo_load_object_stream (repo, objtype, checksum, &content_stream, &content_size, cancellable, error)) goto out; } else { if (!ostree_repo_load_file (repo, checksum, &content_stream, &content_finfo, &content_xattrs, cancellable, error)) goto out; content_size = g_file_info_get_size (content_finfo); } /* Check to see if this delta is maximum size */ if (current_part->objects->len > 0 && current_part->payload->len + content_size > builder->max_chunk_size_bytes) { *current_part_val = current_part = allocate_part (builder); } if (!ostree_repo_query_object_storage_size (repo, objtype, checksum, &compressed_size, cancellable, error)) goto out; builder->loose_compressed_size += compressed_size; current_part->uncompressed_size += content_size; g_ptr_array_add (current_part->objects, ostree_object_name_serialize (checksum, objtype)); if (OSTREE_OBJECT_TYPE_IS_META (objtype)) { gsize object_payload_start; object_payload_start = current_part->payload->len; if (!splice_stream_to_payload (current_part, content_stream, cancellable, error)) goto out; g_string_append_c (current_part->operations, (gchar)OSTREE_STATIC_DELTA_OP_OPEN_SPLICE_AND_CLOSE); _ostree_write_varuint64 (current_part->operations, content_size); _ostree_write_varuint64 (current_part->operations, object_payload_start); } else { gsize mode_offset, xattr_offset, content_offset; guint32 mode; mode = g_file_info_get_attribute_uint32 (content_finfo, "unix::mode"); write_content_mode_xattrs (repo, current_part, content_finfo, content_xattrs, &mode_offset, &xattr_offset); if (S_ISLNK (mode)) { const char *target; g_assert (content_stream == NULL); target = g_file_info_get_symlink_target (content_finfo); content_stream = g_memory_input_stream_new_from_data (target, strlen (target), NULL); content_size = strlen (target); } else { g_assert (S_ISREG (mode)); } content_offset = current_part->payload->len; if (!splice_stream_to_payload (current_part, content_stream, cancellable, error)) goto out; g_string_append_c (current_part->operations, (gchar)OSTREE_STATIC_DELTA_OP_OPEN_SPLICE_AND_CLOSE); _ostree_write_varuint64 (current_part->operations, mode_offset); _ostree_write_varuint64 (current_part->operations, xattr_offset); _ostree_write_varuint64 (current_part->operations, content_size); _ostree_write_varuint64 (current_part->operations, content_offset); } ret = TRUE; out: return ret; } typedef struct { char *from_checksum; GBytes *tmp_from; GBytes *tmp_to; } ContentBsdiff; typedef struct { char *from_checksum; OstreeRollsumMatches *matches; GBytes *tmp_from; GBytes *tmp_to; } ContentRollsum; static void content_rollsums_free (ContentRollsum *rollsum) { g_free (rollsum->from_checksum); _ostree_rollsum_matches_free (rollsum->matches); g_bytes_unref (rollsum->tmp_from); g_bytes_unref (rollsum->tmp_to); g_free (rollsum); } static void content_bsdiffs_free (ContentBsdiff *bsdiff) { g_free (bsdiff->from_checksum); g_bytes_unref (bsdiff->tmp_from); g_bytes_unref (bsdiff->tmp_to); g_free (bsdiff); } /* Load a content object, uncompressing it to an unlinked tmpfile that's mmap()'d and suitable for seeking. */ static gboolean get_unpacked_unlinked_content (OstreeRepo *repo, const char *checksum, GBytes **out_content, GFileInfo **out_finfo, GCancellable *cancellable, GError **error) { gboolean ret = FALSE; g_autofree char *tmpname = g_strdup ("tmpostree-deltaobj-XXXXXX"); glnx_fd_close int fd = -1; g_autoptr(GBytes) ret_content = NULL; g_autoptr(GInputStream) istream = NULL; g_autoptr(GFileInfo) ret_finfo = NULL; g_autoptr(GOutputStream) out = NULL; fd = g_mkstemp (tmpname); if (fd == -1) { glnx_set_error_from_errno (error); goto out; } /* Doesn't need a name */ (void) unlink (tmpname); if (!ostree_repo_load_file (repo, checksum, &istream, &ret_finfo, NULL, cancellable, error)) goto out; g_assert (g_file_info_get_file_type (ret_finfo) == G_FILE_TYPE_REGULAR); out = g_unix_output_stream_new (fd, FALSE); if (g_output_stream_splice (out, istream, G_OUTPUT_STREAM_SPLICE_CLOSE_TARGET, cancellable, error) < 0) goto out; { GMappedFile *mfile = g_mapped_file_new_from_fd (fd, FALSE, error); ret_content = g_mapped_file_get_bytes (mfile); g_mapped_file_unref (mfile); } ret = TRUE; if (out_content) *out_content = g_steal_pointer (&ret_content); out: return ret; } static gboolean try_content_bsdiff (OstreeRepo *repo, const char *from, const char *to, ContentBsdiff **out_bsdiff, guint64 max_bsdiff_size_bytes, GCancellable *cancellable, GError **error) { gboolean ret = FALSE; g_autoptr(GHashTable) from_bsdiff = NULL; g_autoptr(GHashTable) to_bsdiff = NULL; g_autoptr(GBytes) tmp_from = NULL; g_autoptr(GBytes) tmp_to = NULL; g_autoptr(GFileInfo) from_finfo = NULL; g_autoptr(GFileInfo) to_finfo = NULL; ContentBsdiff *ret_bsdiff = NULL; *out_bsdiff = NULL; if (!get_unpacked_unlinked_content (repo, from, &tmp_from, &from_finfo, cancellable, error)) goto out; if (!get_unpacked_unlinked_content (repo, to, &tmp_to, &to_finfo, cancellable, error)) goto out; if (g_bytes_get_size (tmp_to) + g_bytes_get_size (tmp_from) > max_bsdiff_size_bytes) { ret = TRUE; goto out; } ret_bsdiff = g_new0 (ContentBsdiff, 1); ret_bsdiff->from_checksum = g_strdup (from); ret_bsdiff->tmp_from = tmp_from; tmp_from = NULL; ret_bsdiff->tmp_to = tmp_to; tmp_to = NULL; ret = TRUE; if (out_bsdiff) *out_bsdiff = g_steal_pointer (&ret_bsdiff); out: return ret; } static gboolean try_content_rollsum (OstreeRepo *repo, DeltaOpts opts, const char *from, const char *to, ContentRollsum **out_rollsum, GCancellable *cancellable, GError **error) { gboolean ret = FALSE; g_autoptr(GHashTable) from_rollsum = NULL; g_autoptr(GHashTable) to_rollsum = NULL; g_autoptr(GBytes) tmp_from = NULL; g_autoptr(GBytes) tmp_to = NULL; g_autoptr(GFileInfo) from_finfo = NULL; g_autoptr(GFileInfo) to_finfo = NULL; OstreeRollsumMatches *matches = NULL; ContentRollsum *ret_rollsum = NULL; *out_rollsum = NULL; /* Load the content objects, splice them to uncompressed temporary files that * we can just mmap() and seek around in conveniently. */ if (!get_unpacked_unlinked_content (repo, from, &tmp_from, &from_finfo, cancellable, error)) goto out; if (!get_unpacked_unlinked_content (repo, to, &tmp_to, &to_finfo, cancellable, error)) goto out; matches = _ostree_compute_rollsum_matches (tmp_from, tmp_to); { guint match_ratio = (matches->bufmatches*100)/matches->total; /* Only proceed if the file contains (arbitrary) more than 50% of * the previous chunks. */ if (match_ratio < 50) { ret = TRUE; goto out; } } if (opts & DELTAOPT_FLAG_VERBOSE) { g_printerr ("rollsum for %s; crcs=%u bufs=%u total=%u matchsize=%llu\n", to, matches->crcmatches, matches->bufmatches, matches->total, (unsigned long long)matches->match_size); } ret_rollsum = g_new0 (ContentRollsum, 1); ret_rollsum->from_checksum = g_strdup (from); ret_rollsum->matches = matches; matches = NULL; ret_rollsum->tmp_from = tmp_from; tmp_from = NULL; ret_rollsum->tmp_to = tmp_to; tmp_to = NULL; ret = TRUE; if (out_rollsum) *out_rollsum = g_steal_pointer (&ret_rollsum); out: if (matches) _ostree_rollsum_matches_free (matches); return ret; } struct bzdiff_opaque_s { GOutputStream *out; GCancellable *cancellable; GError **error; }; static int bzdiff_write (struct bsdiff_stream* stream, const void* buffer, int size) { struct bzdiff_opaque_s *op = stream->opaque; if (!g_output_stream_write (op->out, buffer, size, op->cancellable, op->error)) return -1; return 0; } static void append_payload_chunk_and_write (OstreeStaticDeltaPartBuilder *current_part, const guint8 *buf, guint64 offset) { guint64 payload_start; payload_start = current_part->payload->len; g_string_append_len (current_part->payload, (char*)buf, offset); g_string_append_c (current_part->operations, (gchar)OSTREE_STATIC_DELTA_OP_WRITE); _ostree_write_varuint64 (current_part->operations, offset); _ostree_write_varuint64 (current_part->operations, payload_start); } static gboolean process_one_rollsum (OstreeRepo *repo, OstreeStaticDeltaBuilder *builder, OstreeStaticDeltaPartBuilder **current_part_val, const char *to_checksum, ContentRollsum *rollsum, GCancellable *cancellable, GError **error) { gboolean ret = FALSE; guint64 content_size; g_autoptr(GInputStream) content_stream = NULL; g_autoptr(GFileInfo) content_finfo = NULL; g_autoptr(GVariant) content_xattrs = NULL; OstreeStaticDeltaPartBuilder *current_part = *current_part_val; const guint8 *tmp_to_buf; gsize tmp_to_len; /* Check to see if this delta has gone over maximum size */ if (current_part->objects->len > 0 && current_part->payload->len > builder->max_chunk_size_bytes) { *current_part_val = current_part = allocate_part (builder); } tmp_to_buf = g_bytes_get_data (rollsum->tmp_to, &tmp_to_len); if (!ostree_repo_load_file (repo, to_checksum, &content_stream, &content_finfo, &content_xattrs, cancellable, error)) goto out; content_size = g_file_info_get_size (content_finfo); g_assert_cmpint (tmp_to_len, ==, content_size); current_part->uncompressed_size += content_size; g_ptr_array_add (current_part->objects, ostree_object_name_serialize (to_checksum, OSTREE_OBJECT_TYPE_FILE)); { gsize mode_offset, xattr_offset, from_csum_offset; gboolean reading_payload = TRUE; guchar source_csum[OSTREE_SHA256_DIGEST_LEN]; guint i; write_content_mode_xattrs (repo, current_part, content_finfo, content_xattrs, &mode_offset, &xattr_offset); /* Write the origin checksum */ ostree_checksum_inplace_to_bytes (rollsum->from_checksum, source_csum); from_csum_offset = current_part->payload->len; g_string_append_len (current_part->payload, (char*)source_csum, sizeof (source_csum)); g_string_append_c (current_part->operations, (gchar)OSTREE_STATIC_DELTA_OP_OPEN); _ostree_write_varuint64 (current_part->operations, mode_offset); _ostree_write_varuint64 (current_part->operations, xattr_offset); _ostree_write_varuint64 (current_part->operations, content_size); { guint64 writing_offset = 0; guint64 offset = 0, to_start = 0, from_start = 0; GPtrArray *matchlist = rollsum->matches->matches; g_assert (matchlist->len > 0); for (i = 0; i < matchlist->len; i++) { GVariant *match = matchlist->pdata[i]; guint32 crc; guint64 prefix; g_variant_get (match, "(uttt)", &crc, &offset, &to_start, &from_start); prefix = to_start - writing_offset; if (prefix > 0) { if (!reading_payload) { g_string_append_c (current_part->operations, (gchar)OSTREE_STATIC_DELTA_OP_UNSET_READ_SOURCE); reading_payload = TRUE; } g_assert_cmpint (writing_offset + prefix, <=, tmp_to_len); append_payload_chunk_and_write (current_part, tmp_to_buf + writing_offset, prefix); writing_offset += prefix; } if (reading_payload) { g_string_append_c (current_part->operations, (gchar)OSTREE_STATIC_DELTA_OP_SET_READ_SOURCE); _ostree_write_varuint64 (current_part->operations, from_csum_offset); reading_payload = FALSE; } g_string_append_c (current_part->operations, (gchar)OSTREE_STATIC_DELTA_OP_WRITE); _ostree_write_varuint64 (current_part->operations, offset); _ostree_write_varuint64 (current_part->operations, from_start); writing_offset += offset; } if (!reading_payload) g_string_append_c (current_part->operations, (gchar)OSTREE_STATIC_DELTA_OP_UNSET_READ_SOURCE); { guint64 remainder = tmp_to_len - writing_offset; if (remainder > 0) append_payload_chunk_and_write (current_part, tmp_to_buf + writing_offset, remainder); writing_offset += remainder; g_assert_cmpint (writing_offset, ==, tmp_to_len); } g_assert_cmpint (writing_offset, ==, content_size); } g_string_append_c (current_part->operations, (gchar)OSTREE_STATIC_DELTA_OP_CLOSE); } ret = TRUE; out: return ret; } static gboolean process_one_bsdiff (OstreeRepo *repo, OstreeStaticDeltaBuilder *builder, OstreeStaticDeltaPartBuilder **current_part_val, const char *to_checksum, ContentBsdiff *bsdiff_content, GCancellable *cancellable, GError **error) { gboolean ret = FALSE; guint64 content_size; g_autoptr(GInputStream) content_stream = NULL; g_autoptr(GFileInfo) content_finfo = NULL; g_autoptr(GVariant) content_xattrs = NULL; OstreeStaticDeltaPartBuilder *current_part = *current_part_val; const guint8 *tmp_to_buf; gsize tmp_to_len; const guint8 *tmp_from_buf; gsize tmp_from_len; /* Check to see if this delta has gone over maximum size */ if (current_part->objects->len > 0 && current_part->payload->len > builder->max_chunk_size_bytes) { *current_part_val = current_part = allocate_part (builder); } tmp_to_buf = g_bytes_get_data (bsdiff_content->tmp_to, &tmp_to_len); tmp_from_buf = g_bytes_get_data (bsdiff_content->tmp_from, &tmp_from_len); if (!ostree_repo_load_file (repo, to_checksum, &content_stream, &content_finfo, &content_xattrs, cancellable, error)) goto out; content_size = g_file_info_get_size (content_finfo); g_assert_cmpint (tmp_to_len, ==, content_size); current_part->uncompressed_size += content_size; g_ptr_array_add (current_part->objects, ostree_object_name_serialize (to_checksum, OSTREE_OBJECT_TYPE_FILE)); { gsize mode_offset, xattr_offset; guchar source_csum[OSTREE_SHA256_DIGEST_LEN]; write_content_mode_xattrs (repo, current_part, content_finfo, content_xattrs, &mode_offset, &xattr_offset); /* Write the origin checksum */ ostree_checksum_inplace_to_bytes (bsdiff_content->from_checksum, source_csum); g_string_append_c (current_part->operations, (gchar)OSTREE_STATIC_DELTA_OP_SET_READ_SOURCE); _ostree_write_varuint64 (current_part->operations, current_part->payload->len); g_string_append_len (current_part->payload, (char*)source_csum, sizeof (source_csum)); g_string_append_c (current_part->operations, (gchar)OSTREE_STATIC_DELTA_OP_OPEN); _ostree_write_varuint64 (current_part->operations, mode_offset); _ostree_write_varuint64 (current_part->operations, xattr_offset); _ostree_write_varuint64 (current_part->operations, content_size); { struct bsdiff_stream stream; struct bzdiff_opaque_s op; const gchar *payload; gssize payload_size; g_autoptr(GOutputStream) out = g_memory_output_stream_new_resizable (); stream.malloc = malloc; stream.free = free; stream.write = bzdiff_write; op.out = out; op.cancellable = cancellable; op.error = error; stream.opaque = &op; if (bsdiff (tmp_from_buf, tmp_from_len, tmp_to_buf, tmp_to_len, &stream) < 0) { g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED, "bsdiff generation failed"); goto out; } payload = g_memory_output_stream_get_data (G_MEMORY_OUTPUT_STREAM (out)); payload_size = g_memory_output_stream_get_data_size (G_MEMORY_OUTPUT_STREAM (out)); g_string_append_c (current_part->operations, (gchar)OSTREE_STATIC_DELTA_OP_BSPATCH); _ostree_write_varuint64 (current_part->operations, current_part->payload->len); _ostree_write_varuint64 (current_part->operations, payload_size); g_string_append_len (current_part->payload, payload, payload_size); } g_string_append_c (current_part->operations, (gchar)OSTREE_STATIC_DELTA_OP_CLOSE); } g_string_append_c (current_part->operations, (gchar)OSTREE_STATIC_DELTA_OP_UNSET_READ_SOURCE); ret = TRUE; out: return ret; } static gboolean generate_delta_lowlatency (OstreeRepo *repo, const char *from, const char *to, DeltaOpts opts, OstreeStaticDeltaBuilder *builder, GCancellable *cancellable, GError **error) { gboolean ret = FALSE; GHashTableIter hashiter; gpointer key, value; OstreeStaticDeltaPartBuilder *current_part = NULL; g_autoptr(GFile) root_from = NULL; g_autoptr(GVariant) from_commit = NULL; g_autoptr(GFile) root_to = NULL; g_autoptr(GVariant) to_commit = NULL; g_autoptr(GHashTable) to_reachable_objects = NULL; g_autoptr(GHashTable) from_reachable_objects = NULL; g_autoptr(GHashTable) from_regfile_content = NULL; g_autoptr(GHashTable) new_reachable_metadata = NULL; g_autoptr(GHashTable) new_reachable_regfile_content = NULL; g_autoptr(GHashTable) new_reachable_symlink_content = NULL; g_autoptr(GHashTable) modified_regfile_content = NULL; g_autoptr(GHashTable) rollsum_optimized_content_objects = NULL; g_autoptr(GHashTable) bsdiff_optimized_content_objects = NULL; g_autoptr(GHashTable) content_object_to_size = NULL; if (from != NULL) { if (!ostree_repo_read_commit (repo, from, &root_from, NULL, cancellable, error)) goto out; if (!ostree_repo_load_variant (repo, OSTREE_OBJECT_TYPE_COMMIT, from, &from_commit, error)) goto out; if (!ostree_repo_traverse_commit (repo, from, 0, &from_reachable_objects, cancellable, error)) goto out; } if (!ostree_repo_read_commit (repo, to, &root_to, NULL, cancellable, error)) goto out; if (!ostree_repo_load_variant (repo, OSTREE_OBJECT_TYPE_COMMIT, to, &to_commit, error)) goto out; if (!ostree_repo_traverse_commit (repo, to, 0, &to_reachable_objects, cancellable, error)) goto out; new_reachable_metadata = ostree_repo_traverse_new_reachable (); new_reachable_regfile_content = g_hash_table_new_full (g_str_hash, g_str_equal, NULL, g_free); new_reachable_symlink_content = g_hash_table_new_full (g_str_hash, g_str_equal, NULL, g_free); g_hash_table_iter_init (&hashiter, to_reachable_objects); while (g_hash_table_iter_next (&hashiter, &key, &value)) { GVariant *serialized_key = key; const char *checksum; OstreeObjectType objtype; if (from_reachable_objects && g_hash_table_contains (from_reachable_objects, serialized_key)) continue; ostree_object_name_deserialize (serialized_key, &checksum, &objtype); g_variant_ref (serialized_key); if (OSTREE_OBJECT_TYPE_IS_META (objtype)) g_hash_table_add (new_reachable_metadata, serialized_key); else { g_autoptr(GFileInfo) finfo = NULL; GFileType ftype; if (!ostree_repo_load_file (repo, checksum, NULL, &finfo, NULL, cancellable, error)) goto out; ftype = g_file_info_get_file_type (finfo); if (ftype == G_FILE_TYPE_REGULAR) g_hash_table_add (new_reachable_regfile_content, g_strdup (checksum)); else if (ftype == G_FILE_TYPE_SYMBOLIC_LINK) g_hash_table_add (new_reachable_symlink_content, g_strdup (checksum)); else g_assert_not_reached (); } } if (from_commit) { if (!_ostree_delta_compute_similar_objects (repo, from_commit, to_commit, new_reachable_regfile_content, CONTENT_SIZE_SIMILARITY_THRESHOLD_PERCENT, &modified_regfile_content, cancellable, error)) goto out; } else modified_regfile_content = g_hash_table_new (g_str_hash, g_str_equal); if (opts & DELTAOPT_FLAG_VERBOSE) { g_printerr ("modified: %u\n", g_hash_table_size (modified_regfile_content)); g_printerr ("new reachable: metadata=%u content regular=%u symlink=%u\n", g_hash_table_size (new_reachable_metadata), g_hash_table_size (new_reachable_regfile_content), g_hash_table_size (new_reachable_symlink_content)); } /* We already ship the to commit in the superblock, don't ship it twice */ g_hash_table_remove (new_reachable_metadata, ostree_object_name_serialize (to, OSTREE_OBJECT_TYPE_COMMIT)); rollsum_optimized_content_objects = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, (GDestroyNotify) content_rollsums_free); bsdiff_optimized_content_objects = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, (GDestroyNotify) content_bsdiffs_free); g_hash_table_iter_init (&hashiter, modified_regfile_content); while (g_hash_table_iter_next (&hashiter, &key, &value)) { const char *to_checksum = key; const char *from_checksum = value; ContentRollsum *rollsum; ContentBsdiff *bsdiff; if (!try_content_rollsum (repo, opts, from_checksum, to_checksum, &rollsum, cancellable, error)) goto out; if (rollsum) { g_hash_table_insert (rollsum_optimized_content_objects, g_strdup (to_checksum), rollsum); builder->rollsum_size += rollsum->matches->match_size; continue; } if (!(opts & DELTAOPT_FLAG_DISABLE_BSDIFF)) { if (!try_content_bsdiff (repo, from_checksum, to_checksum, &bsdiff, builder->max_bsdiff_size_bytes, cancellable, error)) goto out; if (bsdiff) g_hash_table_insert (bsdiff_optimized_content_objects, g_strdup (to_checksum), bsdiff); } } if (opts & DELTAOPT_FLAG_VERBOSE) { g_printerr ("rollsum for %u/%u modified\n", g_hash_table_size (rollsum_optimized_content_objects), g_hash_table_size (modified_regfile_content)); } current_part = allocate_part (builder); /* Pack the metadata first */ g_hash_table_iter_init (&hashiter, new_reachable_metadata); while (g_hash_table_iter_next (&hashiter, &key, &value)) { GVariant *serialized_key = key; const char *checksum; OstreeObjectType objtype; ostree_object_name_deserialize (serialized_key, &checksum, &objtype); if (!process_one_object (repo, builder, &current_part, checksum, objtype, cancellable, error)) goto out; } /* Now do rollsummed objects */ g_hash_table_iter_init (&hashiter, rollsum_optimized_content_objects); while (g_hash_table_iter_next (&hashiter, &key, &value)) { const char *checksum = key; ContentRollsum *rollsum = value; if (!process_one_rollsum (repo, builder, &current_part, checksum, rollsum, cancellable, error)) goto out; builder->n_rollsum++; } /* Now do bsdiff'ed objects */ g_hash_table_iter_init (&hashiter, bsdiff_optimized_content_objects); while (g_hash_table_iter_next (&hashiter, &key, &value)) { const char *checksum = key; ContentBsdiff *bsdiff = value; if (!process_one_bsdiff (repo, builder, &current_part, checksum, bsdiff, cancellable, error)) goto out; builder->n_bsdiff++; } /* Scan for large objects, so we can fall back to plain HTTP-based * fetch. */ g_hash_table_iter_init (&hashiter, new_reachable_regfile_content); while (g_hash_table_iter_next (&hashiter, &key, &value)) { const char *checksum = key; guint64 uncompressed_size; gboolean fallback = FALSE; /* Skip content objects we rollsum'd or bsdiff'ed */ if (g_hash_table_contains (rollsum_optimized_content_objects, checksum) || g_hash_table_contains (bsdiff_optimized_content_objects, checksum)) continue; if (!ostree_repo_load_object_stream (repo, OSTREE_OBJECT_TYPE_FILE, checksum, NULL, &uncompressed_size, cancellable, error)) goto out; if (builder->min_fallback_size_bytes > 0 && uncompressed_size > builder->min_fallback_size_bytes) fallback = TRUE; if (fallback) { g_autofree char *size = g_format_size (uncompressed_size); if (opts & DELTAOPT_FLAG_VERBOSE) g_printerr ("fallback for %s (%s)\n", checksum, size); g_ptr_array_add (builder->fallback_objects, ostree_object_name_serialize (checksum, OSTREE_OBJECT_TYPE_FILE)); g_hash_table_iter_remove (&hashiter); builder->n_fallback++; } } /* Now non-rollsummed or bsdiff'ed regular file content */ g_hash_table_iter_init (&hashiter, new_reachable_regfile_content); while (g_hash_table_iter_next (&hashiter, &key, &value)) { const char *checksum = key; /* Skip content objects we rollsum'd */ if (g_hash_table_contains (rollsum_optimized_content_objects, checksum) || g_hash_table_contains (bsdiff_optimized_content_objects, checksum)) continue; if (!process_one_object (repo, builder, &current_part, checksum, OSTREE_OBJECT_TYPE_FILE, cancellable, error)) goto out; } /* Now symlinks */ g_hash_table_iter_init (&hashiter, new_reachable_symlink_content); while (g_hash_table_iter_next (&hashiter, &key, &value)) { const char *checksum = key; if (!process_one_object (repo, builder, &current_part, checksum, OSTREE_OBJECT_TYPE_FILE, cancellable, error)) goto out; } ret = TRUE; out: return ret; } static gboolean get_fallback_headers (OstreeRepo *self, OstreeStaticDeltaBuilder *builder, GVariant **out_headers, GCancellable *cancellable, GError **error) { gboolean ret = FALSE; guint i; g_autoptr(GVariant) ret_headers = NULL; g_autoptr(GVariantBuilder) fallback_builder = NULL; fallback_builder = g_variant_builder_new (G_VARIANT_TYPE ("a" OSTREE_STATIC_DELTA_FALLBACK_FORMAT)); for (i = 0; i < builder->fallback_objects->len; i++) { GVariant *serialized = builder->fallback_objects->pdata[i]; const char *checksum; OstreeObjectType objtype; guint64 compressed_size; guint64 uncompressed_size; ostree_object_name_deserialize (serialized, &checksum, &objtype); if (OSTREE_OBJECT_TYPE_IS_META (objtype)) { if (!ostree_repo_load_object_stream (self, objtype, checksum, NULL, &uncompressed_size, cancellable, error)) goto out; compressed_size = uncompressed_size; } else { g_autoptr(GFileInfo) file_info = NULL; if (!ostree_repo_query_object_storage_size (self, OSTREE_OBJECT_TYPE_FILE, checksum, &compressed_size, cancellable, error)) goto out; if (!ostree_repo_load_file (self, checksum, NULL, &file_info, NULL, cancellable, error)) goto out; uncompressed_size = g_file_info_get_size (file_info); } g_variant_builder_add_value (fallback_builder, g_variant_new ("(y@aytt)", objtype, ostree_checksum_to_bytes_v (checksum), maybe_swap_endian_u64 (builder->swap_endian, compressed_size), maybe_swap_endian_u64 (builder->swap_endian, uncompressed_size))); } ret_headers = g_variant_ref_sink (g_variant_builder_end (fallback_builder)); ret = TRUE; if (out_headers) *out_headers = g_steal_pointer (&ret_headers); out: return ret; } /** * ostree_repo_static_delta_generate: * @self: Repo * @opt: High level optimization choice * @from: ASCII SHA256 checksum of origin, or %NULL * @to: ASCII SHA256 checksum of target * @metadata: (allow-none): Optional metadata * @params: (allow-none): Parameters, see below * @cancellable: Cancellable * @error: Error * * Generate a lookaside "static delta" from @from (%NULL means * from-empty) which can generate the objects in @to. This delta is * an optimization over fetching individual objects, and can be * conveniently stored and applied offline. * * The @params argument should be an a{sv}. The following attributes * are known: * - min-fallback-size: u: Minimume uncompressed size in megabytes to use fallback, 0 to disable fallbacks * - max-chunk-size: u: Maximum size in megabytes of a delta part * - max-bsdiff-size: u: Maximum size in megabytes to consider bsdiff compression * for input files * - compression: y: Compression type: 0=none, x=lzma, g=gzip * - bsdiff-enabled: b: Enable bsdiff compression. Default TRUE. * - inline-parts: b: Put part data in header, to get a single file delta. Default FALSE. * - verbose: b: Print diagnostic messages. Default FALSE. * - endianness: b: Deltas use host byte order by default; this option allows choosing (G_BIG_ENDIAN or G_LITTLE_ENDIAN) * - filename: ay: Save delta superblock to this filename, and parts in the same directory. Default saves to repository. */ gboolean ostree_repo_static_delta_generate (OstreeRepo *self, OstreeStaticDeltaGenerateOpt opt, const char *from, const char *to, GVariant *metadata, GVariant *params, GCancellable *cancellable, GError **error) { gboolean ret = FALSE; OstreeStaticDeltaBuilder builder = { 0, }; guint i; guint min_fallback_size; guint max_bsdiff_size; guint max_chunk_size; GVariantBuilder metadata_builder; DeltaOpts delta_opts = DELTAOPT_FLAG_NONE; guint64 total_compressed_size = 0; guint64 total_uncompressed_size = 0; g_autoptr(GVariantBuilder) part_headers = NULL; g_autoptr(GPtrArray) part_tempfiles = NULL; g_autoptr(GVariant) delta_descriptor = NULL; g_autoptr(GVariant) to_commit = NULL; const char *opt_filename; g_autofree char *descriptor_relpath = NULL; g_autoptr(GFile) descriptor_path = NULL; g_autoptr(GFile) descriptor_dir = NULL; g_autoptr(GVariant) tmp_metadata = NULL; g_autoptr(GVariant) fallback_headers = NULL; g_autoptr(GVariant) detached = NULL; gboolean inline_parts; guint endianness = G_BYTE_ORDER; g_autoptr(GFile) tmp_dir = NULL; builder.parts = g_ptr_array_new_with_free_func ((GDestroyNotify)ostree_static_delta_part_builder_unref); builder.fallback_objects = g_ptr_array_new_with_free_func ((GDestroyNotify)g_variant_unref); if (!g_variant_lookup (params, "min-fallback-size", "u", &min_fallback_size)) min_fallback_size = 4; builder.min_fallback_size_bytes = ((guint64)min_fallback_size) * 1000 * 1000; if (!g_variant_lookup (params, "max-bsdiff-size", "u", &max_bsdiff_size)) max_bsdiff_size = 128; builder.max_bsdiff_size_bytes = ((guint64)max_bsdiff_size) * 1000 * 1000; if (!g_variant_lookup (params, "max-chunk-size", "u", &max_chunk_size)) max_chunk_size = 32; builder.max_chunk_size_bytes = ((guint64)max_chunk_size) * 1000 * 1000; (void) g_variant_lookup (params, "endianness", "u", &endianness); g_return_val_if_fail (endianness == G_BIG_ENDIAN || endianness == G_LITTLE_ENDIAN, FALSE); builder.swap_endian = endianness != G_BYTE_ORDER; { gboolean use_bsdiff; if (!g_variant_lookup (params, "bsdiff-enabled", "b", &use_bsdiff)) use_bsdiff = TRUE; if (!use_bsdiff) delta_opts |= DELTAOPT_FLAG_DISABLE_BSDIFF; } { gboolean verbose; if (!g_variant_lookup (params, "verbose", "b", &verbose)) verbose = FALSE; if (verbose) delta_opts |= DELTAOPT_FLAG_VERBOSE; } if (!g_variant_lookup (params, "inline-parts", "b", &inline_parts)) inline_parts = FALSE; if (!g_variant_lookup (params, "filename", "^&ay", &opt_filename)) opt_filename = NULL; if (!ostree_repo_load_variant (self, OSTREE_OBJECT_TYPE_COMMIT, to, &to_commit, error)) goto out; /* Ignore optimization flags */ if (!generate_delta_lowlatency (self, from, to, delta_opts, &builder, cancellable, error)) goto out; /* NOTE: Add user-supplied metadata first. This is used by at least * xdg-app as a way to provide MIME content sniffing, since the * metadata appears first in the file. */ g_variant_builder_init (&metadata_builder, G_VARIANT_TYPE ("a{sv}")); if (metadata != NULL) { GVariantIter iter; GVariant *item; g_variant_iter_init (&iter, metadata); while ((item = g_variant_iter_next_value (&iter))) { g_variant_builder_add (&metadata_builder, "@{sv}", item); g_variant_unref (item); } } { guint8 endianness_char; switch (endianness) { case G_LITTLE_ENDIAN: endianness_char = 'l'; break; case G_BIG_ENDIAN: endianness_char = 'B'; break; default: g_assert_not_reached (); } g_variant_builder_add (&metadata_builder, "{sv}", "ostree.endianness", g_variant_new_byte (endianness_char)); } if (opt_filename) { g_autoptr(GFile) f = g_file_new_for_path (opt_filename); tmp_dir = g_file_get_parent (f); } else { tmp_dir = g_object_ref (self->tmp_dir); } part_headers = g_variant_builder_new (G_VARIANT_TYPE ("a" OSTREE_STATIC_DELTA_META_ENTRY_FORMAT)); part_tempfiles = g_ptr_array_new_with_free_func (g_object_unref); for (i = 0; i < builder.parts->len; i++) { OstreeStaticDeltaPartBuilder *part_builder = builder.parts->pdata[i]; GBytes *payload_b; GBytes *operations_b; g_autofree guchar *part_checksum = NULL; g_autoptr(GChecksum) checksum = NULL; g_autoptr(GBytes) objtype_checksum_array = NULL; g_autoptr(GBytes) checksum_bytes = NULL; g_autoptr(GFile) part_tempfile = NULL; g_autoptr(GOutputStream) part_temp_outstream = NULL; g_autoptr(GInputStream) part_in = NULL; g_autoptr(GInputStream) part_payload_in = NULL; g_autoptr(GMemoryOutputStream) part_payload_out = NULL; g_autoptr(GConverterOutputStream) part_payload_compressor = NULL; g_autoptr(GConverter) compressor = NULL; g_autoptr(GVariant) delta_part_content = NULL; g_autoptr(GVariant) delta_part = NULL; g_autoptr(GVariant) delta_part_header = NULL; GVariantBuilder *mode_builder = g_variant_builder_new (G_VARIANT_TYPE ("a(uuu)")); GVariantBuilder *xattr_builder = g_variant_builder_new (G_VARIANT_TYPE ("aa(ayay)")); guint8 compression_type_char; { guint j; for (j = 0; j < part_builder->modes->len; j++) g_variant_builder_add_value (mode_builder, part_builder->modes->pdata[j]); for (j = 0; j < part_builder->xattrs->len; j++) g_variant_builder_add_value (xattr_builder, part_builder->xattrs->pdata[j]); } payload_b = g_string_free_to_bytes (part_builder->payload); part_builder->payload = NULL; operations_b = g_string_free_to_bytes (part_builder->operations); part_builder->operations = NULL; /* FIXME - avoid duplicating memory here */ delta_part_content = g_variant_new ("(a(uuu)aa(ayay)@ay@ay)", mode_builder, xattr_builder, ot_gvariant_new_ay_bytes (payload_b), ot_gvariant_new_ay_bytes (operations_b)); g_variant_ref_sink (delta_part_content); /* Hardcode xz for now */ compressor = (GConverter*)_ostree_lzma_compressor_new (NULL); compression_type_char = 'x'; part_payload_in = ot_variant_read (delta_part_content); part_payload_out = (GMemoryOutputStream*)g_memory_output_stream_new (NULL, 0, g_realloc, g_free); part_payload_compressor = (GConverterOutputStream*)g_converter_output_stream_new ((GOutputStream*)part_payload_out, compressor); { gssize n_bytes_written = g_output_stream_splice ((GOutputStream*)part_payload_compressor, part_payload_in, G_OUTPUT_STREAM_SPLICE_CLOSE_TARGET | G_OUTPUT_STREAM_SPLICE_CLOSE_SOURCE, cancellable, error); if (n_bytes_written < 0) goto out; } /* FIXME - avoid duplicating memory here */ delta_part = g_variant_new ("(y@ay)", compression_type_char, ot_gvariant_new_ay_bytes (g_memory_output_stream_steal_as_bytes (part_payload_out))); g_variant_ref_sink (delta_part); if (inline_parts) { g_autofree char *part_relpath = _ostree_get_relative_static_delta_part_path (from, to, i); g_variant_builder_add (&metadata_builder, "{sv}", part_relpath, delta_part); } else if (!gs_file_open_in_tmpdir (tmp_dir, 0644, &part_tempfile, &part_temp_outstream, cancellable, error)) goto out; part_in = ot_variant_read (delta_part); if (!ot_gio_splice_get_checksum (part_temp_outstream, part_in, &part_checksum, cancellable, error)) goto out; checksum_bytes = g_bytes_new (part_checksum, OSTREE_SHA256_DIGEST_LEN); objtype_checksum_array = objtype_checksum_array_new (part_builder->objects); delta_part_header = g_variant_new ("(u@aytt@ay)", maybe_swap_endian_u32 (builder.swap_endian, OSTREE_DELTAPART_VERSION), ot_gvariant_new_ay_bytes (checksum_bytes), maybe_swap_endian_u64 (builder.swap_endian, (guint64) g_variant_get_size (delta_part)), maybe_swap_endian_u64 (builder.swap_endian, part_builder->uncompressed_size), ot_gvariant_new_ay_bytes (objtype_checksum_array)); g_variant_builder_add_value (part_headers, g_variant_ref (delta_part_header)); if (part_tempfile) g_ptr_array_add (part_tempfiles, g_object_ref (part_tempfile)); total_compressed_size += g_variant_get_size (delta_part); total_uncompressed_size += part_builder->uncompressed_size; if (delta_opts & DELTAOPT_FLAG_VERBOSE) { g_printerr ("part %u n:%u compressed:%" G_GUINT64_FORMAT " uncompressed:%" G_GUINT64_FORMAT "\n", i, part_builder->objects->len, (guint64)g_variant_get_size (delta_part), part_builder->uncompressed_size); } } if (opt_filename) { descriptor_path = g_file_new_for_path (opt_filename); } else { descriptor_relpath = _ostree_get_relative_static_delta_superblock_path (from, to); descriptor_path = g_file_resolve_relative_path (self->repodir, descriptor_relpath); } descriptor_dir = g_file_get_parent (descriptor_path); if (!gs_file_ensure_directory (descriptor_dir, TRUE, cancellable, error)) goto out; for (i = 0; i < part_tempfiles->len; i++) { GFile *tempfile = part_tempfiles->pdata[i]; g_autofree char *partstr = g_strdup_printf ("%u", i); g_autoptr(GFile) part_path = g_file_resolve_relative_path (descriptor_dir, partstr); if (!gs_file_rename (tempfile, part_path, cancellable, error)) goto out; } if (!get_fallback_headers (self, &builder, &fallback_headers, cancellable, error)) goto out; if (!ostree_repo_read_commit_detached_metadata (self, to, &detached, cancellable, error)) goto out; if (detached) { g_autofree char *detached_key = _ostree_get_relative_static_delta_path (from, to, "commitmeta"); g_variant_builder_add (&metadata_builder, "{sv}", detached_key, detached); } /* Generate OSTREE_STATIC_DELTA_SUPERBLOCK_FORMAT */ { GDateTime *now = g_date_time_new_now_utc (); /* floating */ GVariant *from_csum_v = from ? ostree_checksum_to_bytes_v (from) : ot_gvariant_new_bytearray ((guchar *)"", 0); /* floating */ GVariant *to_csum_v = ostree_checksum_to_bytes_v (to); delta_descriptor = g_variant_new ("(@a{sv}t@ay@ay@" OSTREE_COMMIT_GVARIANT_STRING "ay" "a" OSTREE_STATIC_DELTA_META_ENTRY_FORMAT "@a" OSTREE_STATIC_DELTA_FALLBACK_FORMAT ")", g_variant_builder_end (&metadata_builder), GUINT64_TO_BE (g_date_time_to_unix (now)), from_csum_v, to_csum_v, to_commit, g_variant_builder_new (G_VARIANT_TYPE ("ay")), part_headers, fallback_headers); g_date_time_unref (now); } if (delta_opts & DELTAOPT_FLAG_VERBOSE) { g_printerr ("uncompressed=%" G_GUINT64_FORMAT " compressed=%" G_GUINT64_FORMAT " loose=%" G_GUINT64_FORMAT "\n", total_uncompressed_size, total_compressed_size, builder.loose_compressed_size); g_printerr ("rollsum=%u objects, %" G_GUINT64_FORMAT " bytes\n", builder.n_rollsum, builder.rollsum_size); g_printerr ("bsdiff=%u objects\n", builder.n_bsdiff); } if (!ot_util_variant_save (descriptor_path, delta_descriptor, cancellable, error)) goto out; ret = TRUE; out: g_clear_pointer (&builder.parts, g_ptr_array_unref); g_clear_pointer (&builder.fallback_objects, g_ptr_array_unref); return ret; }
1
7,289
Ugh, we were using cwd? =(
ostreedev-ostree
c
@@ -21,7 +21,6 @@ struct screencopy_damage { struct pixman_region32 damage; struct wl_listener output_precommit; struct wl_listener output_destroy; - uint32_t last_commit_seq; }; static const struct zwlr_screencopy_frame_v1_interface frame_impl;
1
#include <assert.h> #include <stdlib.h> #include <drm_fourcc.h> #include <wlr/render/wlr_renderer.h> #include <wlr/types/wlr_matrix.h> #include <wlr/types/wlr_output.h> #include <wlr/types/wlr_linux_dmabuf_v1.h> #include <wlr/types/wlr_screencopy_v1.h> #include <wlr/backend.h> #include <wlr/util/box.h> #include <wlr/util/log.h> #include "wlr-screencopy-unstable-v1-protocol.h" #include "render/pixel_format.h" #include "util/signal.h" #define SCREENCOPY_MANAGER_VERSION 3 struct screencopy_damage { struct wl_list link; struct wlr_output *output; struct pixman_region32 damage; struct wl_listener output_precommit; struct wl_listener output_destroy; uint32_t last_commit_seq; }; static const struct zwlr_screencopy_frame_v1_interface frame_impl; static struct screencopy_damage *screencopy_damage_find( struct wlr_screencopy_v1_client *client, struct wlr_output *output) { struct screencopy_damage *damage; wl_list_for_each(damage, &client->damages, link) { if (damage->output == output) { return damage; } } return NULL; } static void screencopy_damage_accumulate(struct screencopy_damage *damage) { struct pixman_region32 *region = &damage->damage; struct wlr_output *output = damage->output; /* This check is done so damage that has been added and cleared in the * frame precommit handler is not added again after it has been handled. */ if (damage->last_commit_seq == output->commit_seq) { return; } if (output->pending.committed & WLR_OUTPUT_STATE_DAMAGE) { // If the compositor submitted damage, copy it over pixman_region32_union(region, region, &output->pending.damage); pixman_region32_intersect_rect(region, region, 0, 0, output->width, output->height); } else if (output->pending.committed & WLR_OUTPUT_STATE_BUFFER) { // If the compositor did not submit damage but did submit a buffer // damage everything pixman_region32_union_rect(region, region, 0, 0, output->width, output->height); } damage->last_commit_seq = output->commit_seq; } static void screencopy_damage_handle_output_precommit( struct wl_listener *listener, void *data) { struct screencopy_damage *damage = wl_container_of(listener, damage, output_precommit); screencopy_damage_accumulate(damage); } static void screencopy_damage_destroy(struct screencopy_damage *damage) { wl_list_remove(&damage->output_destroy.link); wl_list_remove(&damage->output_precommit.link); wl_list_remove(&damage->link); pixman_region32_fini(&damage->damage); free(damage); } static void screencopy_damage_handle_output_destroy( struct wl_listener *listener, void *data) { struct screencopy_damage *damage = wl_container_of(listener, damage, output_destroy); screencopy_damage_destroy(damage); } static struct screencopy_damage *screencopy_damage_create( struct wlr_screencopy_v1_client *client, struct wlr_output *output) { struct screencopy_damage *damage = calloc(1, sizeof(struct screencopy_damage)); if (!damage) { return NULL; } damage->output = output; damage->last_commit_seq = output->commit_seq - 1; pixman_region32_init_rect(&damage->damage, 0, 0, output->width, output->height); wl_list_insert(&client->damages, &damage->link); wl_signal_add(&output->events.precommit, &damage->output_precommit); damage->output_precommit.notify = screencopy_damage_handle_output_precommit; wl_signal_add(&output->events.destroy, &damage->output_destroy); damage->output_destroy.notify = screencopy_damage_handle_output_destroy; return damage; } static struct screencopy_damage *screencopy_damage_get_or_create( struct wlr_screencopy_v1_client *client, struct wlr_output *output) { struct screencopy_damage *damage = screencopy_damage_find(client, output); return damage ? damage : screencopy_damage_create(client, output); } static void client_unref(struct wlr_screencopy_v1_client *client) { assert(client->ref > 0); if (--client->ref != 0) { return; } struct screencopy_damage *damage, *tmp_damage; wl_list_for_each_safe(damage, tmp_damage, &client->damages, link) { screencopy_damage_destroy(damage); } free(client); } static struct wlr_screencopy_frame_v1 *frame_from_resource( struct wl_resource *resource) { assert(wl_resource_instance_of(resource, &zwlr_screencopy_frame_v1_interface, &frame_impl)); return wl_resource_get_user_data(resource); } static void frame_destroy(struct wlr_screencopy_frame_v1 *frame) { if (frame == NULL) { return; } if (frame->output != NULL && (frame->shm_buffer != NULL || frame->dma_buffer != NULL)) { wlr_output_lock_attach_render(frame->output, false); if (frame->cursor_locked) { wlr_output_lock_software_cursors(frame->output, false); } } wl_list_remove(&frame->link); wl_list_remove(&frame->output_precommit.link); wl_list_remove(&frame->output_commit.link); wl_list_remove(&frame->output_destroy.link); wl_list_remove(&frame->output_enable.link); wl_list_remove(&frame->buffer_destroy.link); // Make the frame resource inert wl_resource_set_user_data(frame->resource, NULL); client_unref(frame->client); free(frame); } static void frame_send_damage(struct wlr_screencopy_frame_v1 *frame) { if (!frame->with_damage) { return; } struct screencopy_damage *damage = screencopy_damage_get_or_create(frame->client, frame->output); if (damage == NULL) { return; } // TODO: send fine-grained damage events struct pixman_box32 *damage_box = pixman_region32_extents(&damage->damage); int damage_x = damage_box->x1; int damage_y = damage_box->y1; int damage_width = damage_box->x2 - damage_box->x1; int damage_height = damage_box->y2 - damage_box->y1; zwlr_screencopy_frame_v1_send_damage(frame->resource, damage_x, damage_y, damage_width, damage_height); pixman_region32_clear(&damage->damage); } static void frame_send_ready(struct wlr_screencopy_frame_v1 *frame, struct timespec *when) { time_t tv_sec = when->tv_sec; uint32_t tv_sec_hi = (sizeof(tv_sec) > 4) ? tv_sec >> 32 : 0; uint32_t tv_sec_lo = tv_sec & 0xFFFFFFFF; zwlr_screencopy_frame_v1_send_ready(frame->resource, tv_sec_hi, tv_sec_lo, when->tv_nsec); } static void frame_handle_output_precommit(struct wl_listener *listener, void *_data) { struct wlr_screencopy_frame_v1 *frame = wl_container_of(listener, frame, output_precommit); struct wlr_output_event_precommit *event = _data; struct wlr_output *output = frame->output; struct wlr_renderer *renderer = wlr_backend_get_renderer(output->backend); assert(renderer); if (!(output->pending.committed & WLR_OUTPUT_STATE_BUFFER)) { return; } struct wl_shm_buffer *shm_buffer = frame->shm_buffer; if (shm_buffer == NULL) { return; } if (frame->with_damage) { struct screencopy_damage *damage = screencopy_damage_get_or_create(frame->client, output); if (damage) { screencopy_damage_accumulate(damage); if (!pixman_region32_not_empty(&damage->damage)) { return; } } } wl_list_remove(&frame->output_precommit.link); wl_list_init(&frame->output_precommit.link); int x = frame->box.x; int y = frame->box.y; enum wl_shm_format wl_shm_format = wl_shm_buffer_get_format(shm_buffer); uint32_t drm_format = convert_wl_shm_format_to_drm(wl_shm_format); int32_t width = wl_shm_buffer_get_width(shm_buffer); int32_t height = wl_shm_buffer_get_height(shm_buffer); int32_t stride = wl_shm_buffer_get_stride(shm_buffer); wl_shm_buffer_begin_access(shm_buffer); void *data = wl_shm_buffer_get_data(shm_buffer); uint32_t renderer_flags = 0; bool ok = wlr_renderer_read_pixels(renderer, drm_format, &renderer_flags, stride, width, height, x, y, 0, 0, data); uint32_t flags = renderer_flags & WLR_RENDERER_READ_PIXELS_Y_INVERT ? ZWLR_SCREENCOPY_FRAME_V1_FLAGS_Y_INVERT : 0; wl_shm_buffer_end_access(shm_buffer); if (!ok) { wlr_log(WLR_ERROR, "Failed to read pixels from renderer"); zwlr_screencopy_frame_v1_send_failed(frame->resource); frame_destroy(frame); return; } zwlr_screencopy_frame_v1_send_flags(frame->resource, flags); frame_send_damage(frame); frame_send_ready(frame, event->when); frame_destroy(frame); } static bool blit_dmabuf(struct wlr_renderer *renderer, struct wlr_dmabuf_v1_buffer *dst_dmabuf, struct wlr_dmabuf_attributes *src_attrs) { struct wlr_buffer *dst_buffer = wlr_buffer_lock(&dst_dmabuf->base); struct wlr_texture *src_tex = wlr_texture_from_dmabuf(renderer, src_attrs); if (src_tex == NULL) { goto error_src_tex; } float mat[9]; wlr_matrix_identity(mat); wlr_matrix_scale(mat, dst_buffer->width, dst_buffer->height); if (!wlr_renderer_begin_with_buffer(renderer, dst_buffer)) { goto error_renderer_begin; } wlr_renderer_clear(renderer, (float[]){ 0.0, 0.0, 0.0, 0.0 }); wlr_render_texture_with_matrix(renderer, src_tex, mat, 1.0f); wlr_renderer_end(renderer); wlr_texture_destroy(src_tex); wlr_buffer_unlock(dst_buffer); return true; error_renderer_begin: wlr_texture_destroy(src_tex); error_src_tex: wlr_buffer_unlock(dst_buffer); return false; } static void frame_handle_output_commit(struct wl_listener *listener, void *data) { struct wlr_screencopy_frame_v1 *frame = wl_container_of(listener, frame, output_commit); struct wlr_output_event_commit *event = data; struct wlr_output *output = frame->output; struct wlr_renderer *renderer = wlr_backend_get_renderer(output->backend); assert(renderer); if (!(event->committed & WLR_OUTPUT_STATE_BUFFER)) { return; } struct wlr_dmabuf_v1_buffer *dma_buffer = frame->dma_buffer; if (dma_buffer == NULL) { return; } if (frame->with_damage) { struct screencopy_damage *damage = screencopy_damage_get_or_create(frame->client, output); if (damage && !pixman_region32_not_empty(&damage->damage)) { return; } } wl_list_remove(&frame->output_commit.link); wl_list_init(&frame->output_commit.link); // TODO: add support for copying regions with DMA-BUFs if (frame->box.x != 0 || frame->box.y != 0 || output->width != frame->box.width || output->height != frame->box.height) { zwlr_screencopy_frame_v1_send_failed(frame->resource); frame_destroy(frame); return; } struct wlr_dmabuf_attributes attr = { 0 }; bool ok = wlr_output_export_dmabuf(output, &attr); ok = ok && blit_dmabuf(renderer, dma_buffer, &attr); uint32_t flags = dma_buffer->attributes.flags & WLR_DMABUF_ATTRIBUTES_FLAGS_Y_INVERT ? ZWLR_SCREENCOPY_FRAME_V1_FLAGS_Y_INVERT : 0; wlr_dmabuf_attributes_finish(&attr); if (!ok) { zwlr_screencopy_frame_v1_send_failed(frame->resource); frame_destroy(frame); return; } zwlr_screencopy_frame_v1_send_flags(frame->resource, flags); frame_send_damage(frame); frame_send_ready(frame, event->when); frame_destroy(frame); } static void frame_handle_output_enable(struct wl_listener *listener, void *data) { struct wlr_screencopy_frame_v1 *frame = wl_container_of(listener, frame, output_enable); if (!frame->output->enabled) { zwlr_screencopy_frame_v1_send_failed(frame->resource); frame_destroy(frame); } } static void frame_handle_output_destroy(struct wl_listener *listener, void *data) { struct wlr_screencopy_frame_v1 *frame = wl_container_of(listener, frame, output_destroy); zwlr_screencopy_frame_v1_send_failed(frame->resource); frame_destroy(frame); } static void frame_handle_buffer_destroy(struct wl_listener *listener, void *data) { struct wlr_screencopy_frame_v1 *frame = wl_container_of(listener, frame, buffer_destroy); zwlr_screencopy_frame_v1_send_failed(frame->resource); frame_destroy(frame); } static void frame_handle_copy(struct wl_client *wl_client, struct wl_resource *frame_resource, struct wl_resource *buffer_resource) { struct wlr_screencopy_frame_v1 *frame = frame_from_resource(frame_resource); if (frame == NULL) { return; } struct wlr_output *output = frame->output; if (!output->enabled) { zwlr_screencopy_frame_v1_send_failed(frame->resource); frame_destroy(frame); return; } struct wlr_dmabuf_v1_buffer *dma_buffer = NULL; struct wl_shm_buffer *shm_buffer = wl_shm_buffer_get(buffer_resource); if (shm_buffer == NULL && wlr_dmabuf_v1_resource_is_buffer(buffer_resource)) { dma_buffer = wlr_dmabuf_v1_buffer_from_buffer_resource(buffer_resource); } if (shm_buffer == NULL && dma_buffer == NULL) { wl_resource_post_error(frame->resource, ZWLR_SCREENCOPY_FRAME_V1_ERROR_INVALID_BUFFER, "unsupported buffer type"); return; } int32_t width = 0; int32_t height = 0; if (shm_buffer) { enum wl_shm_format fmt = wl_shm_buffer_get_format(shm_buffer); if (fmt != frame->format) { wl_resource_post_error(frame->resource, ZWLR_SCREENCOPY_FRAME_V1_ERROR_INVALID_BUFFER, "invalid buffer format"); return; } int32_t stride = wl_shm_buffer_get_stride(shm_buffer); if (stride != frame->stride) { wl_resource_post_error(frame->resource, ZWLR_SCREENCOPY_FRAME_V1_ERROR_INVALID_BUFFER, "invalid buffer stride"); return; } width = wl_shm_buffer_get_width(shm_buffer); height = wl_shm_buffer_get_height(shm_buffer); } else if (dma_buffer) { uint32_t fourcc = dma_buffer->attributes.format; if (fourcc != frame->fourcc) { wl_resource_post_error(frame->resource, ZWLR_SCREENCOPY_FRAME_V1_ERROR_INVALID_BUFFER, "invalid buffer format"); return; } width = dma_buffer->attributes.width; height = dma_buffer->attributes.height; } else { abort(); } if (width != frame->box.width || height != frame->box.height) { wl_resource_post_error(frame->resource, ZWLR_SCREENCOPY_FRAME_V1_ERROR_INVALID_BUFFER, "invalid buffer dimensions"); return; } if (!wl_list_empty(&frame->output_precommit.link) || frame->shm_buffer != NULL || frame->dma_buffer != NULL) { wl_resource_post_error(frame->resource, ZWLR_SCREENCOPY_FRAME_V1_ERROR_ALREADY_USED, "frame already used"); return; } frame->shm_buffer = shm_buffer; frame->dma_buffer = dma_buffer; wl_signal_add(&output->events.precommit, &frame->output_precommit); frame->output_precommit.notify = frame_handle_output_precommit; wl_signal_add(&output->events.commit, &frame->output_commit); frame->output_commit.notify = frame_handle_output_commit; wl_signal_add(&output->events.destroy, &frame->output_enable); frame->output_enable.notify = frame_handle_output_enable; wl_signal_add(&output->events.destroy, &frame->output_destroy); frame->output_destroy.notify = frame_handle_output_destroy; wl_resource_add_destroy_listener(buffer_resource, &frame->buffer_destroy); frame->buffer_destroy.notify = frame_handle_buffer_destroy; // Schedule a buffer commit wlr_output_schedule_frame(output); wlr_output_lock_attach_render(output, true); if (frame->overlay_cursor) { wlr_output_lock_software_cursors(output, true); frame->cursor_locked = true; } } static void frame_handle_copy_with_damage(struct wl_client *wl_client, struct wl_resource *frame_resource, struct wl_resource *buffer_resource) { struct wlr_screencopy_frame_v1 *frame = frame_from_resource(frame_resource); if (frame == NULL) { return; } frame->with_damage = true; frame_handle_copy(wl_client, frame_resource, buffer_resource); } static void frame_handle_destroy(struct wl_client *wl_client, struct wl_resource *frame_resource) { wl_resource_destroy(frame_resource); } static const struct zwlr_screencopy_frame_v1_interface frame_impl = { .copy = frame_handle_copy, .destroy = frame_handle_destroy, .copy_with_damage = frame_handle_copy_with_damage, }; static void frame_handle_resource_destroy(struct wl_resource *frame_resource) { struct wlr_screencopy_frame_v1 *frame = frame_from_resource(frame_resource); frame_destroy(frame); } static const struct zwlr_screencopy_manager_v1_interface manager_impl; static struct wlr_screencopy_v1_client *client_from_resource( struct wl_resource *resource) { assert(wl_resource_instance_of(resource, &zwlr_screencopy_manager_v1_interface, &manager_impl)); return wl_resource_get_user_data(resource); } static uint32_t get_output_fourcc(struct wlr_output *output) { struct wlr_dmabuf_attributes attr = { 0 }; if (!wlr_output_export_dmabuf(output, &attr)) { return DRM_FORMAT_INVALID; } uint32_t format = attr.format; wlr_dmabuf_attributes_finish(&attr); return format; } static void capture_output(struct wl_client *wl_client, struct wlr_screencopy_v1_client *client, uint32_t version, uint32_t id, int32_t overlay_cursor, struct wlr_output *output, const struct wlr_box *box) { struct wlr_screencopy_frame_v1 *frame = calloc(1, sizeof(struct wlr_screencopy_frame_v1)); if (frame == NULL) { wl_client_post_no_memory(wl_client); return; } frame->output = output; frame->overlay_cursor = !!overlay_cursor; frame->resource = wl_resource_create(wl_client, &zwlr_screencopy_frame_v1_interface, version, id); if (frame->resource == NULL) { free(frame); wl_client_post_no_memory(wl_client); return; } wl_resource_set_implementation(frame->resource, &frame_impl, frame, frame_handle_resource_destroy); if (output == NULL) { wl_resource_set_user_data(frame->resource, NULL); zwlr_screencopy_frame_v1_send_failed(frame->resource); free(frame); return; } frame->client = client; client->ref++; wl_list_insert(&client->manager->frames, &frame->link); wl_list_init(&frame->output_precommit.link); wl_list_init(&frame->output_commit.link); wl_list_init(&frame->output_enable.link); wl_list_init(&frame->output_destroy.link); wl_list_init(&frame->buffer_destroy.link); if (output == NULL || !output->enabled) { goto error; } struct wlr_renderer *renderer = wlr_backend_get_renderer(output->backend); assert(renderer); uint32_t drm_format = wlr_output_preferred_read_format(frame->output); if (drm_format == DRM_FORMAT_INVALID) { wlr_log(WLR_ERROR, "Failed to capture output: no read format supported by renderer"); goto error; } frame->format = convert_drm_format_to_wl_shm(drm_format); frame->fourcc = get_output_fourcc(output); struct wlr_box buffer_box = {0}; if (box == NULL) { buffer_box.width = output->width; buffer_box.height = output->height; } else { int ow, oh; wlr_output_effective_resolution(output, &ow, &oh); buffer_box = *box; wlr_box_transform(&buffer_box, &buffer_box, output->transform, ow, oh); buffer_box.x *= output->scale; buffer_box.y *= output->scale; buffer_box.width *= output->scale; buffer_box.height *= output->scale; } frame->box = buffer_box; frame->stride = 4 * buffer_box.width; // TODO: depends on read format zwlr_screencopy_frame_v1_send_buffer(frame->resource, frame->format, buffer_box.width, buffer_box.height, frame->stride); if (version >= 3) { if (frame->fourcc != DRM_FORMAT_INVALID) { zwlr_screencopy_frame_v1_send_linux_dmabuf( frame->resource, frame->fourcc, buffer_box.width, buffer_box.height); } zwlr_screencopy_frame_v1_send_buffer_done(frame->resource); } return; error: zwlr_screencopy_frame_v1_send_failed(frame->resource); frame_destroy(frame); } static void manager_handle_capture_output(struct wl_client *wl_client, struct wl_resource *manager_resource, uint32_t id, int32_t overlay_cursor, struct wl_resource *output_resource) { struct wlr_screencopy_v1_client *client = client_from_resource(manager_resource); uint32_t version = wl_resource_get_version(manager_resource); struct wlr_output *output = wlr_output_from_resource(output_resource); capture_output(wl_client, client, version, id, overlay_cursor, output, NULL); } static void manager_handle_capture_output_region(struct wl_client *wl_client, struct wl_resource *manager_resource, uint32_t id, int32_t overlay_cursor, struct wl_resource *output_resource, int32_t x, int32_t y, int32_t width, int32_t height) { struct wlr_screencopy_v1_client *client = client_from_resource(manager_resource); uint32_t version = wl_resource_get_version(manager_resource); struct wlr_output *output = wlr_output_from_resource(output_resource); struct wlr_box box = { .x = x, .y = y, .width = width, .height = height, }; capture_output(wl_client, client, version, id, overlay_cursor, output, &box); } static void manager_handle_destroy(struct wl_client *wl_client, struct wl_resource *manager_resource) { wl_resource_destroy(manager_resource); } static const struct zwlr_screencopy_manager_v1_interface manager_impl = { .capture_output = manager_handle_capture_output, .capture_output_region = manager_handle_capture_output_region, .destroy = manager_handle_destroy, }; static void manager_handle_resource_destroy(struct wl_resource *resource) { struct wlr_screencopy_v1_client *client = client_from_resource(resource); client_unref(client); } static void manager_bind(struct wl_client *wl_client, void *data, uint32_t version, uint32_t id) { struct wlr_screencopy_manager_v1 *manager = data; struct wlr_screencopy_v1_client *client = calloc(1, sizeof(struct wlr_screencopy_v1_client)); if (client == NULL) { goto failure; } struct wl_resource *resource = wl_resource_create(wl_client, &zwlr_screencopy_manager_v1_interface, version, id); if (resource == NULL) { goto failure; } client->ref = 1; client->manager = manager; wl_list_init(&client->damages); wl_resource_set_implementation(resource, &manager_impl, client, manager_handle_resource_destroy); return; failure: free(client); wl_client_post_no_memory(wl_client); } static void handle_display_destroy(struct wl_listener *listener, void *data) { struct wlr_screencopy_manager_v1 *manager = wl_container_of(listener, manager, display_destroy); wlr_signal_emit_safe(&manager->events.destroy, manager); wl_list_remove(&manager->display_destroy.link); wl_global_destroy(manager->global); free(manager); } struct wlr_screencopy_manager_v1 *wlr_screencopy_manager_v1_create( struct wl_display *display) { struct wlr_screencopy_manager_v1 *manager = calloc(1, sizeof(struct wlr_screencopy_manager_v1)); if (manager == NULL) { return NULL; } manager->global = wl_global_create(display, &zwlr_screencopy_manager_v1_interface, SCREENCOPY_MANAGER_VERSION, manager, manager_bind); if (manager->global == NULL) { free(manager); return NULL; } wl_list_init(&manager->frames); wl_signal_init(&manager->events.destroy); manager->display_destroy.notify = handle_display_destroy; wl_display_add_destroy_listener(display, &manager->display_destroy); return manager; }
1
16,548
This can probably be removed?
swaywm-wlroots
c
@@ -89,8 +89,9 @@ void FetchExecutor::setupResponse(cpp2::ExecutionResponse &resp) { } void FetchExecutor::onEmptyInputs() { + auto outputs = std::make_unique<InterimResult>(std::move(resultColNames_)); if (onResult_) { - onResult_(nullptr); + onResult_(std::move(outputs)); } else if (resp_ == nullptr) { resp_ = std::make_unique<cpp2::ExecutionResponse>(); }
1
/* Copyright (c) 2019 vesoft inc. All rights reserved. * * This source code is licensed under Apache 2.0 License, * attached with Common Clause Condition 1.0, found in the LICENSES directory. */ #include "base/Base.h" #include "FetchExecutor.h" namespace nebula { namespace graph { Status FetchExecutor::prepareYield() { if (yieldClause_ == nullptr) { setupColumns(); } else { yields_ = yieldClause_->columns(); // TODO 'distinct' could always pushdown in fetch. distinct_ = yieldClause_->isDistinct(); } for (auto *col : yields_) { col->expr()->setContext(expCtx_.get()); Status status = col->expr()->prepare(); if (!status.ok()) { return status; } if (col->alias() == nullptr) { resultColNames_.emplace_back(col->expr()->toString()); } else { resultColNames_.emplace_back(*col->alias()); } // such as YIELD 1+1, it has not type in schema, the type from the eval() colTypes_.emplace_back(nebula::cpp2::SupportedType::UNKNOWN); if (col->expr()->isAliasExpression()) { colNames_.emplace_back(*static_cast<InputPropertyExpression*>(col->expr())->prop()); continue; } else if (col->expr()->isTypeCastingExpression()) { // type cast auto exprPtr = static_cast<TypeCastingExpression*>(col->expr()); colTypes_.back() = ColumnTypeToSupportedType(exprPtr->getType()); } colNames_.emplace_back(col->expr()->toString()); } if (expCtx_->hasSrcTagProp() || expCtx_->hasDstTagProp()) { return Status::SyntaxError( "Only support form of alias.prop in fetch sentence."); } auto aliasProps = expCtx_->aliasProps(); for (auto pair : aliasProps) { if (pair.first != *labelName_) { return Status::SyntaxError( "[%s.%s] tag not declared in %s.", pair.first.c_str(), pair.second.c_str(), (*labelName_).c_str()); } } return Status::OK(); } void FetchExecutor::setupColumns() { DCHECK_NOTNULL(labelSchema_); auto iter = labelSchema_->begin(); if (yieldColsHolder_ == nullptr) { yieldColsHolder_ = std::make_unique<YieldColumns>(); } while (iter) { auto *ref = new std::string(""); auto *alias = new std::string(*labelName_); auto *prop = iter->getName(); Expression *expr = new AliasPropertyExpression(ref, alias, new std::string(prop)); YieldColumn *column = new YieldColumn(expr); yieldColsHolder_->addColumn(column); yields_.emplace_back(column); ++iter; } } void FetchExecutor::setupResponse(cpp2::ExecutionResponse &resp) { if (resp_ == nullptr) { resp_ = std::make_unique<cpp2::ExecutionResponse>(); } resp = std::move(*resp_); } void FetchExecutor::onEmptyInputs() { if (onResult_) { onResult_(nullptr); } else if (resp_ == nullptr) { resp_ = std::make_unique<cpp2::ExecutionResponse>(); } onFinish_(); } Status FetchExecutor::getOutputSchema( meta::SchemaProviderIf *schema, const RowReader *reader, SchemaWriter *outputSchema) const { if (expCtx_ == nullptr || resultColNames_.empty()) { LOG(FATAL) << "Input is empty"; } auto collector = std::make_unique<Collector>(schema); auto &getters = expCtx_->getters(); getters.getAliasProp = [&] (const std::string&, const std::string &prop) { return collector->getProp(prop, reader); }; std::vector<VariantType> record; for (auto *column : yields_) { auto *expr = column->expr(); auto value = expr->eval(); if (!value.ok()) { return value.status(); } record.emplace_back(std::move(value.value())); } if (colTypes_.size() != record.size()) { return Status::Error("Input is not equal to output"); } using nebula::cpp2::SupportedType; auto index = 0u; for (auto &it : colTypes_) { SupportedType type; if (it == SupportedType::UNKNOWN) { switch (record[index].which()) { case VAR_INT64: // all integers in InterimResult are regarded as type of INT type = SupportedType::INT; break; case VAR_DOUBLE: type = SupportedType::DOUBLE; break; case VAR_BOOL: type = SupportedType::BOOL; break; case VAR_STR: type = SupportedType::STRING; break; default: LOG(FATAL) << "Unknown VariantType: " << record[index].which(); } } else { type = it; } outputSchema->appendCol(resultColNames_[index], type); index++; } return Status::OK(); } void FetchExecutor::finishExecution(std::unique_ptr<RowSetWriter> rsWriter) { std::unique_ptr<InterimResult> outputs; if (rsWriter != nullptr) { outputs = std::make_unique<InterimResult>(std::move(rsWriter)); } if (onResult_) { onResult_(std::move(outputs)); } else { resp_ = std::make_unique<cpp2::ExecutionResponse>(); resp_->set_column_names(std::move(resultColNames_)); if (outputs != nullptr) { auto rows = outputs->getRows(); resp_->set_rows(std::move(rows)); } } DCHECK(onFinish_); onFinish_(); } } // namespace graph } // namespace nebula
1
21,468
put this sentence in `if (onResult_) { }`
vesoft-inc-nebula
cpp
@@ -235,11 +235,16 @@ echo "echo '{export_forseti_vars}' >> /etc/profile.d/forseti_environment.sh" | s gsutil cp gs://{scanner_bucket}/configs/forseti_conf_server.yaml {forseti_server_conf} gsutil cp -r gs://{scanner_bucket}/rules {forseti_home}/ +# Download the Newest Config Validator constraints from GCS +rm -rf /home/ubuntu/config_validator_constraints +gsutil cp -r gs://{scanner_bucket}/config_validator_constraints /home/ubuntu/ + # Start Forseti service depends on vars defined above. bash ./install/gcp/scripts/initialize_forseti_services.sh echo "Starting services." systemctl start cloudsqlproxy +systemctl start config-validator sleep 5 echo "Attempting to update database schema, if necessary."
1
# Copyright 2017 The Forseti Security 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. """Creates a GCE instance template for Forseti Security.""" def get_patch_search_expression(forseti_version): """Returns a glob expression matching all patches of the given version. TODO: Update in client/forseti-instance-client if update here. Args: forseti_version (str): Installed forseti version. Should start with 'tags/v' if patches are to be updated automatically. Returns: str: Glob expression matching all patches of given forseti_version. None: Returns None if forseti_version is not in 'tags/vX.Y.Z' format. """ if forseti_version[:6] != 'tags/v': return None segments = forseti_version.replace('tags/v', '').split('.') for segment in segments: if not segment.isdigit(): return None return 'v{}.{}.{{[0-9],[0-9][0-9]}}'.format(segments[0], segments[1]) def GenerateConfig(context): """Generate configuration.""" FORSETI_HOME = '$USER_HOME/forseti-security' DOWNLOAD_FORSETI = ( "git clone {src_path}.git".format( src_path=context.properties['src-path'])) patch_search_expression = get_patch_search_expression(context.properties['forseti-version']) if patch_search_expression: CHECKOUT_FORSETI_VERSION = ( """versions=$(git tag -l {patch_search_expression}) versions=(${{versions//;/ }}) for version in "${{versions[@]}}" do segments=(${{version//./ }}) patch=${{segments[2]}} patch=${{patch: 0: 2}} patch=$(echo $patch | sed 's/[^0-9]*//g') # latest_version is an array [full_version, patch_number] if !((${{#latest_version[@]}})) || ((patch > ${{latest_version[1]}})); then latest_version=($version $patch) fi done git checkout ${{latest_version[0]}}""" .format(patch_search_expression=patch_search_expression)) else: CHECKOUT_FORSETI_VERSION = ( "git checkout {forseti_version}".format( forseti_version=context.properties['forseti-version'])) CLOUDSQL_CONN_STRING = '{}:{}:{}'.format( context.env['project'], '$(ref.cloudsql-instance.region)', '$(ref.cloudsql-instance.name)') SCANNER_BUCKET = context.properties['scanner-bucket'] FORSETI_DB_NAME = context.properties['database-name'] SERVICE_ACCOUNT_SCOPES = context.properties['service-account-scopes'] FORSETI_SERVER_CONF = '{}/configs/forseti_conf_server.yaml'.format(FORSETI_HOME) EXPORT_INITIALIZE_VARS = ( 'export SQL_PORT={0}\n' 'export SQL_INSTANCE_CONN_STRING="{1}"\n' 'export FORSETI_DB_NAME="{2}"\n') EXPORT_INITIALIZE_VARS = EXPORT_INITIALIZE_VARS.format( context.properties['db-port'], CLOUDSQL_CONN_STRING, FORSETI_DB_NAME) EXPORT_FORSETI_VARS = ( 'export FORSETI_HOME={forseti_home}\n' 'export FORSETI_SERVER_CONF={forseti_server_conf}\n' ).format(forseti_home=FORSETI_HOME, forseti_server_conf=FORSETI_SERVER_CONF) RUN_FREQUENCY = context.properties['run-frequency'] resources = [] deployment_name_splitted = context.env['deployment'].split('-') deployment_name_splitted.insert(len(deployment_name_splitted)-1, 'vm') instance_name = '-'.join(deployment_name_splitted) resources.append({ 'name': instance_name, 'type': 'compute.v1.instance', 'properties': { 'zone': context.properties['zone'], 'machineType': ( 'https://www.googleapis.com/compute/v1/projects/{}' '/zones/{}/machineTypes/{}'.format( context.env['project'], context.properties['zone'], context.properties['instance-type'])), 'disks': [{ 'deviceName': 'boot', 'type': 'PERSISTENT', 'boot': True, 'autoDelete': True, 'initializeParams': { 'sourceImage': ( 'https://www.googleapis.com/compute/v1' '/projects/{}/global/images/family/{}'.format( context.properties['image-project'], context.properties['image-family'] ) ) } }], 'networkInterfaces': [{ 'network': ( 'https://www.googleapis.com/compute/v1/' 'projects/{}/global/networks/{}'.format( context.properties['vpc-host-project-id'], context.properties['vpc-host-network'])), 'accessConfigs': [{ 'name': 'External NAT', 'type': 'ONE_TO_ONE_NAT' }], 'subnetwork': ( 'https://www.googleapis.com/compute/v1/' 'projects/{}/regions/{}/subnetworks/{}'.format( context.properties['vpc-host-project-id'], context.properties['region'], context.properties['vpc-host-subnetwork'])) }], 'serviceAccounts': [{ 'email': context.properties['service-account'], 'scopes': SERVICE_ACCOUNT_SCOPES, }], 'metadata': { 'items': [{ 'key': 'startup-script', 'value': """#!/bin/bash exec > /tmp/deployment.log exec 2>&1 # Ubuntu available packages refresh. sudo apt-get update -y # Install Google Cloud SDK sudo apt-get --assume-yes install google-cloud-sdk USER_HOME=/home/ubuntu # Install fluentd if necessary. FLUENTD=$(ls /usr/sbin/google-fluentd) if [ -z "$FLUENTD" ]; then cd $USER_HOME curl -sSO https://dl.google.com/cloudagents/install-logging-agent.sh bash install-logging-agent.sh fi # Check whether Cloud SQL proxy is installed. CLOUD_SQL_PROXY=$(which cloud_sql_proxy) if [ -z "$CLOUD_SQL_PROXY" ]; then cd $USER_HOME wget https://dl.google.com/cloudsql/cloud_sql_proxy.{cloudsql_arch} sudo mv cloud_sql_proxy.{cloudsql_arch} /usr/local/bin/cloud_sql_proxy chmod +x /usr/local/bin/cloud_sql_proxy fi # Install Forseti Security. cd $USER_HOME rm -rf *forseti* # Download Forseti source code {download_forseti} cd forseti-security # Fetch tags updates tag changes which fetch all doesn't do git fetch --tags git fetch --all {checkout_forseti_version} # Forseti Host Setup sudo apt-get install -y git unzip # Forseti host dependencies sudo apt-get install -y $(cat install/dependencies/apt_packages.txt | grep -v "#" | xargs) # Forseti dependencies pip install --upgrade pip==9.0.3 pip install -q --upgrade setuptools wheel pip install -q --upgrade -r requirements.txt # Setup Forseti logging touch /var/log/forseti.log chown ubuntu:root /var/log/forseti.log cp {forseti_home}/configs/logging/fluentd/forseti.conf /etc/google-fluentd/config.d/forseti.conf cp {forseti_home}/configs/logging/logrotate/forseti /etc/logrotate.d/forseti chmod 644 /etc/logrotate.d/forseti service google-fluentd restart logrotate /etc/logrotate.conf # Change the access level of configs/ rules/ and run_forseti.sh chmod -R ug+rwx {forseti_home}/configs {forseti_home}/rules {forseti_home}/install/gcp/scripts/run_forseti.sh # Install Forseti python setup.py install # Export variables required by initialize_forseti_services.sh. {export_initialize_vars} # Export variables required by run_forseti.sh {export_forseti_vars} # Store the variables in /etc/profile.d/forseti_environment.sh # so all the users will have access to them echo "echo '{export_forseti_vars}' >> /etc/profile.d/forseti_environment.sh" | sudo sh # Download server configuration from GCS gsutil cp gs://{scanner_bucket}/configs/forseti_conf_server.yaml {forseti_server_conf} gsutil cp -r gs://{scanner_bucket}/rules {forseti_home}/ # Start Forseti service depends on vars defined above. bash ./install/gcp/scripts/initialize_forseti_services.sh echo "Starting services." systemctl start cloudsqlproxy sleep 5 echo "Attempting to update database schema, if necessary." python $USER_HOME/forseti-security/install/gcp/upgrade_tools/db_migrator.py systemctl start forseti echo "Success! The Forseti API server has been started." # Create a Forseti env script FORSETI_ENV="$(cat <<EOF #!/bin/bash export PATH=$PATH:/usr/local/bin # Forseti environment variables export FORSETI_HOME=/home/ubuntu/forseti-security export FORSETI_SERVER_CONF=$FORSETI_HOME/configs/forseti_conf_server.yaml export SCANNER_BUCKET={scanner_bucket} EOF )" echo "$FORSETI_ENV" > $USER_HOME/forseti_env.sh USER=ubuntu # Use flock to prevent rerun of the same cron job when the previous job is still running. # If the lock file does not exist under the tmp directory, it will create the file and put a lock on top of the file. # When the previous cron job is not finished and the new one is trying to run, it will attempt to acquire the lock # to the lock file and fail because the file is already locked by the previous process. # The -n flag in flock will fail the process right away when the process is not able to acquire the lock so we won't # queue up the jobs. # If the cron job failed the acquire lock on the process, it will log a warning message to syslog. (echo "{run_frequency} (/usr/bin/flock -n /home/ubuntu/forseti-security/forseti_cron_runner.lock $FORSETI_HOME/install/gcp/scripts/run_forseti.sh || echo '[forseti-security] Warning: New Forseti cron job will not be started, because previous Forseti job is still running.') 2>&1 | logger") | crontab -u $USER - echo "Added the run_forseti.sh to crontab under user $USER" echo "Execution of startup script finished" """.format( # Cloud SQL properties cloudsql_arch = context.properties['cloudsqlproxy-os-arch'], # Install Forseti. download_forseti=DOWNLOAD_FORSETI, # If installed on a version tag, checkout latest patch. # Otherwise checkout originally installed version. checkout_forseti_version=CHECKOUT_FORSETI_VERSION, # Set ownership for Forseti conf and rules dirs forseti_home=FORSETI_HOME, # Download the Forseti conf and rules. scanner_bucket=SCANNER_BUCKET, forseti_server_conf=FORSETI_SERVER_CONF, # Env variables for Explain export_initialize_vars=EXPORT_INITIALIZE_VARS, # Env variables for Forseti export_forseti_vars=EXPORT_FORSETI_VARS, # Forseti run frequency run_frequency=RUN_FREQUENCY, ) }] } } }) return {'resources': resources}
1
33,781
Will this always be started up as default? Is there any impact to the VM in terms of load and memory usage?
forseti-security-forseti-security
py
@@ -374,7 +374,7 @@ class CommandLine /// parsable types (values are comma separated without space). /// /// Qualifiers that are defined BEFORE any parameter sets apply to ALL parameter sets. qualifiers that - /// are defined AFTER a parameter set will apply only the the parameter set that preceeds them. + /// are defined AFTER a parameter set will apply only the the parameter set that precedes them. /// /// See code:#DefiningParametersAndQualifiers /// See code:#Overview
1
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Text; using System.Collections.Generic; using System.IO; using Microsoft.DotNet.Execute; using System.Reflection; namespace Microsoft.Fx.CommandLine { // See code:#Overview to get started. /// <summary> /// #Overview /// /// The code:CommandLineParser is a utility for parsing command lines. Command lines consist of three basic /// entities. A command can have any (or none) of the following (separated by whitespace of any size). /// /// * PARAMETERS - these are non-space strings. They are positional (logicaly they are numbered). Strings /// with whitespace can be specified by enclosing in double quotes. /// /// * QUALIFIERS - Qualifiers are name-value pairs. The following syntax is supported. /// * -QUALIFIER /// * -QUALIFIER:VALUE /// * -QUALIFIER=VALUE /// * -QUALIFIER VALUE /// /// The end of a value is delimited by space. Again values with spaces can be encoded by enclosing them /// within the value (or the whole qualifer-value string), in double quotes. The first form (where a value is /// not specified) is only available for boolean qualifiers, and boolean values can not use the form where /// the qualifer and value are separated by space. The '/' character can also be used instead of the '-' /// to begin a qualifier. /// /// Unlike parameters, qualifiers are NOT ordered. They may occur in any order with respect to the /// parameters or other qualifiers and THAT ORDER IS NOT COMMUNICATED THROUGH THE PARSER. Thus it is not /// possible to have qualifiers that only apply to specific parameters. /// /// * PARAMETER SET SPECIFIER - A parameter set is optional argument that looks like a boolean qualifier /// (however if NoDashOnParameterSets is set the dash is not need, so it is looks like a parameter), /// that is special in that it decides what qualifiers and positional parameters are allowed. See /// code:#ParameterSets for more /// /// #ParameterSets /// /// Parameter sets are an OPTIONAL facility of code:CommandLineParser that allow more complex command lines /// to be specified accurately. It not uncommon for a EXE to have several 'commands' that are logically /// independent of one another. For example a for example For example a program might have 'checkin' /// 'checkout' 'list' commands, and each of these commands has a different set of parameters that are needed /// and qualifiers that are allowed. (for example checkout will take a list of file names, list needs nothing, /// and checkin needs a comment). Additionally some qualifiers (like say -dataBaseName can apply to any of the /// commands). /// /// The following command lines are legal: /// /// * EXE -checkout MyFile1 MyFile -dataBaseName:MyDatabase /// * EXE -dataBaseName:MyDatabase -list /// * EXE -comment "Specifying the comment first" -checkin /// * EXE -checkin -comment "Specifying the comment afterward" /// /// But the following are not: /// /// * EXE -checkout /// * EXE -checkout -comment "hello" /// * EXE -list MyFile /// /// You do this by specifying 'checkout', 'list' and 'checkin' as parameter sets. On the command line they /// look like boolean qualifiers, however they have additional semantics. They must come before any /// positional parameters (because they affect whether the parameters are allowed and what they are named), /// and they are mutually exclusive. Each parameter set gets its own set of parameter definitions, and /// qualifiers can either be associated with a particular parameter set (like -comment) or global to all /// parameter sets (like -dataBaseName) . /// /// By default parameter set specifiers look like a boolean specifier (begin with a '-' or '/'), however /// because it is common practice to NOT have a dash for commands, there there is a Property /// code:CommandLineParser.NoDashOnParameterSets that indicates that the dash is not used. If this was /// specified then the following command would be legal. /// /// * EXE checkout MyFile1 MyFile -dataBaseName:MyDatabase /// /// #DefaultParameterSet /// /// One parameter set (which has the empty string name), is special in that it is used when no other /// parameter set is matched. This is the default parameter set. For example, if -checkout was defined to be /// the default parameter set, then the following would be legal. /// /// * EXE Myfile1 Myfile /// /// And would implicitly mean 'checkout' Myfile1, Myfile2 /// /// If no parameter sets are defined, then all qualifiers and parameters are in the default parameter set. /// /// ------------------------------------------------------------------------- /// #Syntatic ambiguities /// /// Because whitespace can separate a qualifier from its value AND Qualifier from each other, and because /// parameter values might start with a dash (and thus look like qualifiers), the syntax is ambiguous. It is /// disambigutated with the following rules. /// * The command line is parsed into 'arguments' that are separated by whitespace. Any string enclosed /// in "" will be a single argument even if it has embedded whitespace. Double quote characters can /// be specified by \" (and a \" literal can be specified by \\" etc). /// * Arguments are parsed into qualifiers. This parsing stops if a '--' argument is found. Thus all /// qualifiers must come before any '--' argument but parameters that begin with - can be specified by /// placing them after the '--' argument, /// * Qualifiers are parsed. Because spaces can be used to separate a qualifier from its value, the type of /// the qualifier must be known to parse it. Boolean values never consume an additional parameter, and /// non-boolean qualifiers ALWAYS consume the next argument (if there is no : or =). If the empty /// string is to be specified, it must use the ':' or '=' form. Moreover it is illegal for the values /// that begin with '-' to use space as a separator. They must instead use the ':' or '=' form. This /// is because it is too confusing for humans to parse (values look like qualifiers). /// * Parameters are parsed. Whatever arguments that were not used by qualifiers are parameters. /// /// -------------------------------------------------------------------------------------------- /// #DefiningParametersAndQualifiers /// /// The following example shows the steps for defining the parameters and qualifiers for the example. Note /// that the order is important. Qualifiers that apply to all commands must be specified first, then each /// parameter set then finally the default parameter set. Most steps are optional. #if EXAMPLE1 class CommandLineParserExample1 { enum Command { checkout, checkin, list }; static void Main() { string dataBaseName = "myDefaultDataBase"; string comment = String.Empty; Command command = checkout; string[] fileNames = null; // Step 1 define the parser. CommandLineParser commandLineParser = new CommandLineParser(); // by default uses Environment.CommandLine // Step 2 (optional) define qualifiers that apply to all parameter sets. commandLineParser.DefineOptionalParameter("dataBaseName", ref dataBaseName, "Help for database."); // Step 3A define the checkin command this includes all parameters and qualifiers specific to this command commandLineParser.DefineParameterSet("checkin", ref command, Command.checkin, "Help for checkin."); commandLineParser.DefineOptionalQualifiers("comment", ref comment, "Help for -comment."); // Step 3B define the list command this includes all parameters and qualifiers specific to this command commandLineParser.DefineParameterSet("list", ref command, Command.list, "Help for list."); // Step 4 (optional) define the default parameter set (in this case checkout). commandLineParser.DefineDefaultParameterSet("checkout", ref command, Command.checkout, "Help for checkout."); commandLineParser.DefineParamter("fileNames", ref fileNames, "Help for fileNames."); // Step 5, do final validation (look for undefined qualifiers, extra parameters ... commandLineParser.CompleteValidation(); // Step 6 use the parsed values Console.WriteLine("Got {0} {1} {2} {3} {4}", dataBaseName, command, comment, string.Join(',', fileNames)); } } #endif /// #RequiredAndOptional /// /// Parameters and qualifiers can be specified as required (the default), or optional. Making the default /// required was chosen to make any mistakes 'obvious' since the parser will fail if a required parameter is /// not present (if the default was optional, it would be easy to make what should have been a required /// qualifier optional, leading to business logic failiure). /// /// #ParsedValues /// /// The class was designed maximize programmer convenience. For each parameter, only one call is needed to /// both define the parameter, its help message, and retrive its (strong typed) value. For example /// /// * int count = 5; /// * parser.DefineOptionalQualifier("count", ref count, "help for optional count qualifier"); /// /// Defines a qualifier 'count' and will place its value in the local variable 'count' as a integer. Default /// values are supported by doing nothing, so in the example above the default value will be 5. /// /// Types supported: The parser will support any type that has a static method called 'Parse' taking one /// string argument and returning that type. This is true for all primtive types, DateTime, Enumerations, and /// any user defined type that follows this convention. /// /// Array types: The parser has special knowledge of arrays. If the type of a qualifier is an array, then the /// string value is assumed to be a ',' separated list of strings which will be parsed as the element type of /// the array. In addition to the ',' syntax, it is also legal to specify the qualifier more than once. For /// example given the definition /// /// * int[] counts; /// * parser.DefineOptionalQualifier("counts", ref counts, "help for optional counts qualifier"); /// /// The command line /// /// * EXE -counts 5 SomeArg -counts 6 -counts:7 /// /// Is the same as /// /// * EXE -counts:5,6,7 SomeArg /// /// If a qualifier or parameter is an array type and is required, then the array must have at least one /// element. If it is optional, then the array can be empty (but in all cases, the array is created, thus /// null is never returned by the command line parser). /// /// By default is it is illegal for a non-array qualifier to be specified more than once. It is however /// possible to override this behavior by setting the LastQualifierWins property before defining the qualifier. /// /// ------------------------------------------------------------------------- /// #Misc /// /// Qualifier can have more than one string form (typically a long and a short form). These are specified /// with the code:CommandLineParser.DefineAliases method. /// /// After defining all the qualifiers and parameters, it is necessary to call the parser to check for the user /// specifying a qualifier (or parameter) that does not exist. This is the purpose of the /// code:CommandLineParser.CompleteValidation method. /// /// When an error is detected at runtime an instance of code:CommandLineParserException is thrown. The error /// message in this exception was designed to be suitable to print to the user directly. /// /// #CommandLineHelp /// /// The parser also can generate help that is correct for the qualifier and parameter definitions. This can be /// accessed from the code:CommandLineParser.GetHelp method. It is also possible to get the help for just a /// particular Parameter set with code:CommandLineParser.GetHelpForParameterSet. This help includes command /// line syntax, whether the qualifier or parameter is optional or a list, the types of the qualifiers and /// parameters, the help text, and default values. The help text comes from the 'Define' Methods, and is /// properly word-wrapped. Newlines in the help text indicate new paragraphs. /// /// #AutomaticExceptionProcessingAndHelp /// /// In the CommandLineParserExample1, while the command line parser did alot of the work there is still work /// needed to make the application user friendly that pretty much all applications need. These include /// /// * Call the code:CommandLineParser constructor and code:CommandLineParser.CompleteValidation /// * Catch any code:CommandLineParserException and print a friendly message /// * Define a -? qualifier and wire it up to print the help. /// /// Since this is stuff that all applications will likely need the /// code:CommandLineParser.ParseForConsoleApplication was created to do all of this for you, thus making it /// super-easy to make a production quality parser (and concentrate on getting your application logic instead /// of command line parsing). Here is an example which defines a 'Ping' command. If you will notice there are /// very few lines of code that are not expressing something very specific to this applications. This is how /// it should be! #if EXAMPLE2 class CommandLineParserExample2 { static void Main() { // Step 1: Initialize to the defaults string Host = null; int Timeout = 1000; bool Forever = false; // Step 2: Define the parameters, in this case there is only the default parameter set. CommandLineParser.ParseForConsoleApplication(args, delegate(CommandLineParser parser) { parser.DefineOptionalQualifier("Timeout", ref Timeout, "Timeout in milliseconds to wait for each reply."); parser.DefineOptionalQualifier("Forever", ref Forever, "Ping forever."); parser.DefineDefaultParameterSet("Ping sends a network request to a host to reply to the message (to check for liveness)."); parser.DefineParameter("Host", ref Host, "The Host to send a ping message to."); }); // Step 3, use the parameters Console.WriteLine("Got {0} {1} {2} {3}", Host, Timeout, Forever); } } #endif /// Using local variables for the parsed arguments if fine when the program is not complex and the values /// don't need to be passed around to many routines. In general, however it is often a better idea to /// create a class whose sole purpose is to act as a repository for the parsed arguments. This also nicely /// separates all command line processing into a single class. This is how the ping example would look in /// that style. Notice that the main program no longer holds any command line processing logic, and that /// 'commandLine' can be passed to other routines in bulk easily. #if EXAMPLE3 class CommandLineParserExample3 { static void Main() { CommandLine commandLine = new CommandLine(); Console.WriteLine("Got {0} {1} {2} {3}", commandLine.Host, commandLine.Timeout, commandLine.Forever); } } class CommandLine { public CommandLine() { CommandLineParser.ParseForConsoleApplication(args, delegate(CommandLineParser parser) { parser.DefineOptionalQualifier("Timeout", ref Timeout, "Timeout in milliseconds to wait for each reply."); parser.DefineOptionalQualifier("Forever", ref Forever, "Ping forever."); parser.DefineDefaultParameterSet("Ping sends a network request to a host to reply to the message (to check for liveness)."); parser.DefineParameter("Host", ref Host, "The Host to send a ping message to."); }); } public string Host = null; public int Timeout = 1000; public bool Forever = false; }; #endif /// <summary> /// see code:#Overview for more /// </summary> public class CommandLineParser { /// <summary> /// If you are building a console Application, there is a common structure to parsing arguments. You want /// the text formatted and output for console windows, and you want /? to be wired up to do this. All /// errors should be caught and displayed in a nice way. This routine does this 'boiler plate'. /// </summary> /// <param name="parseBody">parseBody is the body of the parsing that this outer shell does not provide. /// in this delegate, you should be defining all the command line parameters using calls to Define* methods. /// </param> public static bool ParseForConsoleApplication(Action<CommandLineParser> parseBody, string[] args, Setup setupContent) { return Parse(parseBody, parser => { var parameterSetTofocusOn = parser.HelpRequested; string helpString; if (parameterSetTofocusOn.Length == 0) { parameterSetTofocusOn = null; //helpString = parser.GetHelp(GetConsoleWidth() - 1, parameterSetTofocusOn, true); } helpString = parser.GetIntroTextForHelp(GetConsoleWidth() - 1).ToString(); helpString += parser.GetHelp(GetConsoleWidth() - 1, parameterSetTofocusOn, true); DisplayStringToConsole(helpString); }, (parser, ex) => { Console.Error.WriteLine("Error: " + ex.Message); Console.ForegroundColor = ConsoleColor.DarkYellow; Console.WriteLine("Our dev workflow has changed! Use -? for help in the new options we have and how to pass parameters now."); Console.ResetColor(); }, setupContent, args); } public static bool Parse(Action<CommandLineParser> parseBody, Action<CommandLineParser> helpHandler, Action<CommandLineParser, Exception> errorHandler, Setup setupContent, string[] args) { var help = false; CommandLineParser parser = new CommandLineParser(args, setupContent); parser.DefineOptionalQualifier("?", ref help, "Print this help guide.", null, null); try { // RawPrint the help. if (parser.HelpRequested != null) { parser._skipParameterSets = true; parser._skipDefinitions = true; } parseBody(parser); if (parser.HelpRequested != null) { helpHandler(parser); return false; } parser.CompleteValidation(); return true; } catch (CommandLineParserException e) { errorHandler(parser, e); return false; } } /// <summary> /// Qualifiers are command line parameters of the form -NAME:VALUE where NAME is an alphanumeric name and /// VALUE is a string. The parser also accepts -NAME: VALUE and -NAME VALUE but not -NAME : VALUE For /// boolan parameters, the VALUE can be dropped (which means true), and a empty string VALUE means false. /// Thus -NAME means the same as -NAME:true and -NAME: means the same as -NAME:false (and boolean /// qualifiers DONT allow -NAME true or -NAME false). /// /// The types that are supported are any type that has a static 'Parse' function that takes a string /// (this includes all primitive types as well as DateTime, and Enumerations, as well as arrays of /// parsable types (values are comma separated without space). /// /// Qualifiers that are defined BEFORE any parameter sets apply to ALL parameter sets. qualifiers that /// are defined AFTER a parameter set will apply only the the parameter set that preceeds them. /// /// See code:#DefiningParametersAndQualifiers /// See code:#Overview /// <param name="name">The name of the qualifier.</param> /// <param name="retVal">The place to put the parsed value</param> /// <param name="helpText">Text to print for this qualifier. It will be word-wrapped. Newlines indicate /// new paragraphs.</param> /// </summary> public void DefineOptionalQualifier<T>(string name, ref T retVal, string helpText, string defaultValue, List<string> legalValues) { object obj = DefineQualifier(name, typeof(T), retVal, helpText, false, defaultValue, legalValues); if (obj != null) retVal = (T)obj; } /// <summary> /// Like code:DeclareOptionalQualifier except it is an error if this parameter is not on the command line. /// <param name="name">The name of the qualifer.</param> /// <param name="retVal">The place to put the parsed value</param> /// <param name="helpText">Text to print for this qualifer. It will be word-wrapped. Newlines indicate /// new paragraphs.</param> /// </summary> public void DefineQualifier<T>(string name, ref T retVal, string helpText, string defaultValue, List<string> legalValues) { object obj = DefineQualifier(name, typeof(T), retVal, helpText, true, defaultValue, legalValues); if (obj != null) retVal = (T)obj; } /// <summary> /// Specify additional aliases for an qualifier. This call must come BEFORE the call to /// Define*Qualifier, since the definition needs to know about its aliases to do its job. /// </summary> public void DefineAliases(string officalName, params string[] alaises) { // TODO assert that aliases are defined before the Definition. // TODO confirm no ambiguities (same alias used again). if (_aliasDefinitions != null && _aliasDefinitions.ContainsKey(officalName)) throw new CommandLineParserDesignerException("Named parameter " + officalName + " already has been given aliases."); if (_aliasDefinitions == null) _aliasDefinitions = new Dictionary<string, string[]>(); _aliasDefinitions.Add(officalName, alaises); } /// <summary> /// DefineParameter declares an unnamed mandatory parameter (basically any parameter that is not a /// qualifier). These are given ordinal numbers (starting at 0). You should declare the parameter in the /// desired order. /// /// /// See code:#DefiningParametersAndQualifiers /// See code:#Overview /// <param name="name">The name of the parameter.</param> /// <param name="retVal">The place to put the parsed value</param> /// <param name="helpText">Text to print for this qualifer. It will be word-wrapped. Newlines indicate /// new paragraphs.</param> /// </summary> public void DefineParameter<T>(string name, ref T retVal, string helpText) { object obj = DefineParameter(name, typeof(T), retVal, helpText, true); if (obj != null) retVal = (T)obj; } /// <summary> /// Like code:DeclareParameter except the parameter is optional. /// These must come after non-optional (required) parameters. /// </summary> /// <param name="name">The name of the parameter</param> /// <param name="retVal">The location to place the parsed value.</param> /// <param name="helpText">Text to print for this qualifer. It will be word-wrapped. Newlines indicate /// new paragraphs.</param> public void DefineOptionalParameter<T>(string name, ref T retVal, string helpText) { object obj = DefineParameter(name, typeof(T), retVal, helpText, false); if (obj != null) retVal = (T)obj; } /// <summary> /// A parameter set defines on of a set of 'commands' that decides how to parse the rest of the command /// line. If this 'command' is present on the command line then 'val' is assigned to 'retVal'. /// Typically 'retVal' is a variable of a enumerated type (one for each command), and 'val' is one /// specific value of that enumeration. /// /// * See code:#ParameterSets /// * See code:#DefiningParametersAndQualifiers /// * See code:#Overview /// <param name="name">The name of the parameter set.</param> /// <param name="retVal">The place to put the parsed value</param> /// <param name="val">The value to place into 'retVal' if this parameter set is indicated</param> /// <param name="helpText">Text to print for this qualifer. It will be word-wrapped. Newlines indicate /// new paragraphs.</param> /// </summary> public void DefineParameterSet<T>(string name, ref T retVal, T val, string helpText) { if (DefineParameterSet(name, helpText)) retVal = val; } /// <summary> /// There is one special parameter set called the default parameter set (whose names is empty) which is /// used when a command line does not have one of defined parameter sets. It is always present, even if /// this method is not called, so calling this method is optional, however, by calling this method you can /// add help text for this case. If present this call must be AFTER all other parameter set /// definitions. /// /// * See code:#DefaultParameterSet /// * See code:#DefiningParametersAndQualifiers /// * See code:#Overview /// <param name="helpText">Text to print for this qualifer. It will be word-wrapped. Newlines indicate /// new paragraphs.</param> /// </summary> public void DefineDefaultParameterSet(string helpText) { DefineParameterSet(String.Empty, helpText); } /// <summary> /// This variation of DefineDefaultParameterSet has a 'retVal' and 'val' parameters. If the command /// line does not match any of the other parameter set defintions, then 'val' is asigned to 'retVal'. /// Typically 'retVal' is a variable of a enumerated type and 'val' is a value of that type. /// /// * See code:DefineDefaultParameterSet for more. /// <param name="retVal">The place to put the parsed value</param> /// <param name="val">The value to place into 'retVal' if this parameter set is indicated</param> /// <param name="helpText">Text to print for this qualifer. It will be word-wrapped. Newlines indicate /// new paragraphs.</param> /// </summary> public void DefineDefaultParameterSet<T>(ref T retVal, T val, string helpText) { if (DefineParameterSet(String.Empty, helpText)) retVal = val; } // You can influence details of command line parsing by setting the following properties. // These should be set before the first call to Define* routines and should not change // thereafter. /// <summary> /// By default parameter set specifiers must look like a qualifier (begin with a -), however setting /// code:NoDashOnParameterSets will define a parameter set marker not to have any special prefix (just /// the name itself. /// </summary> public bool NoDashOnParameterSets { get { return _noDashOnParameterSets; } set { if (_noDashOnParameterSets != value) ThrowIfNotFirst("NoDashOnParameterSets"); _noDashOnParameterSets = value; } } /// <summary> /// By default, the syntax (-Qualifier:Value) and (-Qualifer Value) are both allowed. However /// this makes it impossible to use -Qualifier to specify that a qualifier is present but uses /// a default value (you have to use (-Qualifier: )) Specifying code:NoSpaceOnQualifierValues /// indicates that the syntax (-Qualifer ObjectEnumerator) is not allowed, which allows this. /// </summary> /// TODO decide if we should keep this... public bool NoSpaceOnQualifierValues { get { return _noSpaceOnQualifierValues; } set { if (_noSpaceOnQualifierValues != value) ThrowIfNotFirst("NoSpaceOnQualifierValues"); _noSpaceOnQualifierValues = value; } } /// <summary> /// If the positional parameters might look like named parameters (typically happens when the tail of the /// command line is literal text), it is useful to stop the search for named parameters at the first /// positional parameter. /// /// Because some parameters sets might want this behavior and some might not, you specify the list of /// parameter sets that you want to opt in. /// /// The expectation is you do something like /// * commandLine.ParameterSetsWhereQualifiersMustBeFirst = new string[] { "parameterSet1" }; /// /// The empty string is a wildcard that indicats all parameter sets have the qualifiersMustBeFirst /// attribute. This is the only way to get this attribute on the default parameter set. /// </summary> public string[] ParameterSetsWhereQualifiersMustBeFirst { get { return _parameterSetsWhereQualifiersMustBeFirst; } set { ThrowIfNotFirst("ParameterSetsWhereQualifiersMustBeFirst"); NoSpaceOnQualifierValues = true; _parameterSetsWhereQualifiersMustBeFirst = value; } } /// <summary> /// By default qualifiers may being with a - or a / character. Setting code:QualifiersUseOnlyDash will /// make / invalid qualifier marker (only - can be used) /// </summary> public bool QualifiersUseOnlyDash { get { return _qualifiersUseOnlyDash; } set { if (_qualifiersUseOnlyDash != value) ThrowIfNotFirst("OnlyDashForQualifiers"); _qualifiersUseOnlyDash = value; } } // TODO remove? Not clear it is useful. Can be useful for CMD.EXE alias (which provide a default) but later user may override. /// <summary> /// By default, a non-list qualifier can not be specified more than once (since one or the other will /// have to be ignored). Normally an error is thrown. Setting code:LastQualifierWins makes it legal, and /// the last qualifier is the one that is used. /// </summary> public bool LastQualifierWins { get { return _lastQualifierWins; } set { _lastQualifierWins = value; } } public static string ExtraParameters { get { return _extraParameters; } } // These routines are typically are not needed because ParseArgsForConsoleApp does the work. public CommandLineParser(string commandLine) { ParseWords(commandLine); } public CommandLineParser(string[] args, Setup setupContent) { _args = new List<string>(args); _setupContent = setupContent; } /// <summary> /// Check for any parameters that the user specified but that were not defined by a Define*Parameter call /// and throw an exception if any are found. /// /// Returns true if validation was completed. It can return false (rather than throwing), If the user /// requested help (/?). Thus if this routine returns false, the 'GetHelp' should be called. /// </summary> public bool CompleteValidation() { // Check if there are any undefined parameters or ones specified twice. foreach (int encodedPos in _dashedParameterEncodedPositions.Values) { throw new CommandLineParserException("Unexpected qualifier: " + _args[GetPosition(encodedPos)] + "."); } // Find any 'unused' parameters; List<string> unusedParameters = new List<string>(); foreach(string param in _args) { if(!string.IsNullOrEmpty(param)) { unusedParameters.Add(param); } } if (unusedParameters.Count > 0) { throw new CommandLineParserException("Parameter not recognized: " + unusedParameters[0] + "."); } // TODO we should null out data structures we no longer need, to save space. // Not critical because in the common case, the parser as a whole becomes dead. if (_helpRequestedFor != null) return false; if (!_defaultParamSetEncountered) { if (_paramSetEncountered && _parameterSetName == null) { if (_noDashOnParameterSets && _curPosition < _args.Count) throw new CommandLineParserException("Unrecognised command: " + _args[_curPosition]); else throw new CommandLineParserException("No command given."); } } return true; } /// <summary> /// Return the string representing the help for a single paramter set. If displayGlobalQualifiers is /// true than qualifiers that apply to all parameter sets is also included, otherwise it is just the /// parameters and qualifiers that are specific to that parameters set. /// /// If the parameterSetName null, then the help for the entire program (all parameter /// sets) is returned. If parameterSetName is not null (empty string is default parameter set), /// then it generates help for the parameter set specified on the command line. /// /// Since most of the time you don't need help, helpInformatin is NOT collected during the Define* calls /// unless HelpRequested is true. If /? is seen on the command line first, then this works. You can /// also force this by setting HelpRequested to True before calling all the Define* APIs. /// /// </summary> public string GetHelp(int maxLineWidth, string parameterSetName = null, bool displayGlobalQualifiers = true) { Debug.Assert(_mustParseHelpStrings); if (!_mustParseHelpStrings) // Backup for retail code. return null; if (parameterSetName == null) return GetFullHelp(maxLineWidth); // Find the beginning of the parameter set parameters, as well as the end of the global parameters // (Which come before any parameters set). int parameterSetBody = 0; // Points at body of the parameter set (parameters after the parameter set) CommandLineParameter parameterSetParameter = null; for (int i = 0; i < _parameterDescriptions.Count; i++) { CommandLineParameter parameter = _parameterDescriptions[i]; if (parameter.IsParameterSet) { parameterSetParameter = parameter; if (string.Compare(parameterSetParameter.Name, parameterSetName, StringComparison.OrdinalIgnoreCase) == 0) { parameterSetBody = i + 1; break; } } } if (parameterSetBody == 0 && parameterSetName != String.Empty) return String.Empty; // At this point parameterSetBody and globalParametersEnd are properly set. Start generating strings StringBuilder sb = new StringBuilder(); // Create the 'Usage' line; string appName = GetEntryAssemblyName(); string command = parameterSetParameter.Syntax(); sb.Append(command).AppendLine().AppendLine(); sb.Append("Usage: ").Append(appName); if (parameterSetName.Length > 0) { sb.Append(' '); sb.Append(command); sb.Append(" [Action] (global settings)"); } bool hasQualifiers = false; bool hasParameters = false; for (int i = parameterSetBody; i < _parameterDescriptions.Count; i++) { CommandLineParameter parameter = _parameterDescriptions[i]; if (parameter.IsParameterSet) break; if (parameter.IsPositional) { hasParameters = true; sb.Append(' ').Append(parameter.Syntax()); } else { hasQualifiers = true; break; } } sb.AppendLine(); // Print the help for the command itself. /*if (parameterSetParameter != null && !string.IsNullOrEmpty(parameterSetParameter.HelpText)) { sb.AppendLine(); Wrap(sb.Append(" "), parameterSetParameter.HelpText, 2, " ", maxLineWidth); }*/ if (hasParameters) { sb.AppendLine().Append("Parameters:").AppendLine(); for (int i = parameterSetBody; i < _parameterDescriptions.Count; i++) { CommandLineParameter parameter = _parameterDescriptions[i]; if (parameter.IsParameterSet) break; if (parameter.IsPositional) { ParameterHelp(parameter, sb, QualifierSyntaxWidth, maxLineWidth); } } } else if (hasQualifiers) { sb.AppendLine().Append("Actions:").AppendLine(); for (int i = parameterSetBody; i < _parameterDescriptions.Count; i++) { CommandLineParameter parameter = _parameterDescriptions[i]; if (parameter.IsParameterSet) break; if (parameter.IsNamed) { ParameterHelp(parameter, sb, QualifierSyntaxWidth, maxLineWidth); string commandSettingsHelp = _setupContent.GetHelpCommand(parameterSetParameter.Name, parameter.Name); Wrap(sb, commandSettingsHelp, QualifierSyntaxWidth, new string(' ', QualifierSyntaxWidth), maxLineWidth, false); } } } else { string commandSettingsHelp = _setupContent.GetHelpCommand(parameterSetParameter.Name); Wrap(sb, commandSettingsHelp, QualifierSyntaxWidth, new string(' ', QualifierSyntaxWidth), maxLineWidth, false); } string globalQualifiers = null; if (displayGlobalQualifiers) globalQualifiers = GetHelpGlobalQualifiers(maxLineWidth); if(!string.IsNullOrEmpty(globalQualifiers)) { sb.AppendLine().Append('-', maxLineWidth - 1).AppendLine(); sb.Append("Global Settings:").AppendLine(); sb.AppendLine(); sb.Append(globalQualifiers); } return sb.ToString(); } /// <summary> /// Returns non-null if the user specified /? on the command line. returns the word after /? (which may be the empty string) /// </summary> public string HelpRequested { get { return _helpRequestedFor; } set { _helpRequestedFor = value; _mustParseHelpStrings = true; } } #region private /// <summary> /// CommandLineParameter contains the 'full' information for a parameter or qualifier used for generating help. /// Most of the time we don't actualy generate instances of this class. (see mustParseHelpStrings) /// </summary> private class CommandLineParameter { public string Name { get { return _name; } } public Type Type { get { return _type; } } public string DefaultValue { get { return _defaultValue; } } public List<string> LegalValues { get { return _legalValues; } } public object Value { get { return _value; } } public bool IsRequired { get { return _isRequired; } } public bool IsPositional { get { return _isPositional; } } public bool IsNamed { get { return !_isPositional; } } public bool IsParameterSet { get { return _isParameterSet; } } public string HelpText { get { return _helpText; } } public override string ToString() { return "<CommandLineParameter " + "Name=\"" + _name + "\" " + "Type=\"" + _type + "\" " + "DefaultValue=\"" + _defaultValue + "\" " + "IsRequired=\"" + IsRequired + "\" " + "IsPositional=\"" + IsPositional + "\" " + "HelpText=\"" + HelpText + "\"/>"; } public string Syntax() { string ret = _name; if (IsNamed) ret = "-" + ret; if (Type.IsArray) ret = ret + (IsNamed ? "," : " ") + "..."; if (!IsRequired) ret = "[" + ret + "]"; return ret; } #region private internal CommandLineParameter(string Name, object value, string helpText, Type type, bool isRequired, bool isPositional, bool isParameterSet, List<string> legalvalues, string defaultValue = null) { _name = Name; _value = value; _defaultValue = defaultValue; _type = type; _helpText = helpText; _isRequired = isRequired; _isPositional = isPositional; _isParameterSet = isParameterSet; if(legalvalues != null) { _legalValues = new List<string>(legalvalues); } else { _legalValues = new List<string>(); } } private string _name; private object _value; private string _defaultValue; private List<string> _legalValues; private string _helpText; private Type _type; private bool _isRequired; private bool _isPositional; private bool _isParameterSet; #endregion } private void ThrowIfNotFirst(string propertyName) { if (_qualiferEncountered || _positionalArgEncountered || _paramSetEncountered) throw new CommandLineParserDesignerException("The property " + propertyName + " can only be set before any calls to Define* Methods."); } private static bool IsDash(char c) { // can be any of ASCII dash (0x002d), endash (0x2013), emdash (0x2014) or hori-zontal bar (0x2015). return c == '-' || ('\x2013' <= c && c <= '\x2015'); } /// <summary> /// Returns true if 'arg' is a qualifier begins with / or - /// </summary> private bool IsQualifier(string arg) { if (arg.Length < 1) return false; if (IsDash(arg[0])) return true; if (!_qualifiersUseOnlyDash && arg[0] == '/') return true; return false; } /// <summary> /// Qualifiers have the syntax -/NAME=Value. This returns the NAME /// </summary> private string ParseParameterName(string arg) { string ret = null; if (arg != null && IsQualifier(arg)) { int endName = arg.IndexOfAny(s_separators); if (endName < 0) endName = arg.Length; ret = arg.Substring(1, endName - 1); } return ret; } /// <summary> /// Parses 'commandLine' into words (space separated items). Handles quoting (using double quotes) /// and handles escapes of double quotes and backslashes with the \" and \\ syntax. /// In theory this mimics the behavior of the parsing done before Main to parse the command line into /// the string[]. /// </summary> /// <param name="commandLine"></param> private void ParseWords(string commandLine) { // TODO review this carefully. _args = new List<string>(); int wordStartIndex = -1; bool hasExcapedQuotes = false; bool isResponseFile = false; int numQuotes = 0; // Loop to <=length to reuse the same logic for AddWord on spaces and the end of the string for (int i = 0; i <= commandLine.Length; i++) { char c = (i < commandLine.Length ? commandLine[i] : '\0'); if (c == '"') { numQuotes++; if (wordStartIndex < 0) wordStartIndex = i; i++; for (;;) { if (i >= commandLine.Length) throw new CommandLineParserException("Unmatched quote at position " + i + "."); c = commandLine[i]; if (c == '"') { if (i > 0 && commandLine[i - 1] == '\\') hasExcapedQuotes = true; else break; } i++; } } else if (c == ' ' || c == '\t' || c == '\0') { if (wordStartIndex >= 0) { AddWord(ref commandLine, wordStartIndex, i, numQuotes, hasExcapedQuotes, isResponseFile); wordStartIndex = -1; hasExcapedQuotes = false; numQuotes = 0; isResponseFile = false; } } else if (c == '@') { isResponseFile = true; } else { if (wordStartIndex < 0) wordStartIndex = i; } } } private void AddWord(ref string commandLine, int wordStartIndex, int wordEndIndex, int numQuotes, bool hasExcapedQuotes, bool isResponseFile) { if (!_seenExeArg) { _seenExeArg = true; return; } string word; if (numQuotes > 0) { // Common case, the whole word is quoted, and no escaping happened. if (!hasExcapedQuotes && numQuotes == 1 && commandLine[wordStartIndex] == '"' && commandLine[wordEndIndex - 1] == '"') word = commandLine.Substring(wordStartIndex + 1, wordEndIndex - wordStartIndex - 2); else { // Remove "" (except for quoted quotes!) StringBuilder sb = new StringBuilder(); for (int i = wordStartIndex; i < wordEndIndex;) { char c = commandLine[i++]; if (c != '"') { if (c == '\\' && i < wordEndIndex && commandLine[i] == '"') { sb.Append('"'); i++; } else sb.Append(c); } } word = sb.ToString(); } } else word = commandLine.Substring(wordStartIndex, wordEndIndex - wordStartIndex); if (isResponseFile) { string responseFile = word; if (!File.Exists(responseFile)) throw new CommandLineParserException("Response file '" + responseFile + "' does not exist!"); // Replace the commandline with the contents from the text file. StringBuilder sb = new StringBuilder(); foreach (string line in File.ReadAllLines(responseFile)) { string cleanLine = line.Trim(); if (string.IsNullOrEmpty(cleanLine)) continue; sb.Append(cleanLine); sb.Append(' '); } if (sb.Length > 0) commandLine += " " + sb.ToString().Trim(); } else { _args.Add(word); } } private int GetNextOccuranceQualifier(string name, string[] aliases) { Debug.Assert(_args != null); Debug.Assert(_dashedParameterEncodedPositions != null); int ret = -1; string match = null; int encodedPos; if (_dashedParameterEncodedPositions.TryGetValue(name, out encodedPos)) { match = name; ret = GetPosition(encodedPos); } if (aliases != null) { foreach (string alias in aliases) { int aliasEncodedPos; if (_dashedParameterEncodedPositions.TryGetValue(alias, out aliasEncodedPos)) { int aliasPos = GetPosition(aliasEncodedPos); // if this alias occurs before the officialName or if no officialName was found // choose the alias as a match if (aliasPos < ret || ret == -1) { name = alias; encodedPos = aliasEncodedPos; ret = aliasPos; match = name; } } } } if (match != null) { if (!IsMulitple(encodedPos)) _dashedParameterEncodedPositions.Remove(match); else { int nextPos = -1; for (int i = ret + 1; i < _args.Count; i++) { if (string.Compare(ParseParameterName(_args[i]), name, StringComparison.OrdinalIgnoreCase) == 0) { nextPos = i; break; } } if (nextPos >= 0) _dashedParameterEncodedPositions[name] = SetMultiple(nextPos); else _dashedParameterEncodedPositions.Remove(name); } } return ret; } // Phase 2 parsing works into things that look like qualifiers (but without knowledge of which qualifiers the command supports) /// <summary> /// Find the locations of all arguments that look like named parameters. /// </summary> private void ParseWordsIntoQualifiers() { _dashedParameterEncodedPositions = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase); bool paramSetEncountered = false; string parameterSet = string.Empty; for (int i = 0; i < _args.Count; i++) { string arg = _args[i]; if (arg == null) continue; string name = ParseParameterName(arg); if (name != null) { if (IsDash(name[0])) { _args[i] = null; i++; string[] extraP = new string[_args.Count - i]; for (int j = 0; i < _args.Count; i++, j++) { extraP[j] = _args[i]; _args[i] = null; } _extraParameters = string.Join(" ", extraP); break; } if (name == "?") // Did the user request help? { _args[i] = null; if(paramSetEncountered) { _helpRequestedFor = parameterSet; } else { _helpRequestedFor = String.Empty; } /*if (i + 1 < _args.Count) { i++; _helpRequestedFor = _args[i]; _args[i] = null; }*/ _mustParseHelpStrings = true; break; } int position = i; if (_dashedParameterEncodedPositions.TryGetValue(name, out position)) position = SetMultiple(position); else position = i; _dashedParameterEncodedPositions[name] = position; if (!paramSetEncountered && !_noDashOnParameterSets && IsParameterSetWithqualifiersMustBeFirst(name)) break; } else { if (!paramSetEncountered) { if (_noDashOnParameterSets && IsParameterSetWithqualifiersMustBeFirst(arg)) break; else if (IsParameterSetWithqualifiersMustBeFirst(String.Empty)) // Then we are the default parameter set break; paramSetEncountered = true; // If we have hit a parameter, we must have hit a parameter set. parameterSet = arg; } } } } private bool IsParameterSetWithqualifiersMustBeFirst(string name) { if (_parameterSetsWhereQualifiersMustBeFirst != null) { foreach (string parameterSetName in _parameterSetsWhereQualifiersMustBeFirst) { if (string.Compare(name, parameterSetName, StringComparison.OrdinalIgnoreCase) == 0) return true; } } return false; } // Phase 3, processing user defintions of qualifiers, parameter sets, etc. /// <summary> /// returns the index in the 'args' array of the next instance of the 'name' qualifier. returns -1 if there is /// no next instance of the qualifer. /// </summary> private object DefineQualifier(string name, Type type, object qualifierValue, string helpText, bool isRequired, string defaultValue, List<string> legalValues) { Debug.Assert(_args != null); if (_dashedParameterEncodedPositions == null) ParseWordsIntoQualifiers(); _qualiferEncountered = true; if (_mustParseHelpStrings) AddHelp(new CommandLineParameter(name, qualifierValue, helpText, type, isRequired, false, false, legalValues, defaultValue)); if (_skipDefinitions) return null; if (_positionalArgEncountered && !_noSpaceOnQualifierValues) throw new CommandLineParserDesignerException("Definitions of Named parameters must come before definitions of positional parameters"); object ret = null; string[] alaises = null; if (_aliasDefinitions != null) _aliasDefinitions.TryGetValue(name, out alaises); int occurenceCount = 0; List<Array> arrayValues = null; for (;;) { int position = GetNextOccuranceQualifier(name, alaises); if (position < 0) break; string parameterStr = _args[position]; _args[position] = null; string value = null; int colonIdx = parameterStr.IndexOfAny(s_separators); if (colonIdx >= 0) value = parameterStr.Substring(colonIdx + 1); if (type == typeof(bool) || type == typeof(bool?)) { if (value == null) value = "true"; else if (value == String.Empty) value = "false"; } else if (value == null) { /*int valuePos = position + 1; if (_noSpaceOnQualifierValues || valuePos >= _args.Count || _args[valuePos] == null) { string message = "Parameter " + name + " is missing a value."; if (_noSpaceOnQualifierValues) message += " The syntax -" + name + ":<value> must be used."; throw new CommandLineParserException(message); } value = _args[valuePos]; // Note that I don't absolutely need to exclude values that look like qualifiers, but it does // complicate the code, and also leads to confusing error messages when we parse the command // in a very different way then the user is expecting. Since you can provide values that // begin with a '-' by doing -qualifier:-value instead of -qualifier -value I force the issue // by excluding it here. TODO: this makes negative numbers harder... if (value.Length > 0 && IsQualifier(value)) throw new CommandLineParserException("Use " + name + ":" + value + " if " + value + " is meant to be value rather than a named parameter"); _args[valuePos] = null;*/ value = string.IsNullOrEmpty(defaultValue) ? "true" : defaultValue; } ret = ParseValue(value, type, name); if (type.IsArray) { if (arrayValues == null) arrayValues = new List<Array>(); arrayValues.Add((Array)ret); ret = null; } else if (occurenceCount > 0 && !_lastQualifierWins) throw new CommandLineParserException("Parameter " + name + " specified more than once."); occurenceCount++; } if (occurenceCount == 0 && isRequired) throw new CommandLineParserException("Required named parameter " + name + " not present."); if (arrayValues != null) ret = ConcatenateArrays(type, arrayValues); return ret; } private object DefineParameter(string name, Type type, object parameterValue, string helpText, bool isRequired) { Debug.Assert(_args != null); if (_dashedParameterEncodedPositions == null) ParseWordsIntoQualifiers(); if (!isRequired) _optionalPositionalArgEncountered = true; else if (_optionalPositionalArgEncountered) throw new CommandLineParserDesignerException("Optional positional parameters can't precede required positional parameters"); _positionalArgEncountered = true; if (_mustParseHelpStrings) AddHelp(new CommandLineParameter(name, parameterValue, helpText, type, isRequired, true, false, null)); if (_skipDefinitions) return null; // Skip any nulled out args (things that used to be named parameters) while (_curPosition < _args.Count && _args[_curPosition] == null) _curPosition++; object ret = null; if (type.IsArray) { // Pass 1, Get the count int count = 0; int argPosition = _curPosition; while (argPosition < _args.Count) if (_args[argPosition++] != null) count++; if (count == 0 && isRequired) throw new CommandLineParserException("Required positional parameter " + name + " not present."); Type elementType = type.GetElementType(); Array array = Array.CreateInstance(elementType, count); argPosition = _curPosition; int index = 0; while (argPosition < _args.Count) { string arg = _args[argPosition++]; if (arg != null) array.SetValue(ParseValue(arg, elementType, name), index++); } _curPosition = _args.Count; ret = array; } else if (_curPosition < _args.Count) // A 'normal' positional parameter with a value { ret = ParseValue(_args[_curPosition++], type, name); } else // No value { if (isRequired) throw new CommandLineParserException("Required positional parameter " + name + " not present."); } return ret; } private bool DefineParameterSet(string name, string helpText) { Debug.Assert(_args != null); if (_dashedParameterEncodedPositions == null) ParseWordsIntoQualifiers(); if (!_paramSetEncountered && _positionalArgEncountered) throw new CommandLineParserDesignerException("Positional parameters must not preceed parameter set definitions."); _paramSetEncountered = true; _positionalArgEncountered = false; // each parameter set gets a new arg set _optionalPositionalArgEncountered = false; if (_defaultParamSetEncountered) throw new CommandLineParserDesignerException("The default parameter set must be defined last."); bool isDefaultParameterSet = (name.Length == 0); if (isDefaultParameterSet) _defaultParamSetEncountered = true; if (_mustParseHelpStrings) AddHelp(new CommandLineParameter(name, null, helpText, typeof(bool), true, _noDashOnParameterSets, true, null)); if (_skipParameterSets) return false; // Have we just finish with the parameter set that was actually on the command line? if (_parameterSetName != null) { _skipDefinitions = true; _skipParameterSets = true; // if yes, we are done, ignore all parameter set definitions. return false; } bool ret = isDefaultParameterSet; if (!isDefaultParameterSet) { for (int i = 0; i < _args.Count; i++) { string arg = _args[i]; if (arg == null) continue; if (IsQualifier(arg)) { if (!_noDashOnParameterSets && string.Compare(arg, 1, name, 0, int.MaxValue, StringComparison.OrdinalIgnoreCase) == 0) { _dashedParameterEncodedPositions.Remove(name); _args[i] = null; ret = true; _parameterSetName = name; break; } } else { if (_noDashOnParameterSets && (string.Compare(arg, name, StringComparison.OrdinalIgnoreCase) == 0)) { _args[i] = null; ret = true; _parameterSetName = name; } break; } } } _skipDefinitions = !((_parameterSetName != null) || isDefaultParameterSet); // To avoid errors when users ask for help, skip any parsing once we have found a parameter set. if (_helpRequestedFor != null && ret) { _skipDefinitions = true; _skipParameterSets = true; } return ret; } private Array ConcatenateArrays(Type arrayType, List<Array> arrays) { int totalCount = 0; for (int i = 0; i < arrays.Count; i++) totalCount += arrays[i].Length; Type elementType = arrayType.GetElementType(); Array ret = Array.CreateInstance(elementType, totalCount); int pos = 0; for (int i = 0; i < arrays.Count; i++) { Array source = arrays[i]; for (int j = 0; j < source.Length; j++) ret.SetValue(source.GetValue(j), pos++); } return ret; } // Phase 3A, parsing qualifer strings into a .NET type (int, enums, ... private object ParseValue(string valueString, Type type, string parameterName) { try { if (type == typeof(string)) return valueString; else if (type == typeof(bool)) return bool.Parse(valueString); else if (type == typeof(int)) { if (valueString.Length > 2 && valueString[0] == '0' && (valueString[1] == 'x' || valueString[1] == 'X')) return int.Parse(valueString.Substring(2), System.Globalization.NumberStyles.AllowHexSpecifier); else return int.Parse(valueString); } else if (type.GetTypeInfo().IsEnum) return ParseCompositeEnumValue(valueString, type, parameterName); else if (type == typeof(string[])) return valueString.Split(','); else if (type.IsArray) { // TODO I need some way of handling string with , in them. Type elementType = type.GetElementType(); string[] elementStrings = valueString.Split(','); Array array = Array.CreateInstance(elementType, elementStrings.Length); for (int i = 0; i < elementStrings.Length; i++) array.SetValue(ParseValue(elementStrings[i], elementType, parameterName), i); return array; } else if (type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) { if (valueString.Length == 0) return null; return ParseValue(valueString, type.GetGenericArguments()[0], parameterName); } else { System.Reflection.MethodInfo parseMethod = type.GetMethod("Parse", new Type[] { typeof(string) }); if (parseMethod == null) throw new CommandLineParserException("Could not find a parser for type " + type.Name + " for parameter " + parameterName); return parseMethod.Invoke(null, new object[] { valueString }); } } catch (CommandLineParserException) { throw; } catch (Exception e) { if (e is System.Reflection.TargetInvocationException) e = e.InnerException; string paramStr = String.Empty; if (parameterName != null) paramStr = " for parameter " + parameterName; if (e is FormatException) throw new CommandLineParserException("The value '" + valueString + "' can not be parsed to a " + type.Name + paramStr + "."); else throw new CommandLineParserException("Failure while converting '" + valueString + "' to a " + type.Name + paramStr + "."); } } /// <summary> /// Enums that are bitfields can have multiple values. Support + and - (for oring and diffing bits). Returns /// the final enum value. for the 'valueString' which is a string form of 'type' for the parameter 'parameter'. /// </summary> private object ParseCompositeEnumValue(string valueString, Type type, string parameterName) { bool knownToBeFlagsEnum = false; long retValue = 0; int curIdx = 0; bool negate = false; while (curIdx < valueString.Length) { int nextIdx = valueString.IndexOfAny(new char[] { ',', '+', '-' }, curIdx); if (nextIdx < 0) nextIdx = valueString.Length; object nextValue = ParseSimpleEnumValue(valueString.Substring(curIdx, nextIdx - curIdx), type, parameterName); if (curIdx == 0 && nextIdx == valueString.Length) return nextValue; if (!knownToBeFlagsEnum) { if (!type.GetTypeInfo().IsDefined(typeof(FlagsAttribute))) { string paramStr = String.Empty; if (parameterName != null) paramStr = " for parameter " + parameterName; throw new CommandLineParserException("The value '" + valueString + paramStr + " can't have the + or - operators."); } knownToBeFlagsEnum = true; } long newValue; if (Enum.GetUnderlyingType(type) == typeof(long)) newValue = (long)nextValue; else newValue = (int)nextValue; if (negate) retValue &= ~newValue; else retValue |= newValue; negate = (nextIdx < valueString.Length && valueString[nextIdx] == '-'); curIdx = nextIdx + 1; } return Enum.ToObject(type, retValue); } private object ParseSimpleEnumValue(string valueString, Type type, string parameterName) { try { if (valueString.StartsWith("0x")) { if (Enum.GetUnderlyingType(type) == typeof(long)) return long.Parse(valueString.Substring(2), System.Globalization.NumberStyles.HexNumber); return int.Parse(valueString.Substring(2), System.Globalization.NumberStyles.HexNumber); } return Enum.Parse(type, valueString, ignoreCase: true); } catch (ArgumentException) { string paramStr = String.Empty; if (parameterName != null) paramStr = " for parameter " + parameterName; StringBuilder sb = new StringBuilder(); sb.Append("The value '").Append(valueString).Append("'").Append(paramStr).Append(" is not a member of the enumeration ").Append(type.Name).Append(".").AppendLine(); sb.Append("The legal values are either a decimal integer, 0x and a hex integer or").AppendLine(); foreach (string name in Enum.GetNames(type)) sb.Append(" ").Append(name).AppendLine(); if (type.GetTypeInfo().IsDefined(typeof(FlagsAttribute))) sb.Append("The + and - operators can be used to combine the values.").AppendLine(); throw new CommandLineParserException(sb.ToString()); } } private StringBuilder GetIntroTextForHelp(int maxLineWidth) { string appName = GetEntryAssemblyName(); StringBuilder sb = new StringBuilder(); sb.AppendLine(); string text = "The Run Command Tool is now in charge of running the dev workflow steps. Each step has its own command and set of actions that are listed below. " + "You could also pass Global Settings to the commands."; Wrap(sb, text, 0, String.Empty, maxLineWidth, true); text = "To pass additional parameters that are not described in the Global Settings section, use `--`. After this command, the Run Command Tool will stop processing arguments and will pass all the information as it is to the selected command."; Wrap(sb, text, 0, String.Empty, maxLineWidth, true); text = "The information comes from a config.json file. By default the file is in the root of the repo. Otherwise the first parameter should be the path to the config.json file."; Wrap(sb, text, 0, String.Empty, maxLineWidth, true); text = "For more information about the Run Command Tool: https://github.com/dotnet/buildtools/blob/master/Documentation/RunCommand.md"; Wrap(sb, text, 0, String.Empty, maxLineWidth, true); sb.AppendLine().AppendLine().Append("Syntax: run [Command] [Action] (global settings)"); sb.AppendLine().Append('-', maxLineWidth - 1).AppendLine(); return sb; } /// <summary> /// Return a string giving the help for the command, word wrapped at 'maxLineWidth' /// </summary> private string GetFullHelp(int maxLineWidth) { // Do we have non-default parameter sets? bool hasParamSets = false; foreach (CommandLineParameter parameter in _parameterDescriptions) { if (parameter.IsParameterSet && parameter.Name != String.Empty) { hasParamSets = true; break; } } if (!hasParamSets) return GetHelp(maxLineWidth, String.Empty, true); StringBuilder sb = new StringBuilder(); // Always print the default parameter set first. if (_defaultParamSetEncountered) { sb.Append(GetHelp(maxLineWidth, String.Empty, false)); } foreach (CommandLineParameter parameter in _parameterDescriptions) { if (parameter.IsParameterSet && parameter.Name.Length != 0) { sb.Append(GetHelp(maxLineWidth, parameter.Name, false)); } } string globalQualifiers = GetHelpGlobalQualifiers(maxLineWidth); if (globalQualifiers.Length > 0) { sb.AppendLine().Append('-', maxLineWidth - 1).AppendLine(); sb.Append("Global settings to all commands:").AppendLine(); sb.AppendLine(); sb.Append(globalQualifiers); } return sb.ToString(); } /// <summary> /// prints a string to the console in a nice way. In particular it /// displays a screen full of data and then ask user to type Enter to continue. /// </summary> /// <param name="helpString"></param> private static void DisplayStringToConsole(string helpString) { // TODO we do paging, but this is not what we want when it is redirected. bool first = true; for (int pos = 0; ;) { int nextPos = pos; int numLines = (first ? GetConsoleHeight() - 2 : GetConsoleHeight() * 3 / 4) - 1; first = false; for (int j = 0; j < numLines; j++) { int search = helpString.IndexOf("\r\n", nextPos) + 2; if (search >= 2) nextPos = search; else nextPos = helpString.Length; } Console.Write(helpString.Substring(pos, nextPos - pos)); if (nextPos == helpString.Length) break; Console.Write("[Press Enter to continue...]"); Console.Read(); Console.Write("\r \r"); pos = nextPos; } } private void AddHelp(CommandLineParameter parameter) { if (_parameterDescriptions == null) _parameterDescriptions = new List<CommandLineParameter>(); _parameterDescriptions.Add(parameter); } private static void ParameterHelp(CommandLineParameter parameter, StringBuilder sb, int firstColumnWidth, int maxLineWidth) { // TODO alias information. sb.Append(parameter.Syntax().PadRight(firstColumnWidth)); string helpText = parameter.HelpText; string defValue = string.Empty; bool shouldPrint = true; // Bool type implied on named parameters if (parameter.IsNamed && parameter.Type == typeof(bool)) { shouldPrint = false; if (parameter.Value != null && (bool)parameter.Value) shouldPrint = false; } if (shouldPrint) { if (!string.IsNullOrEmpty(parameter.DefaultValue)) { helpText += "\n=> Default value: " + parameter.DefaultValue.ToString(); } } if (parameter.LegalValues.Count > 0) helpText = helpText + "\n=> Legal values: [" + string.Join(", ", parameter.LegalValues) + "]."; Wrap(sb, helpText, firstColumnWidth, new string(' ', firstColumnWidth), maxLineWidth, true); } private static void Wrap(StringBuilder sb, string text, int startColumn, string linePrefix, int maxLineWidth, bool first) { if (text != null) { //bool first = true; int column = startColumn; string previousWord = String.Empty; string[] paragraphs = text.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries); foreach (string paragraph in paragraphs) { if (!first) { column = 0; linePrefix = new string(' ', startColumn); } string[] words = paragraph.Split((char[])null, StringSplitOptions.RemoveEmptyEntries); // Split on whitespace foreach (string word in words) { if (column + word.Length >= maxLineWidth) { sb.AppendLine(); column = 0; } if (column == 0) { sb.Append(linePrefix); column = linePrefix.Length; } else if (!first) { // add an extra space at the end of sentences. if (previousWord.Length > 0 && previousWord[previousWord.Length - 1] == '.') { sb.Append(' '); column++; } sb.Append(' '); column++; } sb.Append(word); previousWord = word; column += word.Length; first = false; } sb.AppendLine(); } } sb.AppendLine(); } private string GetHelpGlobalQualifiers(int maxLineWidth) { if (!_paramSetEncountered) return String.Empty; StringBuilder sb = new StringBuilder(); for (int i = 0; i < _parameterDescriptions.Count; i++) { CommandLineParameter parameter = _parameterDescriptions[i]; if (parameter.IsParameterSet) break; if (parameter.IsNamed) ParameterHelp(parameter, sb, GlobalQualifierSyntaxWidth, maxLineWidth); } return sb.ToString(); } private static int GetConsoleWidth() { return 120; // Can't retrieve console width in .NET Core } private static int GetConsoleHeight() { return 100; // Can't retrieve console height in .NET Core } private static string GetEntryAssemblyName() { Assembly entryAssembly = Assembly.GetEntryAssembly(); if (entryAssembly != null) { return Path.GetFileNameWithoutExtension(entryAssembly.ManifestModule.Name); } else { return string.Empty; } } // TODO expose the ability to change this? private static char[] s_separators = new char[] { ':', '=' }; // tweaks the user can specify private bool _noDashOnParameterSets = true; private bool _noSpaceOnQualifierValues; private string[] _parameterSetsWhereQualifiersMustBeFirst; private bool _qualifiersUseOnlyDash = true; private bool _lastQualifierWins; private static string _extraParameters; // In order to produce help, we need to remember everything useful about all the parameters. This list // does this. It is only done when help is needed, so it is not here in the common scenario. private List<CommandLineParameter> _parameterDescriptions; private int _qualifierSyntaxWidth; // When printing help, how much indent any line wraps. private int _globalQualifierSyntaxWidth; public int QualifierSyntaxWidth { get { // Find the optimal size for the 'first column' of the help text. if (_qualifierSyntaxWidth == 0) { _qualifierSyntaxWidth = 35; if (_parameterDescriptions != null) { int maxSyntaxWidth = 0; bool qualifierStart = false; foreach (CommandLineParameter parameter in _parameterDescriptions) { if (parameter.IsParameterSet) { qualifierStart = true; } if(qualifierStart) { maxSyntaxWidth = Math.Max(maxSyntaxWidth, parameter.Syntax().Length); } } _qualifierSyntaxWidth = Math.Max(8, maxSyntaxWidth + 2); // +2 leaves two extra spaces } } return _qualifierSyntaxWidth; } } public int GlobalQualifierSyntaxWidth { get { // Find the optimal size for the 'first column' of the help text. if (_globalQualifierSyntaxWidth == 0) { _globalQualifierSyntaxWidth = 35; if (_parameterDescriptions != null) { int maxSyntaxWidth = 0; foreach (CommandLineParameter parameter in _parameterDescriptions) { if (parameter.IsParameterSet) break; maxSyntaxWidth = Math.Max(maxSyntaxWidth, parameter.Syntax().Length); } _globalQualifierSyntaxWidth = Math.Max(8, maxSyntaxWidth + 2); // +2 leaves two extra spaces } } return _globalQualifierSyntaxWidth; } } /// <summary> /// Qualifiers can have aliases (e.g. for short names). This holds these aliases. /// </summary> private Dictionary<string, string[]> _aliasDefinitions; // Often null if no aliases are defined. // Because we do all the parsing for a single parameter at once, it is useful to know quickly if the // parameter even exists, exists once, or exist more than once. This dictionary holds this. It is // initialized in code:PreParseQualifiers. The value in this dictionary is an ecncoded position // which encodes both the position and whether this qualifer occurs multiple times (see GetMultiple, // GetPosition, IsMultiple methods). private Dictionary<string, int> _dashedParameterEncodedPositions; // We steal the top bit to prepresent whether the parameter occurs more than once. private const int MultiplePositions = unchecked((int)0x80000000); private static int SetMultiple(int encodedPos) { return encodedPos | MultiplePositions; } private static int GetPosition(int encodedPos) { return encodedPos & ~MultiplePositions; } private static bool IsMulitple(int encodedPos) { return (encodedPos & MultiplePositions) != 0; } // As we parse qualifiers we remove them from the command line by nulling them out, and thus // ultimately ends up only having positional parameters being non-null. private List<string> _args; private Setup _setupContent; private int _curPosition; // All arguments before this position have been processed. private bool _skipParameterSets; // Have we found the parameter set qualifer, so we don't look at any others. private bool _skipDefinitions; // Should we skip all subsequent definitions (typically until the next parameter set def) private string _parameterSetName; // if we matched a parameter set, this is it. private bool _mustParseHelpStrings; // we have to go to the overhead of parsing the help strings (because user wants help) private string _helpRequestedFor; // The user specified /? on the command line. This is the word after the /? may be empty private bool _seenExeArg; // Used in AddWord, indicates we have seen the exe itself (before the args) on the command line private bool _paramSetEncountered; private bool _defaultParamSetEncountered; private bool _positionalArgEncountered; private bool _optionalPositionalArgEncountered; private bool _qualiferEncountered; #endregion } /// <summary> /// Run time parsing error throw this exception. These are expected to be caught and the error message /// printed out to the user. Thus the messages should be 'user friendly'. /// </summary> public class CommandLineParserException : Exception { public CommandLineParserException(string message) : base(message) { } } /// <summary> /// This exception represents a compile time error in the command line parsing. These should not happen in /// correctly written programs. /// </summary> public class CommandLineParserDesignerException : Exception { public CommandLineParserDesignerException(string message) : base(message) { } } }
1
11,895
Thanks for fixing the typo's but given that this is a fork of the other commandline.cs file they will still exist there :( Part of the reason forks suck.
dotnet-buildtools
.cs
@@ -141,8 +141,14 @@ import datetime import itertools import logging import luigi -import sqlalchemy import os +import warnings + +try: + import sqlalchemy +except ImportError: + # Don't fail on import because we want the documentation to be generated + warnings.warn("sqlalchemy could not be imported, db_task_history will not work", warnings.ImportWarning, stacklevel=3) class SQLAlchemyTarget(luigi.Target):
1
# -*- coding: utf-8 -*- # # Copyright (c) 2015 Gouthaman Balaraman # # 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. # """ Support for SQLAlchmey. Provides SQLAlchemyTarget for storing in databases supported by SQLAlchemy. The user would be responsible for installing the required database driver to connect using SQLAlchemy. Minimal example of a job to copy data to database using SQLAlchemy is as shown below: .. code-block:: python from sqlalchemy import String import luigi from luigi.contrib import sqla class SQLATask(sqla.CopyToTable): # columns defines the table schema, with each element corresponding # to a column in the format (args, kwargs) which will be sent to # the sqlalchemy.Column(*args, **kwargs) columns = [ (["item", String(64)], {"primary_key": True}), (["property", String(64)], {}) ] connection_string = "sqlite://" # in memory SQLite database table = "item_property" # name of the table to store data def rows(self): for row in [("item1" "property1"), ("item2", "property2")]: yield row if __name__ == '__main__': task = SQLATask() luigi.build([task], local_scheduler=True) If the target table where the data needs to be copied already exists, then the column schema definition can be skipped and instead the reflect flag can be set as True. Here is a modified version of the above example: .. code-block:: python from sqlalchemy import String import luigi from luigi.contrib import sqla class SQLATask(sqla.CopyToTable): # If database table is already created, then the schema can be loaded # by setting the reflect flag to True reflect = True connection_string = "sqlite://" # in memory SQLite database table = "item_property" # name of the table to store data def rows(self): for row in [("item1" "property1"), ("item2", "property2")]: yield row if __name__ == '__main__': task = SQLATask() luigi.build([task], local_scheduler=True) In the above examples, the data that needs to be copied was directly provided by overriding the rows method. Alternately, if the data comes from another task, the modified example would look as shown below: .. code-block:: python from sqlalchemy import String import luigi from luigi.contrib import sqla from luigi.mock import MockFile class BaseTask(luigi.Task): def output(self): return MockFile("BaseTask") def run(self): out = self.output().open("w") TASK_LIST = ["item%d\\tproperty%d\\n" % (i, i) for i in range(10)] for task in TASK_LIST: out.write(task) out.close() class SQLATask(sqla.CopyToTable): # columns defines the table schema, with each element corresponding # to a column in the format (args, kwargs) which will be sent to # the sqlalchemy.Column(*args, **kwargs) columns = [ (["item", String(64)], {"primary_key": True}), (["property", String(64)], {}) ] connection_string = "sqlite://" # in memory SQLite database table = "item_property" # name of the table to store data def requires(self): return BaseTask() if __name__ == '__main__': task1, task2 = SQLATask(), BaseTask() luigi.build([task1, task2], local_scheduler=True) In the above example, the output from `BaseTask` is copied into the database. Here we did not have to implement the `rows` method because by default `rows` implementation assumes every line is a row with column values separated by a tab. One can define `column_separator` option for the task if the values are say comma separated instead of tab separated. The other option to `sqla.CopyToTable` that can be of help with performance aspect is the `chunk_size`. The default is 5000. This is the number of rows that will be inserted in a transaction at a time. Depending on the size of the inserts, this value can be tuned for performance. See here for a `tutorial on building task pipelines using luigi <http://gouthamanbalaraman.com/blog/building-luigi-task-pipeline.html>`_ and using `SQLAlchemy in workflow pipelines <http://gouthamanbalaraman.com/blog/sqlalchemy-luigi-workflow-pipeline.html>`_. Author: Gouthaman Balaraman Date: 01/02/2015 """ import abc import datetime import itertools import logging import luigi import sqlalchemy import os class SQLAlchemyTarget(luigi.Target): """ Database target using SQLAlchemy. This will rarely have to be directly instantiated by the user. Typical usage would be to override `luigi.contrib.sqla.CopyToTable` class to create a task to write to the database. """ marker_table = None _engine = None # sqlalchemy engine _pid = None # the pid of the sqlalchemy engine object def __init__(self, connection_string, target_table, update_id, echo=False): """ Constructor for the SQLAlchemyTarget. :param connection_string: SQLAlchemy connection string :type connection_string: str :param target_table: The table name for the data :type target_table: str :param update_id: An identifier for this data set :type update_id: str :param echo: Flag to setup SQLAlchemy logging :type echo: bool :return: """ self.target_table = target_table self.update_id = update_id self.connection_string = connection_string self.echo = echo self.marker_table_bound = None @property def engine(self): pid = os.getpid() if (SQLAlchemyTarget._engine is None) or (SQLAlchemyTarget._pid != pid): SQLAlchemyTarget._engine = sqlalchemy.create_engine(self.connection_string, echo=self.echo) SQLAlchemyTarget._pid = pid return SQLAlchemyTarget._engine def touch(self): """ Mark this update as complete. """ if self.marker_table_bound is None: self.create_marker_table() table = self.marker_table_bound id_exists = self.exists() with self.engine.begin() as conn: if not id_exists: ins = table.insert().values(update_id=self.update_id, target_table=self.target_table, inserted=datetime.datetime.now()) else: ins = table.update().where(sqlalchemy.and_(table.c.update_id == self.update_id, table.c.target_table == self.target_table)).\ values(update_id=self.update_id, target_table=self.target_table, inserted=datetime.datetime.now()) conn.execute(ins) assert self.exists() def exists(self): row = None if self.marker_table_bound is None: self.create_marker_table() with self.engine.begin() as conn: table = self.marker_table_bound s = sqlalchemy.select([table]).where(sqlalchemy.and_(table.c.update_id == self.update_id, table.c.target_table == self.target_table)).limit(1) row = conn.execute(s).fetchone() return row is not None def create_marker_table(self): """ Create marker table if it doesn't exist. Using a separate connection since the transaction might have to be reset. """ if self.marker_table is None: self.marker_table = luigi.configuration.get_config().get('sqlalchemy', 'marker-table', 'table_updates') engine = self.engine with engine.begin() as con: metadata = sqlalchemy.MetaData() if not con.dialect.has_table(con, self.marker_table): self.marker_table_bound = sqlalchemy.Table( self.marker_table, metadata, sqlalchemy.Column("update_id", sqlalchemy.String(128), primary_key=True), sqlalchemy.Column("target_table", sqlalchemy.String(128)), sqlalchemy.Column("inserted", sqlalchemy.DateTime, default=datetime.datetime.now())) metadata.create_all(engine) else: metadata.reflect(bind=engine) self.marker_table_bound = metadata.tables[self.marker_table] def open(self, mode): raise NotImplementedError("Cannot open() SQLAlchemyTarget") class CopyToTable(luigi.Task): """ An abstract task for inserting a data set into SQLAlchemy RDBMS Usage: * subclass and override the required `connection_string`, `table` and `columns` attributes. """ _logger = logging.getLogger('luigi-interface') echo = False @abc.abstractmethod def connection_string(self): return None @abc.abstractproperty def table(self): return None # specify the columns that define the schema. The format for the columns is a list # of tuples. For example : # columns = [ # (["id", sqlalchemy.Integer], dict(primary_key=True)), # (["name", sqlalchemy.String(64)], {}), # (["value", sqlalchemy.String(64)], {}) # ] # The tuple (args_list, kwargs_dict) here is the args and kwargs # that need to be passed to sqlalchemy.Column(*args, **kwargs). # If the tables have already been setup by another process, then you can # completely ignore the columns. Instead set the reflect value to True below columns = [] # options column_separator = "\t" # how columns are separated in the file copied into postgres chunk_size = 5000 # default chunk size for insert reflect = False # Set this to true only if the table has already been created by alternate means def create_table(self, engine): """ Override to provide code for creating the target table. By default it will be created using types specified in columns. If the table exists, then it binds to the existing table. If overridden, use the provided connection object for setting up the table in order to create the table and insert data using the same transaction. :param engine: The sqlalchemy engine instance :type engine: object """ def construct_sqla_columns(columns): retval = [sqlalchemy.Column(*c[0], **c[1]) for c in columns] return retval needs_setup = (len(self.columns) == 0) or (False in [len(c) == 2 for c in self.columns]) if not self.reflect else False if needs_setup: # only names of columns specified, no types raise NotImplementedError("create_table() not implemented for %r and columns types not specified" % self.table) else: # if columns is specified as (name, type) tuples with engine.begin() as con: metadata = sqlalchemy.MetaData() try: if not con.dialect.has_table(con, self.table): sqla_columns = construct_sqla_columns(self.columns) self.table_bound = sqlalchemy.Table(self.table, metadata, *sqla_columns) metadata.create_all(engine) else: metadata.reflect(bind=engine) self.table_bound = metadata.tables[self.table] except Exception as e: self._logger.exception(self.table + str(e)) def update_id(self): """ This update id will be a unique identifier for this insert on this table. """ return self.task_id def output(self): return SQLAlchemyTarget( connection_string=self.connection_string, target_table=self.table, update_id=self.update_id(), echo=self.echo) def rows(self): """ Return/yield tuples or lists corresponding to each row to be inserted. This method can be overridden for custom file types or formats. """ with self.input().open('r') as fobj: for line in fobj: yield line.strip("\n").split(self.column_separator) def run(self): self._logger.info("Running task copy to table for update id %s for table %s" % (self.update_id(), self.table)) output = self.output() engine = output.engine self.create_table(engine) with engine.begin() as conn: rows = iter(self.rows()) ins_rows = [dict(zip(("_" + c.key for c in self.table_bound.c), row)) for row in itertools.islice(rows, self.chunk_size)] while ins_rows: self.copy(conn, ins_rows, self.table_bound) ins_rows = [dict(zip(("_" + c.key for c in self.table_bound.c), row)) for row in itertools.islice(rows, self.chunk_size)] self._logger.info("Finished inserting %d rows into SQLAlchemy target" % len(ins_rows)) output.touch() self._logger.info("Finished inserting rows into SQLAlchemy target") def copy(self, conn, ins_rows, table_bound): """ This method does the actual insertion of the rows of data given by ins_rows into the database. A task that needs row updates instead of insertions should overload this method. :param conn: The sqlalchemy connection object :param ins_rows: The dictionary of rows with the keys in the format _<column_name>. For example if you have a table with a column name "property", then the key in the dictionary would be "_property". This format is consistent with the bindparam usage in sqlalchemy. :param table_bound: The object referring to the table :return: """ bound_cols = dict((c, sqlalchemy.bindparam("_" + c.key)) for c in table_bound.columns) ins = table_bound.insert().values(bound_cols) conn.execute(ins, ins_rows)
1
11,162
This doesn't seem related to docs? :)
spotify-luigi
py
@@ -233,7 +233,7 @@ public class K9 extends Application { private static boolean hideSpecialAccounts = false; private static boolean autofitWidth; private static boolean quietTimeEnabled = false; - private static boolean notificationDuringQuietTimeEnabled = true; + private static boolean notificationDuringQuietTimeDisabled = true; private static String quietTimeStarts = null; private static String quietTimeEnds = null; private static String attachmentDefaultPath = "";
1
package com.fsck.k9; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.BlockingQueue; import java.util.concurrent.SynchronousQueue; import android.app.Application; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.pm.PackageManager; import android.net.Uri; import android.os.AsyncTask; import android.os.Environment; import android.os.Handler; import android.os.Looper; import android.os.StrictMode; import com.fsck.k9.Account.SortType; import com.fsck.k9.activity.MessageCompose; import com.fsck.k9.activity.UpgradeDatabases; import com.fsck.k9.controller.MessagingController; import com.fsck.k9.controller.SimpleMessagingListener; import com.fsck.k9.mail.Address; import com.fsck.k9.mail.K9MailLib; import com.fsck.k9.mail.Message; import com.fsck.k9.mail.internet.BinaryTempFileBody; import com.fsck.k9.mail.ssl.LocalKeyStore; import com.fsck.k9.mailstore.LocalStore; import com.fsck.k9.power.DeviceIdleManager; import com.fsck.k9.preferences.Storage; import com.fsck.k9.preferences.StorageEditor; import com.fsck.k9.service.BootReceiver; import com.fsck.k9.service.MailService; import com.fsck.k9.service.ShutdownReceiver; import com.fsck.k9.service.StorageGoneReceiver; import com.fsck.k9.widget.list.MessageListWidgetProvider; import com.fsck.k9.widget.unread.UnreadWidgetUpdater; import timber.log.Timber; import timber.log.Timber.DebugTree; public class K9 extends Application { public static final int VERSION_MIGRATE_OPENPGP_TO_ACCOUNTS = 63; /** * Components that are interested in knowing when the K9 instance is * available and ready (Android invokes Application.onCreate() after other * components') should implement this interface and register using * {@link K9#registerApplicationAware(ApplicationAware)}. */ public static interface ApplicationAware { /** * Called when the Application instance is available and ready. * * @param application * The application instance. Never <code>null</code>. * @throws Exception */ void initializeComponent(Application application); } public static Application app = null; public static File tempDirectory; public static final String LOG_TAG = "k9"; /** * Name of the {@link SharedPreferences} file used to store the last known version of the * accounts' databases. * * <p> * See {@link UpgradeDatabases} for a detailed explanation of the database upgrade process. * </p> */ private static final String DATABASE_VERSION_CACHE = "database_version_cache"; /** * Key used to store the last known database version of the accounts' databases. * * @see #DATABASE_VERSION_CACHE */ private static final String KEY_LAST_ACCOUNT_DATABASE_VERSION = "last_account_database_version"; /** * Components that are interested in knowing when the K9 instance is * available and ready. * * @see ApplicationAware */ private static final List<ApplicationAware> observers = new ArrayList<ApplicationAware>(); /** * This will be {@code true} once the initialization is complete and {@link #notifyObservers()} * was called. * Afterwards calls to {@link #registerApplicationAware(com.fsck.k9.K9.ApplicationAware)} will * immediately call {@link com.fsck.k9.K9.ApplicationAware#initializeComponent(Application)} for the * supplied argument. */ private static boolean initialized = false; public enum BACKGROUND_OPS { ALWAYS, NEVER, WHEN_CHECKED_AUTO_SYNC } private static String language = ""; private static Theme theme = Theme.LIGHT; private static Theme messageViewTheme = Theme.USE_GLOBAL; private static Theme composerTheme = Theme.USE_GLOBAL; private static boolean useFixedMessageTheme = true; private static final FontSizes fontSizes = new FontSizes(); private static BACKGROUND_OPS backgroundOps = BACKGROUND_OPS.WHEN_CHECKED_AUTO_SYNC; /** * Some log messages can be sent to a file, so that the logs * can be read using unprivileged access (eg. Terminal Emulator) * on the phone, without adb. Set to null to disable */ public static final String logFile = null; //public static final String logFile = Environment.getExternalStorageDirectory() + "/k9mail/debug.log"; /** * If this is enabled, various development settings will be enabled * It should NEVER be on for Market builds * Right now, it just governs strictmode **/ public static boolean DEVELOPER_MODE = BuildConfig.DEVELOPER_MODE; /** * If this is enabled there will be additional logging information sent to * Log.d, including protocol dumps. * Controlled by Preferences at run-time */ private static boolean DEBUG = false; /** * If this is enabled than logging that normally hides sensitive information * like passwords will show that information. */ public static boolean DEBUG_SENSITIVE = false; /** * A reference to the {@link SharedPreferences} used for caching the last known database * version. * * @see #checkCachedDatabaseVersion() * @see #setDatabasesUpToDate(boolean) */ private static SharedPreferences databaseVersionCache; private static boolean animations = true; private static boolean confirmDelete = false; private static boolean confirmDiscardMessage = true; private static boolean confirmDeleteStarred = false; private static boolean confirmSpam = false; private static boolean confirmDeleteFromNotification = true; private static boolean confirmMarkAllRead = true; private static NotificationHideSubject notificationHideSubject = NotificationHideSubject.NEVER; /** * Controls when to hide the subject in the notification area. */ public enum NotificationHideSubject { ALWAYS, WHEN_LOCKED, NEVER } private static NotificationQuickDelete notificationQuickDelete = NotificationQuickDelete.NEVER; /** * Controls behaviour of delete button in notifications. */ public enum NotificationQuickDelete { ALWAYS, FOR_SINGLE_MSG, NEVER } private static LockScreenNotificationVisibility sLockScreenNotificationVisibility = LockScreenNotificationVisibility.MESSAGE_COUNT; public enum LockScreenNotificationVisibility { EVERYTHING, SENDERS, MESSAGE_COUNT, APP_NAME, NOTHING } /** * Controls when to use the message list split view. */ public enum SplitViewMode { ALWAYS, NEVER, WHEN_IN_LANDSCAPE } private static boolean messageListCheckboxes = true; private static boolean messageListStars = true; private static int messageListPreviewLines = 2; private static boolean showCorrespondentNames = true; private static boolean messageListSenderAboveSubject = false; private static boolean showContactName = false; private static boolean changeContactNameColor = false; private static int contactNameColor = 0xff00008f; private static boolean showContactPicture = true; private static boolean messageViewFixedWidthFont = false; private static boolean messageViewReturnToList = false; private static boolean messageViewShowNext = false; private static boolean gesturesEnabled = true; private static boolean useVolumeKeysForNavigation = false; private static boolean useVolumeKeysForListNavigation = false; private static boolean startIntegratedInbox = false; private static boolean measureAccounts = true; private static boolean countSearchMessages = true; private static boolean hideSpecialAccounts = false; private static boolean autofitWidth; private static boolean quietTimeEnabled = false; private static boolean notificationDuringQuietTimeEnabled = true; private static String quietTimeStarts = null; private static String quietTimeEnds = null; private static String attachmentDefaultPath = ""; private static boolean wrapFolderNames = false; private static boolean hideUserAgent = false; private static boolean hideTimeZone = false; private static boolean hideHostnameWhenConnecting = false; private static SortType sortType; private static Map<SortType, Boolean> sortAscending = new HashMap<SortType, Boolean>(); private static boolean useBackgroundAsUnreadIndicator = true; private static boolean threadedViewEnabled = true; private static SplitViewMode splitViewMode = SplitViewMode.NEVER; private static boolean colorizeMissingContactPictures = true; private static boolean messageViewArchiveActionVisible = false; private static boolean messageViewDeleteActionVisible = true; private static boolean messageViewMoveActionVisible = false; private static boolean messageViewCopyActionVisible = false; private static boolean messageViewSpamActionVisible = false; private static int pgpInlineDialogCounter; private static int pgpSignOnlyDialogCounter; /** * @see #areDatabasesUpToDate() */ private static boolean databasesUpToDate = false; /** * For use when displaying that no folder is selected */ public static final String FOLDER_NONE = "-NONE-"; public static final String LOCAL_UID_PREFIX = "K9LOCAL:"; public static final String REMOTE_UID_PREFIX = "K9REMOTE:"; public static final String IDENTITY_HEADER = K9MailLib.IDENTITY_HEADER; /** * Specifies how many messages will be shown in a folder by default. This number is set * on each new folder and can be incremented with "Load more messages..." by the * VISIBLE_LIMIT_INCREMENT */ public static final int DEFAULT_VISIBLE_LIMIT = 25; /** * The maximum size of an attachment we're willing to download (either View or Save) * Attachments that are base64 encoded (most) will be about 1.375x their actual size * so we should probably factor that in. A 5MB attachment will generally be around * 6.8MB downloaded but only 5MB saved. */ public static final int MAX_ATTACHMENT_DOWNLOAD_SIZE = (128 * 1024 * 1024); /* How many times should K-9 try to deliver a message before giving up * until the app is killed and restarted */ public static final int MAX_SEND_ATTEMPTS = 5; /** * Max time (in millis) the wake lock will be held for when background sync is happening */ public static final int WAKE_LOCK_TIMEOUT = 600000; public static final int MANUAL_WAKE_LOCK_TIMEOUT = 120000; public static final int PUSH_WAKE_LOCK_TIMEOUT = K9MailLib.PUSH_WAKE_LOCK_TIMEOUT; public static final int MAIL_SERVICE_WAKE_LOCK_TIMEOUT = 60000; public static final int BOOT_RECEIVER_WAKE_LOCK_TIMEOUT = 60000; public static class Intents { public static class EmailReceived { public static final String ACTION_EMAIL_RECEIVED = BuildConfig.APPLICATION_ID + ".intent.action.EMAIL_RECEIVED"; public static final String ACTION_EMAIL_DELETED = BuildConfig.APPLICATION_ID + ".intent.action.EMAIL_DELETED"; public static final String ACTION_REFRESH_OBSERVER = BuildConfig.APPLICATION_ID + ".intent.action.REFRESH_OBSERVER"; public static final String EXTRA_ACCOUNT = BuildConfig.APPLICATION_ID + ".intent.extra.ACCOUNT"; public static final String EXTRA_FOLDER = BuildConfig.APPLICATION_ID + ".intent.extra.FOLDER"; public static final String EXTRA_SENT_DATE = BuildConfig.APPLICATION_ID + ".intent.extra.SENT_DATE"; public static final String EXTRA_FROM = BuildConfig.APPLICATION_ID + ".intent.extra.FROM"; public static final String EXTRA_TO = BuildConfig.APPLICATION_ID + ".intent.extra.TO"; public static final String EXTRA_CC = BuildConfig.APPLICATION_ID + ".intent.extra.CC"; public static final String EXTRA_BCC = BuildConfig.APPLICATION_ID + ".intent.extra.BCC"; public static final String EXTRA_SUBJECT = BuildConfig.APPLICATION_ID + ".intent.extra.SUBJECT"; public static final String EXTRA_FROM_SELF = BuildConfig.APPLICATION_ID + ".intent.extra.FROM_SELF"; } public static class Share { /* * We don't want to use EmailReceived.EXTRA_FROM ("com.fsck.k9.intent.extra.FROM") * because of different semantics (String array vs. string with comma separated * email addresses) */ public static final String EXTRA_FROM = BuildConfig.APPLICATION_ID + ".intent.extra.SENDER"; } } /** * Called throughout the application when the number of accounts has changed. This method * enables or disables the Compose activity, the boot receiver and the service based on * whether any accounts are configured. */ public static void setServicesEnabled(Context context) { Context appContext = context.getApplicationContext(); int acctLength = Preferences.getPreferences(appContext).getAvailableAccounts().size(); boolean enable = acctLength > 0; setServicesEnabled(appContext, enable, null); updateDeviceIdleReceiver(appContext, enable); } private static void updateDeviceIdleReceiver(Context context, boolean enable) { DeviceIdleManager deviceIdleManager = DeviceIdleManager.getInstance(context); if (enable) { deviceIdleManager.registerReceiver(); } else { deviceIdleManager.unregisterReceiver(); } } private static void setServicesEnabled(Context context, boolean enabled, Integer wakeLockId) { PackageManager pm = context.getPackageManager(); if (!enabled && pm.getComponentEnabledSetting(new ComponentName(context, MailService.class)) == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { /* * If no accounts now exist but the service is still enabled we're about to disable it * so we'll reschedule to kill off any existing alarms. */ MailService.actionReset(context, wakeLockId); } Class<?>[] classes = { MessageCompose.class, BootReceiver.class, MailService.class }; for (Class<?> clazz : classes) { boolean alreadyEnabled = pm.getComponentEnabledSetting(new ComponentName(context, clazz)) == PackageManager.COMPONENT_ENABLED_STATE_ENABLED; if (enabled != alreadyEnabled) { pm.setComponentEnabledSetting( new ComponentName(context, clazz), enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED : PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP); } } if (enabled && pm.getComponentEnabledSetting(new ComponentName(context, MailService.class)) == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { /* * And now if accounts do exist then we've just enabled the service and we want to * schedule alarms for the new accounts. */ MailService.actionReset(context, wakeLockId); } } /** * Register BroadcastReceivers programmatically because doing it from manifest * would make K-9 auto-start. We don't want auto-start because the initialization * sequence isn't safe while some events occur (SD card unmount). */ protected void registerReceivers() { final StorageGoneReceiver receiver = new StorageGoneReceiver(); final IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_MEDIA_EJECT); filter.addAction(Intent.ACTION_MEDIA_UNMOUNTED); filter.addDataScheme("file"); final BlockingQueue<Handler> queue = new SynchronousQueue<Handler>(); // starting a new thread to handle unmount events new Thread(new Runnable() { @Override public void run() { Looper.prepare(); try { queue.put(new Handler()); } catch (InterruptedException e) { Timber.e(e); } Looper.loop(); } }, "Unmount-thread").start(); try { final Handler storageGoneHandler = queue.take(); registerReceiver(receiver, filter, null, storageGoneHandler); Timber.i("Registered: unmount receiver"); } catch (InterruptedException e) { Timber.e(e, "Unable to register unmount receiver"); } registerReceiver(new ShutdownReceiver(), new IntentFilter(Intent.ACTION_SHUTDOWN)); Timber.i("Registered: shutdown receiver"); } public static void save(StorageEditor editor) { editor.putBoolean("enableDebugLogging", K9.DEBUG); editor.putBoolean("enableSensitiveLogging", K9.DEBUG_SENSITIVE); editor.putString("backgroundOperations", K9.backgroundOps.name()); editor.putBoolean("animations", animations); editor.putBoolean("gesturesEnabled", gesturesEnabled); editor.putBoolean("useVolumeKeysForNavigation", useVolumeKeysForNavigation); editor.putBoolean("useVolumeKeysForListNavigation", useVolumeKeysForListNavigation); editor.putBoolean("autofitWidth", autofitWidth); editor.putBoolean("quietTimeEnabled", quietTimeEnabled); editor.putBoolean("notificationDuringQuietTimeEnabled", notificationDuringQuietTimeEnabled); editor.putString("quietTimeStarts", quietTimeStarts); editor.putString("quietTimeEnds", quietTimeEnds); editor.putBoolean("startIntegratedInbox", startIntegratedInbox); editor.putBoolean("measureAccounts", measureAccounts); editor.putBoolean("countSearchMessages", countSearchMessages); editor.putBoolean("messageListSenderAboveSubject", messageListSenderAboveSubject); editor.putBoolean("hideSpecialAccounts", hideSpecialAccounts); editor.putBoolean("messageListStars", messageListStars); editor.putInt("messageListPreviewLines", messageListPreviewLines); editor.putBoolean("messageListCheckboxes", messageListCheckboxes); editor.putBoolean("showCorrespondentNames", showCorrespondentNames); editor.putBoolean("showContactName", showContactName); editor.putBoolean("showContactPicture", showContactPicture); editor.putBoolean("changeRegisteredNameColor", changeContactNameColor); editor.putInt("registeredNameColor", contactNameColor); editor.putBoolean("messageViewFixedWidthFont", messageViewFixedWidthFont); editor.putBoolean("messageViewReturnToList", messageViewReturnToList); editor.putBoolean("messageViewShowNext", messageViewShowNext); editor.putBoolean("wrapFolderNames", wrapFolderNames); editor.putBoolean("hideUserAgent", hideUserAgent); editor.putBoolean("hideTimeZone", hideTimeZone); editor.putBoolean("hideHostnameWhenConnecting", hideHostnameWhenConnecting); editor.putString("language", language); editor.putInt("theme", theme.ordinal()); editor.putInt("messageViewTheme", messageViewTheme.ordinal()); editor.putInt("messageComposeTheme", composerTheme.ordinal()); editor.putBoolean("fixedMessageViewTheme", useFixedMessageTheme); editor.putBoolean("confirmDelete", confirmDelete); editor.putBoolean("confirmDiscardMessage", confirmDiscardMessage); editor.putBoolean("confirmDeleteStarred", confirmDeleteStarred); editor.putBoolean("confirmSpam", confirmSpam); editor.putBoolean("confirmDeleteFromNotification", confirmDeleteFromNotification); editor.putBoolean("confirmMarkAllRead", confirmMarkAllRead); editor.putString("sortTypeEnum", sortType.name()); editor.putBoolean("sortAscending", sortAscending.get(sortType)); editor.putString("notificationHideSubject", notificationHideSubject.toString()); editor.putString("notificationQuickDelete", notificationQuickDelete.toString()); editor.putString("lockScreenNotificationVisibility", sLockScreenNotificationVisibility.toString()); editor.putString("attachmentdefaultpath", attachmentDefaultPath); editor.putBoolean("useBackgroundAsUnreadIndicator", useBackgroundAsUnreadIndicator); editor.putBoolean("threadedView", threadedViewEnabled); editor.putString("splitViewMode", splitViewMode.name()); editor.putBoolean("colorizeMissingContactPictures", colorizeMissingContactPictures); editor.putBoolean("messageViewArchiveActionVisible", messageViewArchiveActionVisible); editor.putBoolean("messageViewDeleteActionVisible", messageViewDeleteActionVisible); editor.putBoolean("messageViewMoveActionVisible", messageViewMoveActionVisible); editor.putBoolean("messageViewCopyActionVisible", messageViewCopyActionVisible); editor.putBoolean("messageViewSpamActionVisible", messageViewSpamActionVisible); editor.putInt("pgpInlineDialogCounter", pgpInlineDialogCounter); editor.putInt("pgpSignOnlyDialogCounter", pgpSignOnlyDialogCounter); fontSizes.save(editor); } @Override public void onCreate() { if (K9.DEVELOPER_MODE) { StrictMode.enableDefaults(); } PRNGFixes.apply(); super.onCreate(); app = this; DI.start(this); Globals.setContext(this); K9MailLib.setDebugStatus(new K9MailLib.DebugStatus() { @Override public boolean enabled() { return DEBUG; } @Override public boolean debugSensitive() { return DEBUG_SENSITIVE; } }); checkCachedDatabaseVersion(); Preferences prefs = Preferences.getPreferences(this); loadPrefs(prefs); /* * We have to give MimeMessage a temp directory because File.createTempFile(String, String) * doesn't work in Android and MimeMessage does not have access to a Context. */ BinaryTempFileBody.setTempDirectory(getCacheDir()); LocalKeyStore.setKeyStoreLocation(getDir("KeyStore", MODE_PRIVATE).toString()); /* * Enable background sync of messages */ setServicesEnabled(this); registerReceivers(); MessagingController.getInstance(this).addListener(new SimpleMessagingListener() { private UnreadWidgetUpdater unreadWidgetUpdater = DI.get(UnreadWidgetUpdater.class); private void broadcastIntent(String action, Account account, String folder, Message message) { Uri uri = Uri.parse("email://messages/" + account.getAccountNumber() + "/" + Uri.encode(folder) + "/" + Uri.encode(message.getUid())); Intent intent = new Intent(action, uri); intent.putExtra(K9.Intents.EmailReceived.EXTRA_ACCOUNT, account.getDescription()); intent.putExtra(K9.Intents.EmailReceived.EXTRA_FOLDER, folder); intent.putExtra(K9.Intents.EmailReceived.EXTRA_SENT_DATE, message.getSentDate()); intent.putExtra(K9.Intents.EmailReceived.EXTRA_FROM, Address.toString(message.getFrom())); intent.putExtra(K9.Intents.EmailReceived.EXTRA_TO, Address.toString(message.getRecipients(Message.RecipientType.TO))); intent.putExtra(K9.Intents.EmailReceived.EXTRA_CC, Address.toString(message.getRecipients(Message.RecipientType.CC))); intent.putExtra(K9.Intents.EmailReceived.EXTRA_BCC, Address.toString(message.getRecipients(Message.RecipientType.BCC))); intent.putExtra(K9.Intents.EmailReceived.EXTRA_SUBJECT, message.getSubject()); intent.putExtra(K9.Intents.EmailReceived.EXTRA_FROM_SELF, account.isAnIdentity(message.getFrom())); K9.this.sendBroadcast(intent); Timber.d("Broadcasted: action=%s account=%s folder=%s message uid=%s", action, account.getDescription(), folder, message.getUid()); } private void updateUnreadWidget() { try { unreadWidgetUpdater.updateAll(); } catch (Exception e) { Timber.e(e, "Error while updating unread widget(s)"); } } private void updateMailListWidget() { try { MessageListWidgetProvider.triggerMessageListWidgetUpdate(K9.this); } catch (RuntimeException e) { if (BuildConfig.DEBUG) { throw e; } else { Timber.e(e, "Error while updating message list widget"); } } } @Override public void synchronizeMailboxRemovedMessage(Account account, String folderServerId, Message message) { broadcastIntent(K9.Intents.EmailReceived.ACTION_EMAIL_DELETED, account, folderServerId, message); updateUnreadWidget(); updateMailListWidget(); } @Override public void messageDeleted(Account account, String folderServerId, Message message) { broadcastIntent(K9.Intents.EmailReceived.ACTION_EMAIL_DELETED, account, folderServerId, message); updateUnreadWidget(); updateMailListWidget(); } @Override public void synchronizeMailboxNewMessage(Account account, String folderServerId, Message message) { broadcastIntent(K9.Intents.EmailReceived.ACTION_EMAIL_RECEIVED, account, folderServerId, message); updateUnreadWidget(); updateMailListWidget(); } @Override public void folderStatusChanged(Account account, String folderServerId, int unreadMessageCount) { updateUnreadWidget(); updateMailListWidget(); // let observers know a change occurred Intent intent = new Intent(K9.Intents.EmailReceived.ACTION_REFRESH_OBSERVER, null); intent.putExtra(K9.Intents.EmailReceived.EXTRA_ACCOUNT, account.getDescription()); intent.putExtra(K9.Intents.EmailReceived.EXTRA_FOLDER, folderServerId); K9.this.sendBroadcast(intent); } }); notifyObservers(); } /** * Loads the last known database version of the accounts' databases from a * {@code SharedPreference}. * * <p> * If the stored version matches {@link LocalStore#DB_VERSION} we know that the databases are * up to date.<br> * Using {@code SharedPreferences} should be a lot faster than opening all SQLite databases to * get the current database version. * </p><p> * See {@link UpgradeDatabases} for a detailed explanation of the database upgrade process. * </p> * * @see #areDatabasesUpToDate() */ public void checkCachedDatabaseVersion() { databaseVersionCache = getSharedPreferences(DATABASE_VERSION_CACHE, MODE_PRIVATE); int cachedVersion = databaseVersionCache.getInt(KEY_LAST_ACCOUNT_DATABASE_VERSION, 0); if (cachedVersion >= LocalStore.DB_VERSION) { K9.setDatabasesUpToDate(false); } if (cachedVersion < VERSION_MIGRATE_OPENPGP_TO_ACCOUNTS) { migrateOpenPgpGlobalToAccountSettings(); } } private void migrateOpenPgpGlobalToAccountSettings() { Preferences preferences = Preferences.getPreferences(this); Storage storage = preferences.getStorage(); String openPgpProvider = storage.getString("openPgpProvider", null); boolean openPgpSupportSignOnly = storage.getBoolean("openPgpSupportSignOnly", false); for (Account account : preferences.getAccounts()) { account.setOpenPgpProvider(openPgpProvider); account.setOpenPgpHideSignOnly(!openPgpSupportSignOnly); account.save(preferences); } storage.edit() .remove("openPgpProvider") .remove("openPgpSupportSignOnly") .commit(); } /** * Load preferences into our statics. * * If you're adding a preference here, odds are you'll need to add it to * {@link com.fsck.k9.preferences.GlobalSettings}, too. * * @param prefs Preferences to load */ public static void loadPrefs(Preferences prefs) { Storage storage = prefs.getStorage(); setDebug(storage.getBoolean("enableDebugLogging", BuildConfig.DEVELOPER_MODE)); DEBUG_SENSITIVE = storage.getBoolean("enableSensitiveLogging", false); animations = storage.getBoolean("animations", true); gesturesEnabled = storage.getBoolean("gesturesEnabled", false); useVolumeKeysForNavigation = storage.getBoolean("useVolumeKeysForNavigation", false); useVolumeKeysForListNavigation = storage.getBoolean("useVolumeKeysForListNavigation", false); startIntegratedInbox = storage.getBoolean("startIntegratedInbox", false); measureAccounts = storage.getBoolean("measureAccounts", true); countSearchMessages = storage.getBoolean("countSearchMessages", true); hideSpecialAccounts = storage.getBoolean("hideSpecialAccounts", false); messageListSenderAboveSubject = storage.getBoolean("messageListSenderAboveSubject", false); messageListCheckboxes = storage.getBoolean("messageListCheckboxes", false); messageListStars = storage.getBoolean("messageListStars", true); messageListPreviewLines = storage.getInt("messageListPreviewLines", 2); autofitWidth = storage.getBoolean("autofitWidth", true); quietTimeEnabled = storage.getBoolean("quietTimeEnabled", false); notificationDuringQuietTimeEnabled = storage.getBoolean("notificationDuringQuietTimeEnabled", true); quietTimeStarts = storage.getString("quietTimeStarts", "21:00"); quietTimeEnds = storage.getString("quietTimeEnds", "7:00"); showCorrespondentNames = storage.getBoolean("showCorrespondentNames", true); showContactName = storage.getBoolean("showContactName", false); showContactPicture = storage.getBoolean("showContactPicture", true); changeContactNameColor = storage.getBoolean("changeRegisteredNameColor", false); contactNameColor = storage.getInt("registeredNameColor", 0xff00008f); messageViewFixedWidthFont = storage.getBoolean("messageViewFixedWidthFont", false); messageViewReturnToList = storage.getBoolean("messageViewReturnToList", false); messageViewShowNext = storage.getBoolean("messageViewShowNext", false); wrapFolderNames = storage.getBoolean("wrapFolderNames", false); hideUserAgent = storage.getBoolean("hideUserAgent", false); hideTimeZone = storage.getBoolean("hideTimeZone", false); hideHostnameWhenConnecting = storage.getBoolean("hideHostnameWhenConnecting", false); confirmDelete = storage.getBoolean("confirmDelete", false); confirmDiscardMessage = storage.getBoolean("confirmDiscardMessage", true); confirmDeleteStarred = storage.getBoolean("confirmDeleteStarred", false); confirmSpam = storage.getBoolean("confirmSpam", false); confirmDeleteFromNotification = storage.getBoolean("confirmDeleteFromNotification", true); confirmMarkAllRead = storage.getBoolean("confirmMarkAllRead", true); try { String value = storage.getString("sortTypeEnum", Account.DEFAULT_SORT_TYPE.name()); sortType = SortType.valueOf(value); } catch (Exception e) { sortType = Account.DEFAULT_SORT_TYPE; } boolean sortAscending = storage.getBoolean("sortAscending", Account.DEFAULT_SORT_ASCENDING); K9.sortAscending.put(sortType, sortAscending); String notificationHideSubject = storage.getString("notificationHideSubject", null); if (notificationHideSubject == null) { // If the "notificationHideSubject" setting couldn't be found, the app was probably // updated. Look for the old "keyguardPrivacy" setting and map it to the new enum. K9.notificationHideSubject = (storage.getBoolean("keyguardPrivacy", false)) ? NotificationHideSubject.WHEN_LOCKED : NotificationHideSubject.NEVER; } else { K9.notificationHideSubject = NotificationHideSubject.valueOf(notificationHideSubject); } String notificationQuickDelete = storage.getString("notificationQuickDelete", null); if (notificationQuickDelete != null) { K9.notificationQuickDelete = NotificationQuickDelete.valueOf(notificationQuickDelete); } String lockScreenNotificationVisibility = storage.getString("lockScreenNotificationVisibility", null); if(lockScreenNotificationVisibility != null) { sLockScreenNotificationVisibility = LockScreenNotificationVisibility.valueOf(lockScreenNotificationVisibility); } String splitViewMode = storage.getString("splitViewMode", null); if (splitViewMode != null) { K9.splitViewMode = SplitViewMode.valueOf(splitViewMode); } attachmentDefaultPath = storage.getString("attachmentdefaultpath", Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()); useBackgroundAsUnreadIndicator = storage.getBoolean("useBackgroundAsUnreadIndicator", true); threadedViewEnabled = storage.getBoolean("threadedView", true); fontSizes.load(storage); try { setBackgroundOps(BACKGROUND_OPS.valueOf(storage.getString( "backgroundOperations", BACKGROUND_OPS.WHEN_CHECKED_AUTO_SYNC.name()))); } catch (Exception e) { setBackgroundOps(BACKGROUND_OPS.WHEN_CHECKED_AUTO_SYNC); } colorizeMissingContactPictures = storage.getBoolean("colorizeMissingContactPictures", true); messageViewArchiveActionVisible = storage.getBoolean("messageViewArchiveActionVisible", false); messageViewDeleteActionVisible = storage.getBoolean("messageViewDeleteActionVisible", true); messageViewMoveActionVisible = storage.getBoolean("messageViewMoveActionVisible", false); messageViewCopyActionVisible = storage.getBoolean("messageViewCopyActionVisible", false); messageViewSpamActionVisible = storage.getBoolean("messageViewSpamActionVisible", false); pgpInlineDialogCounter = storage.getInt("pgpInlineDialogCounter", 0); pgpSignOnlyDialogCounter = storage.getInt("pgpSignOnlyDialogCounter", 0); K9.setK9Language(storage.getString("language", "")); int themeValue = storage.getInt("theme", Theme.LIGHT.ordinal()); // We used to save the resource ID of the theme. So convert that to the new format if // necessary. if (themeValue == Theme.DARK.ordinal() || themeValue == android.R.style.Theme) { K9.setK9Theme(Theme.DARK); } else { K9.setK9Theme(Theme.LIGHT); } themeValue = storage.getInt("messageViewTheme", Theme.USE_GLOBAL.ordinal()); K9.setK9MessageViewThemeSetting(Theme.values()[themeValue]); themeValue = storage.getInt("messageComposeTheme", Theme.USE_GLOBAL.ordinal()); K9.setK9ComposerThemeSetting(Theme.values()[themeValue]); K9.setUseFixedMessageViewTheme(storage.getBoolean("fixedMessageViewTheme", true)); } /** * since Android invokes Application.onCreate() only after invoking all * other components' onCreate(), here is a way to notify interested * component that the application is available and ready */ protected void notifyObservers() { synchronized (observers) { for (final ApplicationAware aware : observers) { Timber.v("Initializing observer: %s", aware); try { aware.initializeComponent(this); } catch (Exception e) { Timber.w(e, "Failure when notifying %s", aware); } } initialized = true; observers.clear(); } } /** * Register a component to be notified when the {@link K9} instance is ready. * * @param component * Never <code>null</code>. */ public static void registerApplicationAware(final ApplicationAware component) { synchronized (observers) { if (initialized) { component.initializeComponent(K9.app); } else if (!observers.contains(component)) { observers.add(component); } } } public static String getK9Language() { return language; } public static void setK9Language(String nlanguage) { language = nlanguage; } /** * Possible values for the different theme settings. * * <p><strong>Important:</strong> * Do not change the order of the items! The ordinal value (position) is used when saving the * settings.</p> */ public enum Theme { LIGHT, DARK, USE_GLOBAL } public static int getK9ThemeResourceId(Theme themeId) { return (themeId == Theme.LIGHT) ? R.style.Theme_K9_Light : R.style.Theme_K9_Dark; } public static int getK9ThemeResourceId() { return getK9ThemeResourceId(theme); } public static Theme getK9MessageViewTheme() { return messageViewTheme == Theme.USE_GLOBAL ? theme : messageViewTheme; } public static Theme getK9MessageViewThemeSetting() { return messageViewTheme; } public static Theme getK9ComposerTheme() { return composerTheme == Theme.USE_GLOBAL ? theme : composerTheme; } public static Theme getK9ComposerThemeSetting() { return composerTheme; } public static Theme getK9Theme() { return theme; } public static void setK9Theme(Theme ntheme) { if (ntheme != Theme.USE_GLOBAL) { theme = ntheme; } } public static void setK9MessageViewThemeSetting(Theme nMessageViewTheme) { messageViewTheme = nMessageViewTheme; } public static boolean useFixedMessageViewTheme() { return useFixedMessageTheme; } public static void setK9ComposerThemeSetting(Theme compTheme) { composerTheme = compTheme; } public static void setUseFixedMessageViewTheme(boolean useFixed) { useFixedMessageTheme = useFixed; if (!useFixedMessageTheme && messageViewTheme == Theme.USE_GLOBAL) { messageViewTheme = theme; } } public static BACKGROUND_OPS getBackgroundOps() { return backgroundOps; } public static boolean setBackgroundOps(BACKGROUND_OPS backgroundOps) { BACKGROUND_OPS oldBackgroundOps = K9.backgroundOps; K9.backgroundOps = backgroundOps; return backgroundOps != oldBackgroundOps; } public static boolean setBackgroundOps(String nbackgroundOps) { return setBackgroundOps(BACKGROUND_OPS.valueOf(nbackgroundOps)); } public static boolean gesturesEnabled() { return gesturesEnabled; } public static void setGesturesEnabled(boolean gestures) { gesturesEnabled = gestures; } public static boolean useVolumeKeysForNavigationEnabled() { return useVolumeKeysForNavigation; } public static void setUseVolumeKeysForNavigation(boolean volume) { useVolumeKeysForNavigation = volume; } public static boolean useVolumeKeysForListNavigationEnabled() { return useVolumeKeysForListNavigation; } public static void setUseVolumeKeysForListNavigation(boolean enabled) { useVolumeKeysForListNavigation = enabled; } public static boolean autofitWidth() { return autofitWidth; } public static void setAutofitWidth(boolean autofitWidth) { K9.autofitWidth = autofitWidth; } public static boolean getQuietTimeEnabled() { return quietTimeEnabled; } public static void setQuietTimeEnabled(boolean quietTimeEnabled) { K9.quietTimeEnabled = quietTimeEnabled; } public static boolean isNotificationDuringQuietTimeEnabled() { return notificationDuringQuietTimeEnabled; } public static void setNotificationDuringQuietTimeEnabled(boolean notificationDuringQuietTimeEnabled) { K9.notificationDuringQuietTimeEnabled = notificationDuringQuietTimeEnabled; } public static String getQuietTimeStarts() { return quietTimeStarts; } public static void setQuietTimeStarts(String quietTimeStarts) { K9.quietTimeStarts = quietTimeStarts; } public static String getQuietTimeEnds() { return quietTimeEnds; } public static void setQuietTimeEnds(String quietTimeEnds) { K9.quietTimeEnds = quietTimeEnds; } public static boolean isQuietTime() { if (!quietTimeEnabled) { return false; } QuietTimeChecker quietTimeChecker = new QuietTimeChecker(Clock.INSTANCE, quietTimeStarts, quietTimeEnds); return quietTimeChecker.isQuietTime(); } public static void setDebug(boolean debug) { K9.DEBUG = debug; updateLoggingStatus(); } public static boolean isDebug() { return DEBUG; } public static boolean startIntegratedInbox() { return startIntegratedInbox; } public static void setStartIntegratedInbox(boolean startIntegratedInbox) { K9.startIntegratedInbox = startIntegratedInbox; } public static boolean showAnimations() { return animations; } public static void setAnimations(boolean animations) { K9.animations = animations; } public static int messageListPreviewLines() { return messageListPreviewLines; } public static void setMessageListPreviewLines(int lines) { messageListPreviewLines = lines; } public static boolean messageListCheckboxes() { return messageListCheckboxes; } public static void setMessageListCheckboxes(boolean checkboxes) { messageListCheckboxes = checkboxes; } public static boolean messageListStars() { return messageListStars; } public static void setMessageListStars(boolean stars) { messageListStars = stars; } public static boolean showCorrespondentNames() { return showCorrespondentNames; } public static boolean messageListSenderAboveSubject() { return messageListSenderAboveSubject; } public static void setMessageListSenderAboveSubject(boolean sender) { messageListSenderAboveSubject = sender; } public static void setShowCorrespondentNames(boolean showCorrespondentNames) { K9.showCorrespondentNames = showCorrespondentNames; } public static boolean showContactName() { return showContactName; } public static void setShowContactName(boolean showContactName) { K9.showContactName = showContactName; } public static boolean changeContactNameColor() { return changeContactNameColor; } public static void setChangeContactNameColor(boolean changeContactNameColor) { K9.changeContactNameColor = changeContactNameColor; } public static int getContactNameColor() { return contactNameColor; } public static void setContactNameColor(int contactNameColor) { K9.contactNameColor = contactNameColor; } public static boolean messageViewFixedWidthFont() { return messageViewFixedWidthFont; } public static void setMessageViewFixedWidthFont(boolean fixed) { messageViewFixedWidthFont = fixed; } public static boolean messageViewReturnToList() { return messageViewReturnToList; } public static void setMessageViewReturnToList(boolean messageViewReturnToList) { K9.messageViewReturnToList = messageViewReturnToList; } public static boolean messageViewShowNext() { return messageViewShowNext; } public static void setMessageViewShowNext(boolean messageViewShowNext) { K9.messageViewShowNext = messageViewShowNext; } public static FontSizes getFontSizes() { return fontSizes; } public static boolean measureAccounts() { return measureAccounts; } public static void setMeasureAccounts(boolean measureAccounts) { K9.measureAccounts = measureAccounts; } public static boolean countSearchMessages() { return countSearchMessages; } public static void setCountSearchMessages(boolean countSearchMessages) { K9.countSearchMessages = countSearchMessages; } public static boolean isHideSpecialAccounts() { return hideSpecialAccounts; } public static void setHideSpecialAccounts(boolean hideSpecialAccounts) { K9.hideSpecialAccounts = hideSpecialAccounts; } public static boolean confirmDelete() { return confirmDelete; } public static void setConfirmDelete(final boolean confirm) { confirmDelete = confirm; } public static boolean confirmDeleteStarred() { return confirmDeleteStarred; } public static void setConfirmDeleteStarred(final boolean confirm) { confirmDeleteStarred = confirm; } public static boolean confirmSpam() { return confirmSpam; } public static boolean confirmDiscardMessage() { return confirmDiscardMessage; } public static void setConfirmSpam(final boolean confirm) { confirmSpam = confirm; } public static void setConfirmDiscardMessage(final boolean confirm) { confirmDiscardMessage = confirm; } public static boolean confirmDeleteFromNotification() { return confirmDeleteFromNotification; } public static void setConfirmDeleteFromNotification(final boolean confirm) { confirmDeleteFromNotification = confirm; } public static boolean confirmMarkAllRead() { return confirmMarkAllRead; } public static void setConfirmMarkAllRead(final boolean confirm) { confirmMarkAllRead = confirm; } public static NotificationHideSubject getNotificationHideSubject() { return notificationHideSubject; } public static void setNotificationHideSubject(final NotificationHideSubject mode) { notificationHideSubject = mode; } public static NotificationQuickDelete getNotificationQuickDeleteBehaviour() { return notificationQuickDelete; } public static void setNotificationQuickDeleteBehaviour(final NotificationQuickDelete mode) { notificationQuickDelete = mode; } public static LockScreenNotificationVisibility getLockScreenNotificationVisibility() { return sLockScreenNotificationVisibility; } public static void setLockScreenNotificationVisibility(final LockScreenNotificationVisibility visibility) { sLockScreenNotificationVisibility = visibility; } public static boolean wrapFolderNames() { return wrapFolderNames; } public static void setWrapFolderNames(final boolean state) { wrapFolderNames = state; } public static boolean hideUserAgent() { return hideUserAgent; } public static void setHideUserAgent(final boolean state) { hideUserAgent = state; } public static boolean hideTimeZone() { return hideTimeZone; } public static void setHideTimeZone(final boolean state) { hideTimeZone = state; } public static boolean hideHostnameWhenConnecting() { return hideHostnameWhenConnecting; } public static void setHideHostnameWhenConnecting(final boolean state) { hideHostnameWhenConnecting = state; } public static String getAttachmentDefaultPath() { return attachmentDefaultPath; } public static void setAttachmentDefaultPath(String attachmentDefaultPath) { K9.attachmentDefaultPath = attachmentDefaultPath; } public static synchronized SortType getSortType() { return sortType; } public static synchronized void setSortType(SortType sortType) { K9.sortType = sortType; } public static synchronized boolean isSortAscending(SortType sortType) { if (sortAscending.get(sortType) == null) { sortAscending.put(sortType, sortType.isDefaultAscending()); } return sortAscending.get(sortType); } public static synchronized void setSortAscending(SortType sortType, boolean sortAscending) { K9.sortAscending.put(sortType, sortAscending); } public static synchronized boolean useBackgroundAsUnreadIndicator() { return useBackgroundAsUnreadIndicator; } public static synchronized void setUseBackgroundAsUnreadIndicator(boolean enabled) { useBackgroundAsUnreadIndicator = enabled; } public static synchronized boolean isThreadedViewEnabled() { return threadedViewEnabled; } public static synchronized void setThreadedViewEnabled(boolean enable) { threadedViewEnabled = enable; } public static synchronized SplitViewMode getSplitViewMode() { return splitViewMode; } public static synchronized void setSplitViewMode(SplitViewMode mode) { splitViewMode = mode; } public static boolean showContactPicture() { return showContactPicture; } public static void setShowContactPicture(boolean show) { showContactPicture = show; } public static boolean isColorizeMissingContactPictures() { return colorizeMissingContactPictures; } public static void setColorizeMissingContactPictures(boolean enabled) { colorizeMissingContactPictures = enabled; } public static boolean isMessageViewArchiveActionVisible() { return messageViewArchiveActionVisible; } public static void setMessageViewArchiveActionVisible(boolean visible) { messageViewArchiveActionVisible = visible; } public static boolean isMessageViewDeleteActionVisible() { return messageViewDeleteActionVisible; } public static void setMessageViewDeleteActionVisible(boolean visible) { messageViewDeleteActionVisible = visible; } public static boolean isMessageViewMoveActionVisible() { return messageViewMoveActionVisible; } public static void setMessageViewMoveActionVisible(boolean visible) { messageViewMoveActionVisible = visible; } public static boolean isMessageViewCopyActionVisible() { return messageViewCopyActionVisible; } public static void setMessageViewCopyActionVisible(boolean visible) { messageViewCopyActionVisible = visible; } public static boolean isMessageViewSpamActionVisible() { return messageViewSpamActionVisible; } public static void setMessageViewSpamActionVisible(boolean visible) { messageViewSpamActionVisible = visible; } public static int getPgpInlineDialogCounter() { return pgpInlineDialogCounter; } public static void setPgpInlineDialogCounter(int pgpInlineDialogCounter) { K9.pgpInlineDialogCounter = pgpInlineDialogCounter; } public static int getPgpSignOnlyDialogCounter() { return pgpSignOnlyDialogCounter; } public static void setPgpSignOnlyDialogCounter(int pgpSignOnlyDialogCounter) { K9.pgpSignOnlyDialogCounter = pgpSignOnlyDialogCounter; } /** * Check if we already know whether all databases are using the current database schema. * * <p> * This method is only used for optimizations. If it returns {@code true} we can be certain that * getting a {@link LocalStore} instance won't trigger a schema upgrade. * </p> * * @return {@code true}, if we know that all databases are using the current database schema. * {@code false}, otherwise. */ public static synchronized boolean areDatabasesUpToDate() { return databasesUpToDate; } /** * Remember that all account databases are using the most recent database schema. * * @param save * Whether or not to write the current database version to the * {@code SharedPreferences} {@link #DATABASE_VERSION_CACHE}. * * @see #areDatabasesUpToDate() */ public static synchronized void setDatabasesUpToDate(boolean save) { databasesUpToDate = true; if (save) { Editor editor = databaseVersionCache.edit(); editor.putInt(KEY_LAST_ACCOUNT_DATABASE_VERSION, LocalStore.DB_VERSION); editor.apply(); } } private static void updateLoggingStatus() { Timber.uprootAll(); boolean enableDebugLogging = BuildConfig.DEBUG || DEBUG; if (enableDebugLogging) { Timber.plant(new DebugTree()); } } public static void saveSettingsAsync() { new AsyncTask<Void,Void,Void>() { @Override protected Void doInBackground(Void... voids) { Preferences prefs = Preferences.getPreferences(app); StorageEditor editor = prefs.getStorage().edit(); save(editor); editor.commit(); return null; } }.execute(); } }
1
16,829
Having a negative in the variable/method name makes the code harder to read. Also, you inverted the logic but didn't invert the default value. I suggest sticking to the original name.
k9mail-k-9
java
@@ -66,8 +66,8 @@ namespace NLog.Targets /// Always use <see cref="Trace.WriteLine(string)"/> independent of <see cref="LogLevel"/> /// </summary> /// <docgen category='Output Options' order='100' /> - [DefaultValue(false)] - public bool RawWrite { get; set; } + [DefaultValue(true)] + public bool ForceTraceWriteLine { get; set; } = true; /// <summary> /// Forward <see cref="LogLevel.Fatal" /> to <see cref="Trace.Fail(string)" /> (Instead of <see cref="Trace.TraceError(string)" />)
1
// // Copyright (c) 2004-2020 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #define TRACE #if !NETSTANDARD1_3 namespace NLog.Targets { using System.ComponentModel; using System.Diagnostics; /// <summary> /// Sends log messages through System.Diagnostics.Trace. /// </summary> /// <seealso href="https://github.com/nlog/nlog/wiki/Trace-target">Documentation on NLog Wiki</seealso> /// <example> /// <p> /// To set up the target in the <a href="config.html">configuration file</a>, /// use the following syntax: /// </p> /// <code lang="XML" source="examples/targets/Configuration File/Trace/NLog.config" /> /// <p> /// This assumes just one target and a single rule. More configuration /// options are described <a href="config.html">here</a>. /// </p> /// <p> /// To set up the log target programmatically use code like this: /// </p> /// <code lang="C#" source="examples/targets/Configuration API/Trace/Simple/Example.cs" /> /// </example> [Target("Trace")] public sealed class TraceTarget : TargetWithLayout { /// <summary> /// Always use <see cref="Trace.WriteLine(string)"/> independent of <see cref="LogLevel"/> /// </summary> /// <docgen category='Output Options' order='100' /> [DefaultValue(false)] public bool RawWrite { get; set; } /// <summary> /// Forward <see cref="LogLevel.Fatal" /> to <see cref="Trace.Fail(string)" /> (Instead of <see cref="Trace.TraceError(string)" />) /// </summary> /// <remarks> /// Trace.Fail can have special side-effects, and give fatal exceptions, message dialogs or Environment.FailFast /// </remarks> /// <docgen category='Output Options' order='100' /> [DefaultValue(false)] public bool EnableTraceFail { get; set; } /// <summary> /// Initializes a new instance of the <see cref="TraceTarget" /> class. /// </summary> /// <remarks> /// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true}</code> /// </remarks> public TraceTarget() : base() { OptimizeBufferReuse = true; } /// <summary> /// Initializes a new instance of the <see cref="TraceTarget" /> class. /// </summary> /// <remarks> /// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true}</code> /// </remarks> /// <param name="name">Name of the target.</param> public TraceTarget(string name) : this() { Name = name; } /// <summary> /// Writes the specified logging event to the <see cref="System.Diagnostics.Trace"/> facility. /// /// Redirects the log message depending on <see cref="LogLevel"/> and <see cref="RawWrite"/>. /// When <see cref="RawWrite"/> is <c>false</c>: /// - <see cref="LogLevel.Fatal"/> writes to <see cref="Trace.TraceError(string)" /> /// - <see cref="LogLevel.Error"/> writes to <see cref="Trace.TraceError(string)" /> /// - <see cref="LogLevel.Warn"/> writes to <see cref="Trace.TraceWarning(string)" /> /// - <see cref="LogLevel.Info"/> writes to <see cref="Trace.TraceInformation(string)" /> /// - <see cref="LogLevel.Debug"/> writes to <see cref="Trace.WriteLine(string)" /> /// - <see cref="LogLevel.Trace"/> writes to <see cref="Trace.WriteLine(string)" /> /// </summary> /// <param name="logEvent">The logging event.</param> protected override void Write(LogEventInfo logEvent) { string logMessage = RenderLogEvent(Layout, logEvent); if (RawWrite || logEvent.Level <= LogLevel.Debug) { Trace.WriteLine(logMessage); } else if (logEvent.Level == LogLevel.Info) { Trace.TraceInformation(logMessage); } else if (logEvent.Level == LogLevel.Warn) { Trace.TraceWarning(logMessage); } else if (logEvent.Level == LogLevel.Error) { Trace.TraceError(logMessage); } else if (logEvent.Level >= LogLevel.Fatal) { if (EnableTraceFail) Trace.Fail(logMessage); // Can throw exceptions, show message dialog or perform Environment.FailFast else Trace.TraceError(logMessage); } else { Trace.WriteLine(logMessage); } } } } #endif
1
21,582
Think you need to keep `RawWrite` around as obsolete until NLog6 (Property that just assigns `ForceTraceWriteLine`)
NLog-NLog
.cs
@@ -45,6 +45,9 @@ proc_init_arch(void) num_simd_registers = MCXT_NUM_SIMD_SLOTS; num_opmask_registers = MCXT_NUM_OPMASK_SLOTS; + set_cache_line_size_using_ctr_el0(/* dcache_line_size= */ &cache_line_size, + /* icache_line_size= */ NULL); + /* FIXME i#1569: NYI */ }
1
/* ********************************************************** * Copyright (c) 2016 ARM Limited. All rights reserved. * **********************************************************/ /* * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of ARM Limited nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL ARM LIMITED OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. */ #include "../globals.h" #include "proc.h" #include "instr.h" static int num_simd_saved; static int num_simd_registers; static int num_opmask_registers; void proc_init_arch(void) { num_simd_saved = MCXT_NUM_SIMD_SLOTS; num_simd_registers = MCXT_NUM_SIMD_SLOTS; num_opmask_registers = MCXT_NUM_OPMASK_SLOTS; /* FIXME i#1569: NYI */ } bool proc_has_feature(feature_bit_t f) { ASSERT_NOT_IMPLEMENTED(false); /* FIXME i#1569 */ return false; } void machine_cache_sync(void *pc_start, void *pc_end, bool flush_icache) { clear_icache(pc_start, pc_end); } DR_API size_t proc_fpstate_save_size(void) { ASSERT_NOT_IMPLEMENTED(false); /* FIXME i#1569 */ return 0; } DR_API int proc_num_simd_saved(void) { return num_simd_saved; } void proc_set_num_simd_saved(int num) { SELF_UNPROTECT_DATASEC(DATASEC_RARELY_PROT); ATOMIC_4BYTE_WRITE(&num_simd_saved, num, false); SELF_PROTECT_DATASEC(DATASEC_RARELY_PROT); } DR_API int proc_num_simd_registers(void) { return num_simd_registers; } DR_API int proc_num_opmask_registers(void) { return num_opmask_registers; } int proc_num_simd_sse_avx_registers(void) { CLIENT_ASSERT(false, "Incorrect usage for ARM/AArch64."); return 0; } int proc_num_simd_sse_avx_saved(void) { CLIENT_ASSERT(false, "Incorrect usage for ARM/AArch64."); return 0; } int proc_xstate_area_kmask_offs(void) { /* Does not apply to AArch64. */ ASSERT_NOT_REACHED(); return 0; } int proc_xstate_area_zmm_hi256_offs(void) { /* Does not apply to AArch64. */ ASSERT_NOT_REACHED(); return 0; } int proc_xstate_area_hi16_zmm_offs(void) { /* Does not apply to AArch64. */ ASSERT_NOT_REACHED(); return 0; } DR_API size_t proc_save_fpstate(byte *buf) { /* All registers are saved by insert_push_all_registers so nothing extra * needs to be saved here. */ return DR_FPSTATE_BUF_SIZE; } DR_API void proc_restore_fpstate(byte *buf) { /* Nothing to restore. */ } void dr_insert_save_fpstate(void *drcontext, instrlist_t *ilist, instr_t *where, opnd_t buf) { ASSERT_NOT_IMPLEMENTED(false); /* FIXME i#1569 */ } void dr_insert_restore_fpstate(void *drcontext, instrlist_t *ilist, instr_t *where, opnd_t buf) { ASSERT_NOT_IMPLEMENTED(false); /* FIXME i#1569 */ } uint64 proc_get_timestamp(void) { ASSERT_NOT_IMPLEMENTED(false); /* FIXME i#1569 */ return 0; }
1
21,691
I would expect this to be named *get* not *set*: it's a query; it's not setting some persistent state.
DynamoRIO-dynamorio
c
@@ -2,7 +2,7 @@ import os from typing import Dict, List from dagster import SensorDefinition -from dagster.core.definitions.pipeline_sensor import PipelineFailureSensorContext +from dagster.core.definitions.pipeline_definition_sensor import PipelineFailureSensorContext from dagster_slack import make_slack_on_pipeline_failure_sensor from hacker_news_assets.utils.slack_message import build_slack_message_blocks
1
import os from typing import Dict, List from dagster import SensorDefinition from dagster.core.definitions.pipeline_sensor import PipelineFailureSensorContext from dagster_slack import make_slack_on_pipeline_failure_sensor from hacker_news_assets.utils.slack_message import build_slack_message_blocks def slack_message_blocks_fn(context: PipelineFailureSensorContext, base_url: str) -> List[Dict]: return build_slack_message_blocks( title="👎 Pipeline Failure", markdown_message=f'Pipeline "{context.pipeline_run.pipeline_name}" failed.', pipeline_name=context.pipeline_run.pipeline_name, run_id=context.pipeline_run.run_id, mode=context.pipeline_run.mode, run_page_url=f"{base_url}/instance/runs/{context.pipeline_run.run_id}", ) def make_pipeline_failure_sensor(base_url: str) -> SensorDefinition: return make_slack_on_pipeline_failure_sensor( channel="#dogfooding-alert", slack_token=os.environ.get("SLACK_DAGSTER_ETL_BOT_TOKEN", ""), blocks_fn=lambda context: slack_message_blocks_fn(context, base_url), pipeline_selection=[ "download_pipeline", "buildkite_activity_pipeline", "slack_stats_pipeline", "github_community_pipeline", ], )
1
16,492
maybe should rename this to be `run_status_sensor_definition.py`
dagster-io-dagster
py
@@ -0,0 +1,19 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.iceberg.spark; + +public class SparkWriteOptions { + public static final String FANOUT_ENABLED = "fanout-enabled"; +}
1
1
29,722
Do we want to add the other write options in this PR or keep the refactor separate?
apache-iceberg
java
@@ -68,7 +68,17 @@ def refresh_user_token(spotify_user): user (domain.spotify.Spotify): the same user with updated tokens """ auth = get_spotify_oauth() - new_token = auth.refresh_access_token(spotify_user.refresh_token) + + retries = 5 + new_token = None + while retries > 0: + new_token = auth.refresh_access_token(spotify_user.refresh_token) + if new_token is not None: + break + retries -= 1 + if new_token is None: + raise SpotifyAPIError('Could not refresh API Token for Spotify user') + access_token = new_token['access_token'] refresh_token = new_token['refresh_token'] expires_at = new_token['expires_at']
1
import pytz from flask import current_app import spotipy.oauth2 from listenbrainz.db import spotify as db_spotify import datetime class Spotify: def __init__(self, user_id, musicbrainz_id, user_token, token_expires, refresh_token, last_updated, active, error_message, latest_listened_at): self.user_id = user_id self.user_token = user_token self.token_expires = token_expires self.refresh_token = refresh_token self.last_updated = last_updated self.active = active self.error_message = error_message self.musicbrainz_id = musicbrainz_id self.latest_listened_at = latest_listened_at def get_spotipy_client(self): return spotipy.Spotify(auth=self.user_token) @property def last_updated_iso(self): if self.last_updated is None: return None return self.last_updated.isoformat() + "Z" @property def latest_listened_at_iso(self): if self.latest_listened_at is None: return None return self.latest_listened_at.isoformat() + "Z" @property def token_expired(self): now = datetime.datetime.utcnow() now = now.replace(tzinfo=pytz.UTC) return now >= self.token_expires @staticmethod def from_dbrow(row): return Spotify( user_id=row['user_id'], user_token=row['user_token'], token_expires=row['token_expires'], refresh_token=row['refresh_token'], last_updated=row['last_updated'], active=row['active'], error_message=row['error_message'], musicbrainz_id=row['musicbrainz_id'], latest_listened_at=row['latest_listened_at'], ) def __str__(self): return "<Spotify(user:%s): %s>" % (self.user_id, self.musicbrainz_id) def refresh_user_token(spotify_user): """ Refreshes the user token for the given spotify user. Args: spotify_user (domain.spotify.Spotify): the user whose token is to be refreshed Returns: user (domain.spotify.Spotify): the same user with updated tokens """ auth = get_spotify_oauth() new_token = auth.refresh_access_token(spotify_user.refresh_token) access_token = new_token['access_token'] refresh_token = new_token['refresh_token'] expires_at = new_token['expires_at'] db_spotify.update_token(spotify_user.user_id, access_token, refresh_token, expires_at) return get_user(spotify_user.user_id) def get_spotify_oauth(): """ Returns a spotipy OAuth instance that can be used to authenticate with spotify. """ client_id = current_app.config['SPOTIFY_CLIENT_ID'] client_secret = current_app.config['SPOTIFY_CLIENT_SECRET'] scope = 'user-read-recently-played' redirect_url = current_app.config['SPOTIFY_CALLBACK_URL'] return spotipy.oauth2.SpotifyOAuth(client_id, client_secret, redirect_uri=redirect_url, scope=scope) def get_user(user_id): """ Returns a Spotify instance corresponding to the specified LB row ID. If the user_id is not present in the spotify table, returns None Args: user_id (int): the ListenBrainz row ID of the user """ row = db_spotify.get_user(user_id) if row: return Spotify.from_dbrow(row) return None def remove_user(user_id): """ Delete user entry for user with specified ListenBrainz user ID. Args: user_id (int): the ListenBrainz row ID of the user """ db_spotify.delete_spotify(user_id) def add_new_user(user_id, spot_access_token): """Create a spotify row for a user based on OAuth access tokens Args: user_id: A flask auth `current_user.id` spot_access_token: A spotipy access token from SpotifyOAuth.get_access_token """ access_token = spot_access_token['access_token'] refresh_token = spot_access_token['refresh_token'] expires_at = spot_access_token['expires_at'] db_spotify.create_spotify(user_id, access_token, refresh_token, expires_at) def get_active_users_to_process(): """ Returns a list of Spotify user instances that need their Spotify listens imported. """ return [Spotify.from_dbrow(row) for row in db_spotify.get_active_users_to_process()] def update_last_updated(user_id, success=True, error_message=None): """ Update the last_update field for user with specified user ID. Also, set the user as active or inactive depending on whether their listens were imported without error. If there was an error, add the error to the db. Args: user_id (int): the ListenBrainz row ID of the user success (bool): flag representing whether the last import was successful or not. error_message (str): the user-friendly error message to be displayed. """ if error_message: db_spotify.add_update_error(user_id, error_message) else: db_spotify.update_last_updated(user_id, success) def update_latest_listened_at(user_id, timestamp): """ Update the latest_listened_at field for user with specified ListenBrainz user ID. Args: user_id (int): the ListenBrainz row ID of the user timestamp (int): the unix timestamp of the latest listen imported for the user """ db_spotify.update_latest_listened_at(user_id, timestamp) class SpotifyImporterException(Exception): pass class SpotifyListenBrainzError(Exception): pass class SpotifyAPIError(Exception): pass
1
15,042
either make this a config or a constant we can define at the top. Burying this in the code is no good.
metabrainz-listenbrainz-server
py
@@ -73,6 +73,13 @@ def multi_error(y_true, y_pred): def multi_logloss(y_true, y_pred): return np.mean([-math.log(y_pred[i][y]) for i, y in enumerate(y_true)]) +def custom_recall(y_true, y_pred): + return 'custom_recall', recall_score(y_true, y_pred > 0.5), True + + +def custom_precision(y_true, y_pred): + return 'custom_precision', precision_score(y_true, y_pred > 0.5), True + class TestSklearn(unittest.TestCase):
1
# coding: utf-8 import itertools import joblib import math import os import unittest import warnings import lightgbm as lgb import numpy as np from sklearn import __version__ as sk_version from sklearn.base import clone from sklearn.datasets import (load_boston, load_breast_cancer, load_digits, load_iris, load_linnerud, load_svmlight_file, make_multilabel_classification) from sklearn.exceptions import SkipTestWarning from sklearn.metrics import log_loss, mean_squared_error from sklearn.model_selection import GridSearchCV, RandomizedSearchCV, train_test_split from sklearn.multioutput import (MultiOutputClassifier, ClassifierChain, MultiOutputRegressor, RegressorChain) from sklearn.utils.estimator_checks import (_yield_all_checks, SkipTest, check_parameters_default_constructible) from sklearn.utils.validation import check_is_fitted decreasing_generator = itertools.count(0, -1) def custom_asymmetric_obj(y_true, y_pred): residual = (y_true - y_pred).astype("float") grad = np.where(residual < 0, -2 * 10.0 * residual, -2 * residual) hess = np.where(residual < 0, 2 * 10.0, 2.0) return grad, hess def objective_ls(y_true, y_pred): grad = (y_pred - y_true) hess = np.ones(len(y_true)) return grad, hess def logregobj(y_true, y_pred): y_pred = 1.0 / (1.0 + np.exp(-y_pred)) grad = y_pred - y_true hess = y_pred * (1.0 - y_pred) return grad, hess def custom_dummy_obj(y_true, y_pred): return np.ones(y_true.shape), np.ones(y_true.shape) def constant_metric(y_true, y_pred): return 'error', 0, False def decreasing_metric(y_true, y_pred): return ('decreasing_metric', next(decreasing_generator), False) def mse(y_true, y_pred): return 'custom MSE', mean_squared_error(y_true, y_pred), False def binary_error(y_true, y_pred): return np.mean((y_pred > 0.5) != y_true) def multi_error(y_true, y_pred): return np.mean(y_true != y_pred) def multi_logloss(y_true, y_pred): return np.mean([-math.log(y_pred[i][y]) for i, y in enumerate(y_true)]) class TestSklearn(unittest.TestCase): def test_binary(self): X, y = load_breast_cancer(return_X_y=True) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=42) gbm = lgb.LGBMClassifier(n_estimators=50, silent=True) gbm.fit(X_train, y_train, eval_set=[(X_test, y_test)], early_stopping_rounds=5, verbose=False) ret = log_loss(y_test, gbm.predict_proba(X_test)) self.assertLess(ret, 0.12) self.assertAlmostEqual(ret, gbm.evals_result_['valid_0']['binary_logloss'][gbm.best_iteration_ - 1], places=5) def test_regression(self): X, y = load_boston(return_X_y=True) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=42) gbm = lgb.LGBMRegressor(n_estimators=50, silent=True) gbm.fit(X_train, y_train, eval_set=[(X_test, y_test)], early_stopping_rounds=5, verbose=False) ret = mean_squared_error(y_test, gbm.predict(X_test)) self.assertLess(ret, 7) self.assertAlmostEqual(ret, gbm.evals_result_['valid_0']['l2'][gbm.best_iteration_ - 1], places=5) def test_multiclass(self): X, y = load_digits(n_class=10, return_X_y=True) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=42) gbm = lgb.LGBMClassifier(n_estimators=50, silent=True) gbm.fit(X_train, y_train, eval_set=[(X_test, y_test)], early_stopping_rounds=5, verbose=False) ret = multi_error(y_test, gbm.predict(X_test)) self.assertLess(ret, 0.05) ret = multi_logloss(y_test, gbm.predict_proba(X_test)) self.assertLess(ret, 0.16) self.assertAlmostEqual(ret, gbm.evals_result_['valid_0']['multi_logloss'][gbm.best_iteration_ - 1], places=5) def test_lambdarank(self): X_train, y_train = load_svmlight_file(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../examples/lambdarank/rank.train')) X_test, y_test = load_svmlight_file(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../examples/lambdarank/rank.test')) q_train = np.loadtxt(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../examples/lambdarank/rank.train.query')) q_test = np.loadtxt(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../examples/lambdarank/rank.test.query')) gbm = lgb.LGBMRanker(n_estimators=50) gbm.fit(X_train, y_train, group=q_train, eval_set=[(X_test, y_test)], eval_group=[q_test], eval_at=[1, 3], early_stopping_rounds=10, verbose=False, callbacks=[lgb.reset_parameter(learning_rate=lambda x: max(0.01, 0.1 - 0.01 * x))]) self.assertLessEqual(gbm.best_iteration_, 24) self.assertGreater(gbm.best_score_['valid_0']['ndcg@1'], 0.5769) self.assertGreater(gbm.best_score_['valid_0']['ndcg@3'], 0.5920) def test_xendcg(self): dir_path = os.path.dirname(os.path.realpath(__file__)) X_train, y_train = load_svmlight_file(os.path.join(dir_path, '../../examples/xendcg/rank.train')) X_test, y_test = load_svmlight_file(os.path.join(dir_path, '../../examples/xendcg/rank.test')) q_train = np.loadtxt(os.path.join(dir_path, '../../examples/xendcg/rank.train.query')) q_test = np.loadtxt(os.path.join(dir_path, '../../examples/xendcg/rank.test.query')) gbm = lgb.LGBMRanker(n_estimators=50, objective='rank_xendcg', random_state=5, n_jobs=1) gbm.fit(X_train, y_train, group=q_train, eval_set=[(X_test, y_test)], eval_group=[q_test], eval_at=[1, 3], early_stopping_rounds=10, verbose=False, eval_metric='ndcg', callbacks=[lgb.reset_parameter(learning_rate=lambda x: max(0.01, 0.1 - 0.01 * x))]) self.assertLessEqual(gbm.best_iteration_, 24) self.assertGreater(gbm.best_score_['valid_0']['ndcg@1'], 0.6211) self.assertGreater(gbm.best_score_['valid_0']['ndcg@3'], 0.6253) def test_regression_with_custom_objective(self): X, y = load_boston(return_X_y=True) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=42) gbm = lgb.LGBMRegressor(n_estimators=50, silent=True, objective=objective_ls) gbm.fit(X_train, y_train, eval_set=[(X_test, y_test)], early_stopping_rounds=5, verbose=False) ret = mean_squared_error(y_test, gbm.predict(X_test)) self.assertLess(ret, 7.0) self.assertAlmostEqual(ret, gbm.evals_result_['valid_0']['l2'][gbm.best_iteration_ - 1], places=5) def test_binary_classification_with_custom_objective(self): X, y = load_digits(n_class=2, return_X_y=True) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=42) gbm = lgb.LGBMClassifier(n_estimators=50, silent=True, objective=logregobj) gbm.fit(X_train, y_train, eval_set=[(X_test, y_test)], early_stopping_rounds=5, verbose=False) # prediction result is actually not transformed (is raw) due to custom objective y_pred_raw = gbm.predict_proba(X_test) self.assertFalse(np.all(y_pred_raw >= 0)) y_pred = 1.0 / (1.0 + np.exp(-y_pred_raw)) ret = binary_error(y_test, y_pred) self.assertLess(ret, 0.05) def test_dart(self): X, y = load_boston(return_X_y=True) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=42) gbm = lgb.LGBMRegressor(boosting_type='dart', n_estimators=50) gbm.fit(X_train, y_train) score = gbm.score(X_test, y_test) self.assertGreaterEqual(score, 0.8) self.assertLessEqual(score, 1.) # sklearn <0.23 does not have a stacking classifier and n_features_in_ property @unittest.skipIf(sk_version < '0.23.0', 'scikit-learn version is less than 0.23') def test_stacking_classifier(self): from sklearn.ensemble import StackingClassifier X, y = load_iris(return_X_y=True) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42) classifiers = [('gbm1', lgb.LGBMClassifier(n_estimators=3)), ('gbm2', lgb.LGBMClassifier(n_estimators=3))] clf = StackingClassifier(estimators=classifiers, final_estimator=lgb.LGBMClassifier(n_estimators=3), passthrough=True) clf.fit(X_train, y_train) score = clf.score(X_test, y_test) self.assertGreaterEqual(score, 0.8) self.assertLessEqual(score, 1.) self.assertEqual(clf.n_features_in_, 4) # number of input features self.assertEqual(len(clf.named_estimators_['gbm1'].feature_importances_), 4) self.assertEqual(clf.named_estimators_['gbm1'].n_features_in_, clf.named_estimators_['gbm2'].n_features_in_) self.assertEqual(clf.final_estimator_.n_features_in_, 10) # number of concatenated features self.assertEqual(len(clf.final_estimator_.feature_importances_), 10) classes = clf.named_estimators_['gbm1'].classes_ == clf.named_estimators_['gbm2'].classes_ self.assertTrue(all(classes)) classes = clf.classes_ == clf.named_estimators_['gbm1'].classes_ self.assertTrue(all(classes)) # sklearn <0.23 does not have a stacking regressor and n_features_in_ property @unittest.skipIf(sk_version < '0.23.0', 'scikit-learn version is less than 0.23') def test_stacking_regressor(self): from sklearn.ensemble import StackingRegressor X, y = load_boston(return_X_y=True) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42) regressors = [('gbm1', lgb.LGBMRegressor(n_estimators=3)), ('gbm2', lgb.LGBMRegressor(n_estimators=3))] reg = StackingRegressor(estimators=regressors, final_estimator=lgb.LGBMRegressor(n_estimators=3), passthrough=True) reg.fit(X_train, y_train) score = reg.score(X_test, y_test) self.assertGreaterEqual(score, 0.2) self.assertLessEqual(score, 1.) self.assertEqual(reg.n_features_in_, 13) # number of input features self.assertEqual(len(reg.named_estimators_['gbm1'].feature_importances_), 13) self.assertEqual(reg.named_estimators_['gbm1'].n_features_in_, reg.named_estimators_['gbm2'].n_features_in_) self.assertEqual(reg.final_estimator_.n_features_in_, 15) # number of concatenated features self.assertEqual(len(reg.final_estimator_.feature_importances_), 15) def test_grid_search(self): X, y = load_iris(return_X_y=True) y = y.astype(str) # utilize label encoder at it's max power X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=42) X_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=0.1, random_state=42) params = dict(subsample=0.8, subsample_freq=1) grid_params = dict(boosting_type=['rf', 'gbdt'], n_estimators=[4, 6], reg_alpha=[0.01, 0.005]) fit_params = dict(verbose=False, eval_set=[(X_val, y_val)], eval_metric=constant_metric, early_stopping_rounds=2) grid = GridSearchCV(estimator=lgb.LGBMClassifier(**params), param_grid=grid_params, cv=2) grid.fit(X_train, y_train, **fit_params) score = grid.score(X_test, y_test) # utilizes GridSearchCV default refit=True self.assertIn(grid.best_params_['boosting_type'], ['rf', 'gbdt']) self.assertIn(grid.best_params_['n_estimators'], [4, 6]) self.assertIn(grid.best_params_['reg_alpha'], [0.01, 0.005]) self.assertLessEqual(grid.best_score_, 1.) self.assertEqual(grid.best_estimator_.best_iteration_, 1) self.assertLess(grid.best_estimator_.best_score_['valid_0']['multi_logloss'], 0.25) self.assertEqual(grid.best_estimator_.best_score_['valid_0']['error'], 0) self.assertGreaterEqual(score, 0.2) self.assertLessEqual(score, 1.) def test_random_search(self): X, y = load_iris(return_X_y=True) y = y.astype(str) # utilize label encoder at it's max power X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=42) X_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=0.1, random_state=42) n_iter = 3 # Number of samples params = dict(subsample=0.8, subsample_freq=1) param_dist = dict(boosting_type=['rf', 'gbdt'], n_estimators=[np.random.randint(low=3, high=10) for i in range(n_iter)], reg_alpha=[np.random.uniform(low=0.01, high=0.06) for i in range(n_iter)]) fit_params = dict(verbose=False, eval_set=[(X_val, y_val)], eval_metric=constant_metric, early_stopping_rounds=2) rand = RandomizedSearchCV(estimator=lgb.LGBMClassifier(**params), param_distributions=param_dist, cv=2, n_iter=n_iter, random_state=42) rand.fit(X_train, y_train, **fit_params) score = rand.score(X_test, y_test) # utilizes RandomizedSearchCV default refit=True self.assertIn(rand.best_params_['boosting_type'], ['rf', 'gbdt']) self.assertIn(rand.best_params_['n_estimators'], list(range(3, 10))) self.assertGreaterEqual(rand.best_params_['reg_alpha'], 0.01) # Left-closed boundary point self.assertLessEqual(rand.best_params_['reg_alpha'], 0.06) # Right-closed boundary point self.assertLessEqual(rand.best_score_, 1.) self.assertLess(rand.best_estimator_.best_score_['valid_0']['multi_logloss'], 0.25) self.assertEqual(rand.best_estimator_.best_score_['valid_0']['error'], 0) self.assertGreaterEqual(score, 0.2) self.assertLessEqual(score, 1.) # sklearn < 0.22 does not have the post fit attribute: classes_ @unittest.skipIf(sk_version < '0.22.0', 'scikit-learn version is less than 0.22') def test_multioutput_classifier(self): n_outputs = 3 X, y = make_multilabel_classification(n_samples=100, n_features=20, n_classes=n_outputs, random_state=0) y = y.astype(str) # utilize label encoder at it's max power X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=42) clf = MultiOutputClassifier(estimator=lgb.LGBMClassifier(n_estimators=10)) clf.fit(X_train, y_train) score = clf.score(X_test, y_test) self.assertGreaterEqual(score, 0.2) self.assertLessEqual(score, 1.) np.testing.assert_array_equal(np.tile(np.unique(y_train), n_outputs), np.concatenate(clf.classes_)) for classifier in clf.estimators_: self.assertIsInstance(classifier, lgb.LGBMClassifier) self.assertIsInstance(classifier.booster_, lgb.Booster) # sklearn < 0.23 does not have as_frame parameter @unittest.skipIf(sk_version < '0.23.0', 'scikit-learn version is less than 0.23') def test_multioutput_regressor(self): bunch = load_linnerud(as_frame=True) # returns a Bunch instance X, y = bunch['data'], bunch['target'] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=42) reg = MultiOutputRegressor(estimator=lgb.LGBMRegressor(n_estimators=10)) reg.fit(X_train, y_train) y_pred = reg.predict(X_test) _, score, _ = mse(y_test, y_pred) self.assertGreaterEqual(score, 0.2) self.assertLessEqual(score, 120.) for regressor in reg.estimators_: self.assertIsInstance(regressor, lgb.LGBMRegressor) self.assertIsInstance(regressor.booster_, lgb.Booster) # sklearn < 0.22 does not have the post fit attribute: classes_ @unittest.skipIf(sk_version < '0.22.0', 'scikit-learn version is less than 0.22') def test_classifier_chain(self): n_outputs = 3 X, y = make_multilabel_classification(n_samples=100, n_features=20, n_classes=n_outputs, random_state=0) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=42) order = [2, 0, 1] clf = ClassifierChain(base_estimator=lgb.LGBMClassifier(n_estimators=10), order=order, random_state=42) clf.fit(X_train, y_train) score = clf.score(X_test, y_test) self.assertGreaterEqual(score, 0.2) self.assertLessEqual(score, 1.) np.testing.assert_array_equal(np.tile(np.unique(y_train), n_outputs), np.concatenate(clf.classes_)) self.assertListEqual(order, clf.order_) for classifier in clf.estimators_: self.assertIsInstance(classifier, lgb.LGBMClassifier) self.assertIsInstance(classifier.booster_, lgb.Booster) # sklearn < 0.23 does not have as_frame parameter @unittest.skipIf(sk_version < '0.23.0', 'scikit-learn version is less than 0.23') def test_regressor_chain(self): bunch = load_linnerud(as_frame=True) # returns a Bunch instance X, y = bunch['data'], bunch['target'] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=42) order = [2, 0, 1] reg = RegressorChain(base_estimator=lgb.LGBMRegressor(n_estimators=10), order=order, random_state=42) reg.fit(X_train, y_train) y_pred = reg.predict(X_test) _, score, _ = mse(y_test, y_pred) self.assertGreaterEqual(score, 0.2) self.assertLessEqual(score, 120.) self.assertListEqual(order, reg.order_) for regressor in reg.estimators_: self.assertIsInstance(regressor, lgb.LGBMRegressor) self.assertIsInstance(regressor.booster_, lgb.Booster) def test_clone_and_property(self): X, y = load_boston(return_X_y=True) gbm = lgb.LGBMRegressor(n_estimators=10, silent=True) gbm.fit(X, y, verbose=False) gbm_clone = clone(gbm) self.assertIsInstance(gbm.booster_, lgb.Booster) self.assertIsInstance(gbm.feature_importances_, np.ndarray) X, y = load_digits(n_class=2, return_X_y=True) clf = lgb.LGBMClassifier(n_estimators=10, silent=True) clf.fit(X, y, verbose=False) self.assertListEqual(sorted(clf.classes_), [0, 1]) self.assertEqual(clf.n_classes_, 2) self.assertIsInstance(clf.booster_, lgb.Booster) self.assertIsInstance(clf.feature_importances_, np.ndarray) def test_joblib(self): X, y = load_boston(return_X_y=True) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=42) gbm = lgb.LGBMRegressor(n_estimators=10, objective=custom_asymmetric_obj, silent=True, importance_type='split') gbm.fit(X_train, y_train, eval_set=[(X_train, y_train), (X_test, y_test)], eval_metric=mse, early_stopping_rounds=5, verbose=False, callbacks=[lgb.reset_parameter(learning_rate=list(np.arange(1, 0, -0.1)))]) joblib.dump(gbm, 'lgb.pkl') # test model with custom functions gbm_pickle = joblib.load('lgb.pkl') self.assertIsInstance(gbm_pickle.booster_, lgb.Booster) self.assertDictEqual(gbm.get_params(), gbm_pickle.get_params()) np.testing.assert_array_equal(gbm.feature_importances_, gbm_pickle.feature_importances_) self.assertAlmostEqual(gbm_pickle.learning_rate, 0.1) self.assertTrue(callable(gbm_pickle.objective)) for eval_set in gbm.evals_result_: for metric in gbm.evals_result_[eval_set]: np.testing.assert_allclose(gbm.evals_result_[eval_set][metric], gbm_pickle.evals_result_[eval_set][metric]) pred_origin = gbm.predict(X_test) pred_pickle = gbm_pickle.predict(X_test) np.testing.assert_allclose(pred_origin, pred_pickle) def test_random_state_object(self): X, y = load_iris(return_X_y=True) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=42) state1 = np.random.RandomState(123) state2 = np.random.RandomState(123) clf1 = lgb.LGBMClassifier(n_estimators=10, subsample=0.5, subsample_freq=1, random_state=state1) clf2 = lgb.LGBMClassifier(n_estimators=10, subsample=0.5, subsample_freq=1, random_state=state2) # Test if random_state is properly stored self.assertIs(clf1.random_state, state1) self.assertIs(clf2.random_state, state2) # Test if two random states produce identical models clf1.fit(X_train, y_train) clf2.fit(X_train, y_train) y_pred1 = clf1.predict(X_test, raw_score=True) y_pred2 = clf2.predict(X_test, raw_score=True) np.testing.assert_allclose(y_pred1, y_pred2) np.testing.assert_array_equal(clf1.feature_importances_, clf2.feature_importances_) df1 = clf1.booster_.model_to_string(num_iteration=0) df2 = clf2.booster_.model_to_string(num_iteration=0) self.assertMultiLineEqual(df1, df2) # Test if subsequent fits sample from random_state object and produce different models clf1.fit(X_train, y_train) y_pred1_refit = clf1.predict(X_test, raw_score=True) df3 = clf1.booster_.model_to_string(num_iteration=0) self.assertIs(clf1.random_state, state1) self.assertIs(clf2.random_state, state2) self.assertRaises(AssertionError, np.testing.assert_allclose, y_pred1, y_pred1_refit) self.assertRaises(AssertionError, self.assertMultiLineEqual, df1, df3) def test_feature_importances_single_leaf(self): data = load_iris(return_X_y=False) clf = lgb.LGBMClassifier(n_estimators=10) clf.fit(data.data, data.target) importances = clf.feature_importances_ self.assertEqual(len(importances), 4) def test_feature_importances_type(self): data = load_iris(return_X_y=False) clf = lgb.LGBMClassifier(n_estimators=10) clf.fit(data.data, data.target) clf.set_params(importance_type='split') importances_split = clf.feature_importances_ clf.set_params(importance_type='gain') importances_gain = clf.feature_importances_ # Test that the largest element is NOT the same, the smallest can be the same, i.e. zero importance_split_top1 = sorted(importances_split, reverse=True)[0] importance_gain_top1 = sorted(importances_gain, reverse=True)[0] self.assertNotEqual(importance_split_top1, importance_gain_top1) # sklearn <0.19 cannot accept instance, but many tests could be passed only with min_data=1 and min_data_in_bin=1 @unittest.skipIf(sk_version < '0.19.0', 'scikit-learn version is less than 0.19') def test_sklearn_integration(self): # we cannot use `check_estimator` directly since there is no skip test mechanism for name, estimator in ((lgb.sklearn.LGBMClassifier.__name__, lgb.sklearn.LGBMClassifier), (lgb.sklearn.LGBMRegressor.__name__, lgb.sklearn.LGBMRegressor)): check_parameters_default_constructible(name, estimator) # we cannot leave default params (see https://github.com/microsoft/LightGBM/issues/833) estimator = estimator(min_child_samples=1, min_data_in_bin=1) for check in _yield_all_checks(name, estimator): check_name = check.func.__name__ if hasattr(check, 'func') else check.__name__ if check_name == 'check_estimators_nan_inf': continue # skip test because LightGBM deals with nan elif check_name == "check_no_attributes_set_in_init": # skip test because scikit-learn incorrectly asserts that # private attributes cannot be set in __init__ # (see https://github.com/microsoft/LightGBM/issues/2628) continue try: check(name, estimator) except SkipTest as message: warnings.warn(message, SkipTestWarning) @unittest.skipIf(not lgb.compat.PANDAS_INSTALLED, 'pandas is not installed') def test_pandas_categorical(self): import pandas as pd np.random.seed(42) # sometimes there is no difference how cols are treated (cat or not cat) X = pd.DataFrame({"A": np.random.permutation(['a', 'b', 'c', 'd'] * 75), # str "B": np.random.permutation([1, 2, 3] * 100), # int "C": np.random.permutation([0.1, 0.2, -0.1, -0.1, 0.2] * 60), # float "D": np.random.permutation([True, False] * 150), # bool "E": pd.Categorical(np.random.permutation(['z', 'y', 'x', 'w', 'v'] * 60), ordered=True)}) # str and ordered categorical y = np.random.permutation([0, 1] * 150) X_test = pd.DataFrame({"A": np.random.permutation(['a', 'b', 'e'] * 20), # unseen category "B": np.random.permutation([1, 3] * 30), "C": np.random.permutation([0.1, -0.1, 0.2, 0.2] * 15), "D": np.random.permutation([True, False] * 30), "E": pd.Categorical(np.random.permutation(['z', 'y'] * 30), ordered=True)}) np.random.seed() # reset seed cat_cols_actual = ["A", "B", "C", "D"] cat_cols_to_store = cat_cols_actual + ["E"] X[cat_cols_actual] = X[cat_cols_actual].astype('category') X_test[cat_cols_actual] = X_test[cat_cols_actual].astype('category') cat_values = [X[col].cat.categories.tolist() for col in cat_cols_to_store] gbm0 = lgb.sklearn.LGBMClassifier(n_estimators=10).fit(X, y) pred0 = gbm0.predict(X_test, raw_score=True) pred_prob = gbm0.predict_proba(X_test)[:, 1] gbm1 = lgb.sklearn.LGBMClassifier(n_estimators=10).fit(X, pd.Series(y), categorical_feature=[0]) pred1 = gbm1.predict(X_test, raw_score=True) gbm2 = lgb.sklearn.LGBMClassifier(n_estimators=10).fit(X, y, categorical_feature=['A']) pred2 = gbm2.predict(X_test, raw_score=True) gbm3 = lgb.sklearn.LGBMClassifier(n_estimators=10).fit(X, y, categorical_feature=['A', 'B', 'C', 'D']) pred3 = gbm3.predict(X_test, raw_score=True) gbm3.booster_.save_model('categorical.model') gbm4 = lgb.Booster(model_file='categorical.model') pred4 = gbm4.predict(X_test) gbm5 = lgb.sklearn.LGBMClassifier(n_estimators=10).fit(X, y, categorical_feature=['A', 'B', 'C', 'D', 'E']) pred5 = gbm5.predict(X_test, raw_score=True) gbm6 = lgb.sklearn.LGBMClassifier(n_estimators=10).fit(X, y, categorical_feature=[]) pred6 = gbm6.predict(X_test, raw_score=True) self.assertRaises(AssertionError, np.testing.assert_allclose, pred0, pred1) self.assertRaises(AssertionError, np.testing.assert_allclose, pred0, pred2) np.testing.assert_allclose(pred1, pred2) np.testing.assert_allclose(pred0, pred3) np.testing.assert_allclose(pred_prob, pred4) self.assertRaises(AssertionError, np.testing.assert_allclose, pred0, pred5) # ordered cat features aren't treated as cat features by default self.assertRaises(AssertionError, np.testing.assert_allclose, pred0, pred6) self.assertListEqual(gbm0.booster_.pandas_categorical, cat_values) self.assertListEqual(gbm1.booster_.pandas_categorical, cat_values) self.assertListEqual(gbm2.booster_.pandas_categorical, cat_values) self.assertListEqual(gbm3.booster_.pandas_categorical, cat_values) self.assertListEqual(gbm4.pandas_categorical, cat_values) self.assertListEqual(gbm5.booster_.pandas_categorical, cat_values) self.assertListEqual(gbm6.booster_.pandas_categorical, cat_values) @unittest.skipIf(not lgb.compat.PANDAS_INSTALLED, 'pandas is not installed') def test_pandas_sparse(self): import pandas as pd try: from pandas.arrays import SparseArray except ImportError: # support old versions from pandas import SparseArray X = pd.DataFrame({"A": SparseArray(np.random.permutation([0, 1, 2] * 100)), "B": SparseArray(np.random.permutation([0.0, 0.1, 0.2, -0.1, 0.2] * 60)), "C": SparseArray(np.random.permutation([True, False] * 150))}) y = pd.Series(SparseArray(np.random.permutation([0, 1] * 150))) X_test = pd.DataFrame({"A": SparseArray(np.random.permutation([0, 2] * 30)), "B": SparseArray(np.random.permutation([0.0, 0.1, 0.2, -0.1] * 15)), "C": SparseArray(np.random.permutation([True, False] * 30))}) if pd.__version__ >= '0.24.0': for dtype in pd.concat([X.dtypes, X_test.dtypes, pd.Series(y.dtypes)]): self.assertTrue(pd.api.types.is_sparse(dtype)) gbm = lgb.sklearn.LGBMClassifier(n_estimators=10).fit(X, y) pred_sparse = gbm.predict(X_test, raw_score=True) if hasattr(X_test, 'sparse'): pred_dense = gbm.predict(X_test.sparse.to_dense(), raw_score=True) else: pred_dense = gbm.predict(X_test.to_dense(), raw_score=True) np.testing.assert_allclose(pred_sparse, pred_dense) def test_predict(self): # With default params iris = load_iris(return_X_y=False) X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.2, random_state=42) gbm = lgb.train({'objective': 'multiclass', 'num_class': 3, 'verbose': -1}, lgb.Dataset(X_train, y_train)) clf = lgb.LGBMClassifier(verbose=-1).fit(X_train, y_train) # Tests same probabilities res_engine = gbm.predict(X_test) res_sklearn = clf.predict_proba(X_test) np.testing.assert_allclose(res_engine, res_sklearn) # Tests same predictions res_engine = np.argmax(gbm.predict(X_test), axis=1) res_sklearn = clf.predict(X_test) np.testing.assert_equal(res_engine, res_sklearn) # Tests same raw scores res_engine = gbm.predict(X_test, raw_score=True) res_sklearn = clf.predict(X_test, raw_score=True) np.testing.assert_allclose(res_engine, res_sklearn) # Tests same leaf indices res_engine = gbm.predict(X_test, pred_leaf=True) res_sklearn = clf.predict(X_test, pred_leaf=True) np.testing.assert_equal(res_engine, res_sklearn) # Tests same feature contributions res_engine = gbm.predict(X_test, pred_contrib=True) res_sklearn = clf.predict(X_test, pred_contrib=True) np.testing.assert_allclose(res_engine, res_sklearn) # Tests other parameters for the prediction works res_engine = gbm.predict(X_test) res_sklearn_params = clf.predict_proba(X_test, pred_early_stop=True, pred_early_stop_margin=1.0) self.assertRaises(AssertionError, np.testing.assert_allclose, res_engine, res_sklearn_params) # Tests start_iteration # Tests same probabilities, starting from iteration 10 res_engine = gbm.predict(X_test, start_iteration=10) res_sklearn = clf.predict_proba(X_test, start_iteration=10) np.testing.assert_allclose(res_engine, res_sklearn) # Tests same predictions, starting from iteration 10 res_engine = np.argmax(gbm.predict(X_test, start_iteration=10), axis=1) res_sklearn = clf.predict(X_test, start_iteration=10) np.testing.assert_equal(res_engine, res_sklearn) # Tests same raw scores, starting from iteration 10 res_engine = gbm.predict(X_test, raw_score=True, start_iteration=10) res_sklearn = clf.predict(X_test, raw_score=True, start_iteration=10) np.testing.assert_allclose(res_engine, res_sklearn) # Tests same leaf indices, starting from iteration 10 res_engine = gbm.predict(X_test, pred_leaf=True, start_iteration=10) res_sklearn = clf.predict(X_test, pred_leaf=True, start_iteration=10) np.testing.assert_equal(res_engine, res_sklearn) # Tests same feature contributions, starting from iteration 10 res_engine = gbm.predict(X_test, pred_contrib=True, start_iteration=10) res_sklearn = clf.predict(X_test, pred_contrib=True, start_iteration=10) np.testing.assert_allclose(res_engine, res_sklearn) # Tests other parameters for the prediction works, starting from iteration 10 res_engine = gbm.predict(X_test, start_iteration=10) res_sklearn_params = clf.predict_proba(X_test, pred_early_stop=True, pred_early_stop_margin=1.0, start_iteration=10) self.assertRaises(AssertionError, np.testing.assert_allclose, res_engine, res_sklearn_params) def test_evaluate_train_set(self): X, y = load_boston(return_X_y=True) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=42) gbm = lgb.LGBMRegressor(n_estimators=10, silent=True) gbm.fit(X_train, y_train, eval_set=[(X_train, y_train), (X_test, y_test)], verbose=False) self.assertEqual(len(gbm.evals_result_), 2) self.assertIn('training', gbm.evals_result_) self.assertEqual(len(gbm.evals_result_['training']), 1) self.assertIn('l2', gbm.evals_result_['training']) self.assertIn('valid_1', gbm.evals_result_) self.assertEqual(len(gbm.evals_result_['valid_1']), 1) self.assertIn('l2', gbm.evals_result_['valid_1']) def test_metrics(self): X, y = load_boston(return_X_y=True) params = {'n_estimators': 2, 'verbose': -1} params_fit = {'X': X, 'y': y, 'eval_set': (X, y), 'verbose': False} # no custom objective, no custom metric # default metric gbm = lgb.LGBMRegressor(**params).fit(**params_fit) self.assertEqual(len(gbm.evals_result_['training']), 1) self.assertIn('l2', gbm.evals_result_['training']) # non-default metric gbm = lgb.LGBMRegressor(metric='mape', **params).fit(**params_fit) self.assertEqual(len(gbm.evals_result_['training']), 1) self.assertIn('mape', gbm.evals_result_['training']) # no metric gbm = lgb.LGBMRegressor(metric='None', **params).fit(**params_fit) self.assertIs(gbm.evals_result_, None) # non-default metric in eval_metric gbm = lgb.LGBMRegressor(**params).fit(eval_metric='mape', **params_fit) self.assertEqual(len(gbm.evals_result_['training']), 2) self.assertIn('l2', gbm.evals_result_['training']) self.assertIn('mape', gbm.evals_result_['training']) # non-default metric with non-default metric in eval_metric gbm = lgb.LGBMRegressor(metric='gamma', **params).fit(eval_metric='mape', **params_fit) self.assertEqual(len(gbm.evals_result_['training']), 2) self.assertIn('gamma', gbm.evals_result_['training']) self.assertIn('mape', gbm.evals_result_['training']) # non-default metric with multiple metrics in eval_metric gbm = lgb.LGBMRegressor(metric='gamma', **params).fit(eval_metric=['l2', 'mape'], **params_fit) self.assertEqual(len(gbm.evals_result_['training']), 3) self.assertIn('gamma', gbm.evals_result_['training']) self.assertIn('l2', gbm.evals_result_['training']) self.assertIn('mape', gbm.evals_result_['training']) # non-default metric with multiple metrics in eval_metric for LGBMClassifier X_classification, y_classification = load_breast_cancer(return_X_y=True) params_classification = {'n_estimators': 2, 'verbose': -1, 'objective': 'binary', 'metric': 'binary_logloss'} params_fit_classification = {'X': X_classification, 'y': y_classification, 'eval_set': (X_classification, y_classification), 'verbose': False} gbm = lgb.LGBMClassifier(**params_classification).fit(eval_metric=['fair', 'error'], **params_fit_classification) self.assertEqual(len(gbm.evals_result_['training']), 3) self.assertIn('fair', gbm.evals_result_['training']) self.assertIn('binary_error', gbm.evals_result_['training']) self.assertIn('binary_logloss', gbm.evals_result_['training']) # default metric for non-default objective gbm = lgb.LGBMRegressor(objective='regression_l1', **params).fit(**params_fit) self.assertEqual(len(gbm.evals_result_['training']), 1) self.assertIn('l1', gbm.evals_result_['training']) # non-default metric for non-default objective gbm = lgb.LGBMRegressor(objective='regression_l1', metric='mape', **params).fit(**params_fit) self.assertEqual(len(gbm.evals_result_['training']), 1) self.assertIn('mape', gbm.evals_result_['training']) # no metric gbm = lgb.LGBMRegressor(objective='regression_l1', metric='None', **params).fit(**params_fit) self.assertIs(gbm.evals_result_, None) # non-default metric in eval_metric for non-default objective gbm = lgb.LGBMRegressor(objective='regression_l1', **params).fit(eval_metric='mape', **params_fit) self.assertEqual(len(gbm.evals_result_['training']), 2) self.assertIn('l1', gbm.evals_result_['training']) self.assertIn('mape', gbm.evals_result_['training']) # non-default metric with non-default metric in eval_metric for non-default objective gbm = lgb.LGBMRegressor(objective='regression_l1', metric='gamma', **params).fit(eval_metric='mape', **params_fit) self.assertEqual(len(gbm.evals_result_['training']), 2) self.assertIn('gamma', gbm.evals_result_['training']) self.assertIn('mape', gbm.evals_result_['training']) # non-default metric with multiple metrics in eval_metric for non-default objective gbm = lgb.LGBMRegressor(objective='regression_l1', metric='gamma', **params).fit(eval_metric=['l2', 'mape'], **params_fit) self.assertEqual(len(gbm.evals_result_['training']), 3) self.assertIn('gamma', gbm.evals_result_['training']) self.assertIn('l2', gbm.evals_result_['training']) self.assertIn('mape', gbm.evals_result_['training']) # custom objective, no custom metric # default regression metric for custom objective gbm = lgb.LGBMRegressor(objective=custom_dummy_obj, **params).fit(**params_fit) self.assertEqual(len(gbm.evals_result_['training']), 1) self.assertIn('l2', gbm.evals_result_['training']) # non-default regression metric for custom objective gbm = lgb.LGBMRegressor(objective=custom_dummy_obj, metric='mape', **params).fit(**params_fit) self.assertEqual(len(gbm.evals_result_['training']), 1) self.assertIn('mape', gbm.evals_result_['training']) # multiple regression metrics for custom objective gbm = lgb.LGBMRegressor(objective=custom_dummy_obj, metric=['l1', 'gamma'], **params).fit(**params_fit) self.assertEqual(len(gbm.evals_result_['training']), 2) self.assertIn('l1', gbm.evals_result_['training']) self.assertIn('gamma', gbm.evals_result_['training']) # no metric gbm = lgb.LGBMRegressor(objective=custom_dummy_obj, metric='None', **params).fit(**params_fit) self.assertIs(gbm.evals_result_, None) # default regression metric with non-default metric in eval_metric for custom objective gbm = lgb.LGBMRegressor(objective=custom_dummy_obj, **params).fit(eval_metric='mape', **params_fit) self.assertEqual(len(gbm.evals_result_['training']), 2) self.assertIn('l2', gbm.evals_result_['training']) self.assertIn('mape', gbm.evals_result_['training']) # non-default regression metric with metric in eval_metric for custom objective gbm = lgb.LGBMRegressor(objective=custom_dummy_obj, metric='mape', **params).fit(eval_metric='gamma', **params_fit) self.assertEqual(len(gbm.evals_result_['training']), 2) self.assertIn('mape', gbm.evals_result_['training']) self.assertIn('gamma', gbm.evals_result_['training']) # multiple regression metrics with metric in eval_metric for custom objective gbm = lgb.LGBMRegressor(objective=custom_dummy_obj, metric=['l1', 'gamma'], **params).fit(eval_metric='l2', **params_fit) self.assertEqual(len(gbm.evals_result_['training']), 3) self.assertIn('l1', gbm.evals_result_['training']) self.assertIn('gamma', gbm.evals_result_['training']) self.assertIn('l2', gbm.evals_result_['training']) # multiple regression metrics with multiple metrics in eval_metric for custom objective gbm = lgb.LGBMRegressor(objective=custom_dummy_obj, metric=['l1', 'gamma'], **params).fit(eval_metric=['l2', 'mape'], **params_fit) self.assertEqual(len(gbm.evals_result_['training']), 4) self.assertIn('l1', gbm.evals_result_['training']) self.assertIn('gamma', gbm.evals_result_['training']) self.assertIn('l2', gbm.evals_result_['training']) self.assertIn('mape', gbm.evals_result_['training']) # no custom objective, custom metric # default metric with custom metric gbm = lgb.LGBMRegressor(**params).fit(eval_metric=constant_metric, **params_fit) self.assertEqual(len(gbm.evals_result_['training']), 2) self.assertIn('l2', gbm.evals_result_['training']) self.assertIn('error', gbm.evals_result_['training']) # non-default metric with custom metric gbm = lgb.LGBMRegressor(metric='mape', **params).fit(eval_metric=constant_metric, **params_fit) self.assertEqual(len(gbm.evals_result_['training']), 2) self.assertIn('mape', gbm.evals_result_['training']) self.assertIn('error', gbm.evals_result_['training']) # multiple metrics with custom metric gbm = lgb.LGBMRegressor(metric=['l1', 'gamma'], **params).fit(eval_metric=constant_metric, **params_fit) self.assertEqual(len(gbm.evals_result_['training']), 3) self.assertIn('l1', gbm.evals_result_['training']) self.assertIn('gamma', gbm.evals_result_['training']) self.assertIn('error', gbm.evals_result_['training']) # custom metric (disable default metric) gbm = lgb.LGBMRegressor(metric='None', **params).fit(eval_metric=constant_metric, **params_fit) self.assertEqual(len(gbm.evals_result_['training']), 1) self.assertIn('error', gbm.evals_result_['training']) # default metric for non-default objective with custom metric gbm = lgb.LGBMRegressor(objective='regression_l1', **params).fit(eval_metric=constant_metric, **params_fit) self.assertEqual(len(gbm.evals_result_['training']), 2) self.assertIn('l1', gbm.evals_result_['training']) self.assertIn('error', gbm.evals_result_['training']) # non-default metric for non-default objective with custom metric gbm = lgb.LGBMRegressor(objective='regression_l1', metric='mape', **params).fit(eval_metric=constant_metric, **params_fit) self.assertEqual(len(gbm.evals_result_['training']), 2) self.assertIn('mape', gbm.evals_result_['training']) self.assertIn('error', gbm.evals_result_['training']) # multiple metrics for non-default objective with custom metric gbm = lgb.LGBMRegressor(objective='regression_l1', metric=['l1', 'gamma'], **params).fit(eval_metric=constant_metric, **params_fit) self.assertEqual(len(gbm.evals_result_['training']), 3) self.assertIn('l1', gbm.evals_result_['training']) self.assertIn('gamma', gbm.evals_result_['training']) self.assertIn('error', gbm.evals_result_['training']) # custom metric (disable default metric for non-default objective) gbm = lgb.LGBMRegressor(objective='regression_l1', metric='None', **params).fit(eval_metric=constant_metric, **params_fit) self.assertEqual(len(gbm.evals_result_['training']), 1) self.assertIn('error', gbm.evals_result_['training']) # custom objective, custom metric # custom metric for custom objective gbm = lgb.LGBMRegressor(objective=custom_dummy_obj, **params).fit(eval_metric=constant_metric, **params_fit) self.assertEqual(len(gbm.evals_result_['training']), 1) self.assertIn('error', gbm.evals_result_['training']) # non-default regression metric with custom metric for custom objective gbm = lgb.LGBMRegressor(objective=custom_dummy_obj, metric='mape', **params).fit(eval_metric=constant_metric, **params_fit) self.assertEqual(len(gbm.evals_result_['training']), 2) self.assertIn('mape', gbm.evals_result_['training']) self.assertIn('error', gbm.evals_result_['training']) # multiple regression metrics with custom metric for custom objective gbm = lgb.LGBMRegressor(objective=custom_dummy_obj, metric=['l2', 'mape'], **params).fit(eval_metric=constant_metric, **params_fit) self.assertEqual(len(gbm.evals_result_['training']), 3) self.assertIn('l2', gbm.evals_result_['training']) self.assertIn('mape', gbm.evals_result_['training']) self.assertIn('error', gbm.evals_result_['training']) X, y = load_digits(n_class=3, return_X_y=True) params_fit = {'X': X, 'y': y, 'eval_set': (X, y), 'verbose': False} # default metric and invalid binary metric is replaced with multiclass alternative gbm = lgb.LGBMClassifier(**params).fit(eval_metric='binary_error', **params_fit) self.assertEqual(len(gbm.evals_result_['training']), 2) self.assertIn('multi_logloss', gbm.evals_result_['training']) self.assertIn('multi_error', gbm.evals_result_['training']) # invalid objective is replaced with default multiclass one # and invalid binary metric is replaced with multiclass alternative gbm = lgb.LGBMClassifier(objective='invalid_obj', **params).fit(eval_metric='binary_error', **params_fit) self.assertEqual(gbm.objective_, 'multiclass') self.assertEqual(len(gbm.evals_result_['training']), 2) self.assertIn('multi_logloss', gbm.evals_result_['training']) self.assertIn('multi_error', gbm.evals_result_['training']) # default metric for non-default multiclass objective # and invalid binary metric is replaced with multiclass alternative gbm = lgb.LGBMClassifier(objective='ovr', **params).fit(eval_metric='binary_error', **params_fit) self.assertEqual(gbm.objective_, 'ovr') self.assertEqual(len(gbm.evals_result_['training']), 2) self.assertIn('multi_logloss', gbm.evals_result_['training']) self.assertIn('multi_error', gbm.evals_result_['training']) X, y = load_digits(n_class=2, return_X_y=True) params_fit = {'X': X, 'y': y, 'eval_set': (X, y), 'verbose': False} # default metric and invalid multiclass metric is replaced with binary alternative gbm = lgb.LGBMClassifier(**params).fit(eval_metric='multi_error', **params_fit) self.assertEqual(len(gbm.evals_result_['training']), 2) self.assertIn('binary_logloss', gbm.evals_result_['training']) self.assertIn('binary_error', gbm.evals_result_['training']) # invalid multiclass metric is replaced with binary alternative for custom objective gbm = lgb.LGBMClassifier(objective=custom_dummy_obj, **params).fit(eval_metric='multi_logloss', **params_fit) self.assertEqual(len(gbm.evals_result_['training']), 1) self.assertIn('binary_logloss', gbm.evals_result_['training']) def test_inf_handle(self): nrows = 100 ncols = 10 X = np.random.randn(nrows, ncols) y = np.random.randn(nrows) + np.full(nrows, 1e30) weight = np.full(nrows, 1e10) params = {'n_estimators': 20, 'verbose': -1} params_fit = {'X': X, 'y': y, 'sample_weight': weight, 'eval_set': (X, y), 'verbose': False, 'early_stopping_rounds': 5} gbm = lgb.LGBMRegressor(**params).fit(**params_fit) np.testing.assert_allclose(gbm.evals_result_['training']['l2'], np.inf) def test_nan_handle(self): nrows = 100 ncols = 10 X = np.random.randn(nrows, ncols) y = np.random.randn(nrows) + np.full(nrows, 1e30) weight = np.zeros(nrows) params = {'n_estimators': 20, 'verbose': -1} params_fit = {'X': X, 'y': y, 'sample_weight': weight, 'eval_set': (X, y), 'verbose': False, 'early_stopping_rounds': 5} gbm = lgb.LGBMRegressor(**params).fit(**params_fit) np.testing.assert_allclose(gbm.evals_result_['training']['l2'], np.nan) def test_first_metric_only(self): def fit_and_check(eval_set_names, metric_names, assumed_iteration, first_metric_only): params['first_metric_only'] = first_metric_only gbm = lgb.LGBMRegressor(**params).fit(**params_fit) self.assertEqual(len(gbm.evals_result_), len(eval_set_names)) for eval_set_name in eval_set_names: self.assertIn(eval_set_name, gbm.evals_result_) self.assertEqual(len(gbm.evals_result_[eval_set_name]), len(metric_names)) for metric_name in metric_names: self.assertIn(metric_name, gbm.evals_result_[eval_set_name]) actual = len(gbm.evals_result_[eval_set_name][metric_name]) expected = assumed_iteration + (params_fit['early_stopping_rounds'] if eval_set_name != 'training' and assumed_iteration != gbm.n_estimators else 0) self.assertEqual(expected, actual) self.assertEqual(assumed_iteration if eval_set_name != 'training' else gbm.n_estimators, gbm.best_iteration_) X, y = load_boston(return_X_y=True) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) X_test1, X_test2, y_test1, y_test2 = train_test_split(X_test, y_test, test_size=0.5, random_state=72) params = {'n_estimators': 30, 'learning_rate': 0.8, 'num_leaves': 15, 'verbose': -1, 'seed': 123} params_fit = {'X': X_train, 'y': y_train, 'early_stopping_rounds': 5, 'verbose': False} iter_valid1_l1 = 3 iter_valid1_l2 = 18 iter_valid2_l1 = 11 iter_valid2_l2 = 7 self.assertEqual(len(set([iter_valid1_l1, iter_valid1_l2, iter_valid2_l1, iter_valid2_l2])), 4) iter_min_l1 = min([iter_valid1_l1, iter_valid2_l1]) iter_min_l2 = min([iter_valid1_l2, iter_valid2_l2]) iter_min = min([iter_min_l1, iter_min_l2]) iter_min_valid1 = min([iter_valid1_l1, iter_valid1_l2]) # training data as eval_set params_fit['eval_set'] = (X_train, y_train) fit_and_check(['training'], ['l2'], 30, False) fit_and_check(['training'], ['l2'], 30, True) # feval params['metric'] = 'None' params_fit['eval_metric'] = lambda preds, train_data: [decreasing_metric(preds, train_data), constant_metric(preds, train_data)] params_fit['eval_set'] = (X_test1, y_test1) fit_and_check(['valid_0'], ['decreasing_metric', 'error'], 1, False) fit_and_check(['valid_0'], ['decreasing_metric', 'error'], 30, True) params_fit['eval_metric'] = lambda preds, train_data: [constant_metric(preds, train_data), decreasing_metric(preds, train_data)] fit_and_check(['valid_0'], ['decreasing_metric', 'error'], 1, True) # single eval_set params.pop('metric') params_fit.pop('eval_metric') fit_and_check(['valid_0'], ['l2'], iter_valid1_l2, False) fit_and_check(['valid_0'], ['l2'], iter_valid1_l2, True) params_fit['eval_metric'] = "l2" fit_and_check(['valid_0'], ['l2'], iter_valid1_l2, False) fit_and_check(['valid_0'], ['l2'], iter_valid1_l2, True) params_fit['eval_metric'] = "l1" fit_and_check(['valid_0'], ['l1', 'l2'], iter_min_valid1, False) fit_and_check(['valid_0'], ['l1', 'l2'], iter_valid1_l1, True) params_fit['eval_metric'] = ["l1", "l2"] fit_and_check(['valid_0'], ['l1', 'l2'], iter_min_valid1, False) fit_and_check(['valid_0'], ['l1', 'l2'], iter_valid1_l1, True) params_fit['eval_metric'] = ["l2", "l1"] fit_and_check(['valid_0'], ['l1', 'l2'], iter_min_valid1, False) fit_and_check(['valid_0'], ['l1', 'l2'], iter_valid1_l2, True) params_fit['eval_metric'] = ["l2", "regression", "mse"] # test aliases fit_and_check(['valid_0'], ['l2'], iter_valid1_l2, False) fit_and_check(['valid_0'], ['l2'], iter_valid1_l2, True) # two eval_set params_fit['eval_set'] = [(X_test1, y_test1), (X_test2, y_test2)] params_fit['eval_metric'] = ["l1", "l2"] fit_and_check(['valid_0', 'valid_1'], ['l1', 'l2'], iter_min_l1, True) params_fit['eval_metric'] = ["l2", "l1"] fit_and_check(['valid_0', 'valid_1'], ['l1', 'l2'], iter_min_l2, True) params_fit['eval_set'] = [(X_test2, y_test2), (X_test1, y_test1)] params_fit['eval_metric'] = ["l1", "l2"] fit_and_check(['valid_0', 'valid_1'], ['l1', 'l2'], iter_min, False) fit_and_check(['valid_0', 'valid_1'], ['l1', 'l2'], iter_min_l1, True) params_fit['eval_metric'] = ["l2", "l1"] fit_and_check(['valid_0', 'valid_1'], ['l1', 'l2'], iter_min, False) fit_and_check(['valid_0', 'valid_1'], ['l1', 'l2'], iter_min_l2, True) def test_class_weight(self): X, y = load_digits(n_class=10, return_X_y=True) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) y_train_str = y_train.astype('str') y_test_str = y_test.astype('str') gbm = lgb.LGBMClassifier(n_estimators=10, class_weight='balanced', silent=True) gbm.fit(X_train, y_train, eval_set=[(X_train, y_train), (X_test, y_test), (X_test, y_test), (X_test, y_test), (X_test, y_test)], eval_class_weight=['balanced', None, 'balanced', {1: 10, 4: 20}, {5: 30, 2: 40}], verbose=False) for eval_set1, eval_set2 in itertools.combinations(gbm.evals_result_.keys(), 2): for metric in gbm.evals_result_[eval_set1]: np.testing.assert_raises(AssertionError, np.testing.assert_allclose, gbm.evals_result_[eval_set1][metric], gbm.evals_result_[eval_set2][metric]) gbm_str = lgb.LGBMClassifier(n_estimators=10, class_weight='balanced', silent=True) gbm_str.fit(X_train, y_train_str, eval_set=[(X_train, y_train_str), (X_test, y_test_str), (X_test, y_test_str), (X_test, y_test_str), (X_test, y_test_str)], eval_class_weight=['balanced', None, 'balanced', {'1': 10, '4': 20}, {'5': 30, '2': 40}], verbose=False) for eval_set1, eval_set2 in itertools.combinations(gbm_str.evals_result_.keys(), 2): for metric in gbm_str.evals_result_[eval_set1]: np.testing.assert_raises(AssertionError, np.testing.assert_allclose, gbm_str.evals_result_[eval_set1][metric], gbm_str.evals_result_[eval_set2][metric]) for eval_set in gbm.evals_result_: for metric in gbm.evals_result_[eval_set]: np.testing.assert_allclose(gbm.evals_result_[eval_set][metric], gbm_str.evals_result_[eval_set][metric]) def test_continue_training_with_model(self): X, y = load_digits(n_class=3, return_X_y=True) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=42) init_gbm = lgb.LGBMClassifier(n_estimators=5).fit(X_train, y_train, eval_set=(X_test, y_test), verbose=False) gbm = lgb.LGBMClassifier(n_estimators=5).fit(X_train, y_train, eval_set=(X_test, y_test), verbose=False, init_model=init_gbm) self.assertEqual(len(init_gbm.evals_result_['valid_0']['multi_logloss']), len(gbm.evals_result_['valid_0']['multi_logloss'])) self.assertEqual(len(init_gbm.evals_result_['valid_0']['multi_logloss']), 5) self.assertLess(gbm.evals_result_['valid_0']['multi_logloss'][-1], init_gbm.evals_result_['valid_0']['multi_logloss'][-1]) # sklearn < 0.22 requires passing "attributes" argument @unittest.skipIf(sk_version < '0.22.0', 'scikit-learn version is less than 0.22') def test_check_is_fitted(self): X, y = load_digits(n_class=2, return_X_y=True) est = lgb.LGBMModel(n_estimators=5, objective="binary") clf = lgb.LGBMClassifier(n_estimators=5) reg = lgb.LGBMRegressor(n_estimators=5) rnk = lgb.LGBMRanker(n_estimators=5) models = (est, clf, reg, rnk) for model in models: self.assertRaises(lgb.compat.LGBMNotFittedError, check_is_fitted, model) est.fit(X, y) clf.fit(X, y) reg.fit(X, y) rnk.fit(X, y, group=np.ones(X.shape[0])) for model in models: check_is_fitted(model)
1
25,329
Same about new metrics. Can we avoid adding them?
microsoft-LightGBM
cpp
@@ -40,6 +40,15 @@ def run(): group.add_argument('--cloudsql-region', help='The Cloud SQL region') + network = parser.add_argument_group(title='network') + network.add_argument('--network-host-project-id', + help='The project id that is hosting the network ' + 'resources.') + network.add_argument('--vpc-name', + help='The VPC name where Forseti VM will run.') + network.add_argument('--subnet-name', + help='The subnetwork name where Forseti VM will run.') + email_params = parser.add_argument_group(title='email') email_params.add_argument('--sendgrid-api-key', help='Sendgrid API key')
1
# Copyright 2017 The Forseti Security 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. """Set up the gcloud environment and Forseti prerequisites. This has been tested with python 2.7. """ import argparse from environment import gcloud_env def run(): """Run the steps for the gcloud setup.""" parser = argparse.ArgumentParser() parser.add_argument('--no-cloudshell', action='store_true', help='Bypass Cloud Shell requirement') parser.add_argument('--no-iam-check', action='store_true', help='Bypass IAM check for user running script') parser.add_argument('--branch', help='Which Forseti branch to deploy') group = parser.add_argument_group(title='regions') group.add_argument('--gcs-location', help='The GCS bucket location') group.add_argument('--cloudsql-region', help='The Cloud SQL region') email_params = parser.add_argument_group(title='email') email_params.add_argument('--sendgrid-api-key', help='Sendgrid API key') email_params.add_argument('--notification-recipient-email', help='Notification recipient email') email_params.add_argument('--gsuite-superadmin-email', help='G Suite super admin email') args = vars(parser.parse_args()) forseti_setup = gcloud_env.ForsetiGcpSetup(**args) forseti_setup.run_setup() if __name__ == '__main__': run()
1
28,123
I know this is a port from the previous PR, but I am wondering if we can take the chance to improve the naming? `--vpc-host-project-id` ?
forseti-security-forseti-security
py
@@ -228,7 +228,7 @@ describe('Formulas general', () => { afterChange, }); - hot.getSourceData()[1][1] = 20; + hot.setSourceDataAtCell(1, 1, 20); hot.getPlugin('formulas').recalculateFull(); hot.render();
1
describe('Formulas general', () => { const id = 'testContainer'; beforeEach(function() { this.$container = $(`<div id="${id}"></div>`).appendTo('body'); }); afterEach(function() { if (this.$container) { destroy(); this.$container.remove(); } }); it('should calculate table (simple example)', () => { const hot = handsontable({ data: getDataSimpleExampleFormulas(), formulas: true, width: 500, height: 300 }); expect(hot.getDataAtRow(0)).toEqual([0, 'Maserati', 'Mazda', 'Mercedes', 'Mini', 0]); expect(hot.getDataAtRow(1)).toEqual([2009, 0, 2941, 4303, 354, 5814]); expect(hot.getDataAtRow(2)).toEqual([2010, 5, 2905, 2867, 2016, 'Maserati']); expect(hot.getDataAtRow(3)).toEqual([2011, 4, 2517, 4822, 552, 6127]); expect(hot.getDataAtRow(4)).toEqual([2012, 8042, 10058, '#DIV/0!', 12, '\'=SUM(E5)']); }); it('should calculate table (advanced example)', () => { const hot = handsontable({ data: getDataAdvancedExampleFormulas(), formulas: true, width: 500, height: 300 }); expect(hot.getDataAtRow(0)).toEqual(['Example #1', '', '', '', '', '', '', '']); expect(hot.getDataAtRow(1)).toEqual(['Text', 'yellow', 'red', 'blue', 'green', 'pink', 'gray', '']); expect(hot.getDataAtRow(2)).toEqual(['Yellow dog on green grass', 'yellow', '', '', 'green', '', '', '']); expect(hot.getDataAtRow(3)).toEqual(['Gray sweater with blue stripes', '', '', 'blue', '', '', 'gray', '']); expect(hot.getDataAtRow(4)).toEqual(['A red sun on a pink horizon', '', 'red', '', '', 'pink', '', '']); expect(hot.getDataAtRow(5)).toEqual(['Blue neon signs everywhere', '', '', 'blue', '', '', '', '']); expect(hot.getDataAtRow(6)).toEqual(['Waves of blue and green', '', '', 'blue', 'green', '', '', '']); expect(hot.getDataAtRow(7)).toEqual(['Hot pink socks and gray socks', '', '', '', '', 'pink', 'gray', '']); expect(hot.getDataAtRow(8)).toEqual(['Deep blue eyes', '', '', 'blue', '', '', '', '']); expect(hot.getDataAtRow(9)).toEqual(['Count of colors', 1, 1, 4, 2, 2, 2, 'SUM: 12']); expect(hot.getDataAtRow(10)).toEqual(['', '', '', '', '', '', '', '']); expect(hot.getDataAtRow(11)).toEqual(['Example #2', '', '', '', '', '', '', '']); expect(hot.getDataAtRow(12)).toEqual(['Name', 'Email', 'Email domain', '', '', '', '', '']); expect(hot.getDataAtRow(13)).toEqual(['Ann Chang', '[email protected]', 'maaker.com', '', '', '', '', '']); expect(hot.getDataAtRow(14)).toEqual(['Jan Siuk', '[email protected]', 'yahoo.com', '', '', '', '', '']); expect(hot.getDataAtRow(15)).toEqual(['Ken Siuk', '[email protected]', 'gmail.com', '', '', '', '', '']); expect(hot.getDataAtRow(16)).toEqual(['Marcin Kowalski', '[email protected]', 'syndex.pl', '', '', '', '', '']); }); it('should not treat single equality sign (=) as a formula expression', () => { const hot = handsontable({ data: [['=', '=3']], formulas: true, width: 500, height: 300 }); expect(hot.getDataAtCell(0, 0)).toBe('='); expect(hot.getDataAtCell(0, 1)).toBe(3); hot.setDataAtCell(0, 1, '='); expect(hot.getDataAtCell(0, 0)).toBe('='); expect(hot.getDataAtCell(0, 1)).toBe('='); }); it('should calculate table with semicolon as separator of formula arguments', () => { const data = getDataSimpleExampleFormulas(); data[2][4] = '=SUM(A4;2;3)'; data[4][2] = '=SUM(B5;E3)'; const hot = handsontable({ data, formulas: true, width: 500, height: 300 }); expect(hot.getDataAtRow(0)).toEqual([0, 'Maserati', 'Mazda', 'Mercedes', 'Mini', 0]); expect(hot.getDataAtRow(1)).toEqual([2009, 0, 2941, 4303, 354, 5814]); expect(hot.getDataAtRow(2)).toEqual([2010, 5, 2905, 2867, 2016, 'Maserati']); expect(hot.getDataAtRow(3)).toEqual([2011, 4, 2517, 4822, 552, 6127]); expect(hot.getDataAtRow(4)).toEqual([2012, 8042, 10058, '#DIV/0!', 12, '\'=SUM(E5)']); }); it('should recalculate table with formulas defined where the next cell is depend on the previous cell', () => { const afterChange = jasmine.createSpy(); const hot = handsontable({ data: getDataSimpleExampleFormulas(), formulas: true, width: 500, height: 300, afterChange, }); hot.setDataAtCell(0, 1, '=B5'); hot.setDataAtCell(0, 2, '=B1'); hot.setDataAtCell(0, 3, '=C1'); hot.setDataAtCell(4, 5, '=D1'); expect(hot.getDataAtRow(0)).toEqual([0, 8042, 8042, 8042, 'Mini', 0]); expect(hot.getDataAtRow(1)).toEqual([2009, 0, 2941, 4303, 354, 5814]); expect(hot.getDataAtRow(2)).toEqual([2010, 5, 2905, 2867, 2016, 8042]); expect(hot.getDataAtRow(3)).toEqual([2011, 4, 2517, 4822, 552, 6127]); expect(hot.getDataAtRow(4)).toEqual([2012, 8042, 10058, '#DIV/0!', 12, 8042]); hot.setDataAtCell(1, 0, 10); expect(hot.getDataAtRow(0)).toEqual([0, 6043, 6043, 6043, 'Mini', 0]); expect(hot.getDataAtRow(1)).toEqual([10, 0, 2941, 4303, 354, 5814]); expect(hot.getDataAtRow(2)).toEqual([2010, 5, 2905, 2867, 2016, 6043]); expect(hot.getDataAtRow(3)).toEqual([2011, 4, 2517, 4822, 552, 6127]); expect(hot.getDataAtRow(4)).toEqual([2012, 6043, 8059, '#DIV/0!', 12, 6043]); }); it('should throw error while parsing invalid cell coordinates syntax', () => { const data = getDataSimpleExampleFormulas(); data[0][0] = '=SUM($$A4;2;3)'; data[0][1] = '=A$$$$$1'; data[0][2] = '=A1$'; data[0][3] = '=SUM(A2:D2$)'; const hot = handsontable({ data, formulas: true, width: 500, height: 300 }); hot.setDataAtCell(2, 0, '=A1$'); hot.setDataAtCell(3, 0, '=$A$$1'); expect(hot.getDataAtRow(0)).toEqual(['#ERROR!', '#ERROR!', '#ERROR!', '#ERROR!', 'Mini', '#ERROR!']); expect(hot.getDataAtRow(1)).toEqual([2009, 0, 2941, 4303, 354, 5814]); expect(hot.getDataAtRow(2)).toEqual(['#ERROR!', 5, 2905, 2867, '#ERROR!', '#ERROR!']); expect(hot.getDataAtRow(3)).toEqual(['#ERROR!', 4, 2517, 4822, 552, 6127]); expect(hot.getDataAtRow(4)).toEqual([2012, '#ERROR!', '#ERROR!', '#DIV/0!', 12, '\'=SUM(E5)']); }); it('should return correct values according to plugin state updated by updateSettings()', () => { const hot = handsontable({ data: getDataSimpleExampleFormulas(), formulas: true, width: 500, height: 300 }); hot.updateSettings({ formulas: false }); expect(hot.getDataAtRow(0)).toEqual(['=$B$2', 'Maserati', 'Mazda', 'Mercedes', 'Mini', '=A$1']); expect(hot.getDataAtRow(1)).toEqual([2009, 0, 2941, 4303, 354, 5814]); expect(hot.getDataAtRow(2)).toEqual([2010, 5, 2905, 2867, '=SUM(A4,2,3)', '=$B1']); expect(hot.getDataAtRow(3)).toEqual([2011, 4, 2517, 4822, 552, 6127]); expect(hot.getDataAtRow(4)).toEqual([2012, '=Sum(a2:a5)', '=SUM(B5,E3)', '=A2/B2', 12, '\'=SUM(E5)']); hot.updateSettings({ formulas: true }); expect(hot.getDataAtRow(0)).toEqual([0, 'Maserati', 'Mazda', 'Mercedes', 'Mini', 0]); expect(hot.getDataAtRow(1)).toEqual([2009, 0, 2941, 4303, 354, 5814]); expect(hot.getDataAtRow(2)).toEqual([2010, 5, 2905, 2867, 2016, 'Maserati']); expect(hot.getDataAtRow(3)).toEqual([2011, 4, 2517, 4822, 552, 6127]); expect(hot.getDataAtRow(4)).toEqual([2012, 8042, 10058, '#DIV/0!', 12, '\'=SUM(E5)']); }); it('should return correct values according to plugin state updated by disablePlugin/enablePlugin methods', () => { const hot = handsontable({ data: getDataSimpleExampleFormulas(), formulas: true, width: 500, height: 300 }); hot.getPlugin('formulas').disablePlugin(); hot.render(); expect(hot.getDataAtRow(0)).toEqual(['=$B$2', 'Maserati', 'Mazda', 'Mercedes', 'Mini', '=A$1']); expect(hot.getDataAtRow(1)).toEqual([2009, 0, 2941, 4303, 354, 5814]); expect(hot.getDataAtRow(2)).toEqual([2010, 5, 2905, 2867, '=SUM(A4,2,3)', '=$B1']); expect(hot.getDataAtRow(3)).toEqual([2011, 4, 2517, 4822, 552, 6127]); expect(hot.getDataAtRow(4)).toEqual([2012, '=Sum(a2:a5)', '=SUM(B5,E3)', '=A2/B2', 12, '\'=SUM(E5)']); hot.getPlugin('formulas').enablePlugin(); hot.render(); expect(hot.getDataAtRow(0)).toEqual([0, 'Maserati', 'Mazda', 'Mercedes', 'Mini', 0]); expect(hot.getDataAtRow(1)).toEqual([2009, 0, 2941, 4303, 354, 5814]); expect(hot.getDataAtRow(2)).toEqual([2010, 5, 2905, 2867, 2016, 'Maserati']); expect(hot.getDataAtRow(3)).toEqual([2011, 4, 2517, 4822, 552, 6127]); expect(hot.getDataAtRow(4)).toEqual([2012, 8042, 10058, '#DIV/0!', 12, '\'=SUM(E5)']); }); it('should recalculate table after changing cell value (setDataAtCell)', () => { const afterChange = jasmine.createSpy(); const hot = handsontable({ data: getDataSimpleExampleFormulas(), formulas: true, width: 500, height: 300, afterChange, }); hot.setDataAtCell(1, 1, 20); expect(hot.getDataAtRow(0)).toEqual([20, 'Maserati', 'Mazda', 'Mercedes', 'Mini', 20]); expect(hot.getDataAtRow(1)).toEqual([2009, 20, 2941, 4303, 354, 5814]); expect(hot.getDataAtRow(2)).toEqual([2010, 5, 2905, 2867, 2016, 'Maserati']); expect(hot.getDataAtRow(3)).toEqual([2011, 4, 2517, 4822, 552, 6127]); expect(hot.getDataAtRow(4)).toEqual([2012, 8042, 10058, 100.45, 12, '\'=SUM(E5)']); expect(afterChange.calls.argsFor(1)).toEqual([[[1, 1, 0, 20]], 'edit', void 0, void 0, void 0, void 0]); }); it('should recalculate table after changing cell value (by reference)', () => { const afterChange = jasmine.createSpy(); const hot = handsontable({ data: getDataSimpleExampleFormulas(), formulas: true, width: 500, height: 300, afterChange, }); hot.getSourceData()[1][1] = 20; hot.getPlugin('formulas').recalculateFull(); hot.render(); expect(hot.getDataAtRow(0)).toEqual([20, 'Maserati', 'Mazda', 'Mercedes', 'Mini', 20]); expect(hot.getDataAtRow(1)).toEqual([2009, 20, 2941, 4303, 354, 5814]); expect(hot.getDataAtRow(2)).toEqual([2010, 5, 2905, 2867, 2016, 'Maserati']); expect(hot.getDataAtRow(3)).toEqual([2011, 4, 2517, 4822, 552, 6127]); expect(hot.getDataAtRow(4)).toEqual([2012, 8042, 10058, 100.45, 12, '\'=SUM(E5)']); }); it('should recalculate table after changing cell value into formula expression written in lower case', () => { const afterChange = jasmine.createSpy(); const hot = handsontable({ data: getDataSimpleExampleFormulas(), formulas: true, width: 500, height: 300, afterChange, }); hot.setDataAtCell(1, 1, '=Sum(a2:A4)'); expect(hot.getDataAtRow(0)).toEqual([6030, 'Maserati', 'Mazda', 'Mercedes', 'Mini', 6030]); expect(hot.getDataAtRow(1)).toEqual([2009, 6030, 2941, 4303, 354, 5814]); expect(hot.getDataAtRow(2)).toEqual([2010, 5, 2905, 2867, 2016, 'Maserati']); expect(hot.getDataAtRow(3)).toEqual([2011, 4, 2517, 4822, 552, 6127]); expect(hot.getDataAtRow(4)).toEqual([2012, 8042, 10058, 0.333167495854063, 12, '\'=SUM(E5)']); expect(afterChange.calls.argsFor(1)).toEqual([[[1, 1, 0, '=Sum(a2:A4)']], 'edit', void 0, void 0, void 0, void 0]); }); it('should prevent recalculate table after changing cell value into escaped formula expression', () => { const afterChange = jasmine.createSpy(); const hot = handsontable({ data: getDataSimpleExampleFormulas(), formulas: true, width: 500, height: 300, afterChange, }); hot.setDataAtCell(1, 1, '\'=SUM(A2:A4)'); expect(hot.getDataAtRow(0)).toEqual(['\'=SUM(A2:A4)', 'Maserati', 'Mazda', 'Mercedes', 'Mini', '\'=SUM(A2:A4)']); expect(hot.getDataAtRow(1)).toEqual([2009, '\'=SUM(A2:A4)', 2941, 4303, 354, 5814]); expect(hot.getDataAtRow(2)).toEqual([2010, 5, 2905, 2867, 2016, 'Maserati']); expect(hot.getDataAtRow(3)).toEqual([2011, 4, 2517, 4822, 552, 6127]); expect(hot.getDataAtRow(4)).toEqual([2012, 8042, 10058, '#VALUE!', 12, '\'=SUM(E5)']); expect(afterChange.calls.argsFor(1)).toEqual([[[1, 1, 0, '\'=SUM(A2:A4)']], 'edit', void 0, void 0, void 0, void 0]); }); it('should recalculate table after changing cell value from escaped formula expression into valid formula expression', () => { const afterChange = jasmine.createSpy(); const hot = handsontable({ data: getDataSimpleExampleFormulas(), formulas: true, width: 500, height: 300, afterChange, }); hot.setDataAtCell(4, 5, hot.getDataAtCell(4, 5).substr(1)); expect(hot.getDataAtRow(0)).toEqual([0, 'Maserati', 'Mazda', 'Mercedes', 'Mini', 0]); expect(hot.getDataAtRow(1)).toEqual([2009, 0, 2941, 4303, 354, 5814]); expect(hot.getDataAtRow(2)).toEqual([2010, 5, 2905, 2867, 2016, 'Maserati']); expect(hot.getDataAtRow(3)).toEqual([2011, 4, 2517, 4822, 552, 6127]); expect(hot.getDataAtRow(4)).toEqual([2012, 8042, 10058, '#DIV/0!', 12, 12]); expect(afterChange.calls.argsFor(1)).toEqual([[[4, 5, '\'=SUM(E5)', '=SUM(E5)']], 'edit', void 0, void 0, void 0, void 0]); }); it('should recalculate table after changing cell value from primitive value into formula expression', () => { const afterChange = jasmine.createSpy(); const hot = handsontable({ data: getDataSimpleExampleFormulas(), formulas: true, width: 500, height: 300, afterChange, }); hot.setDataAtCell(1, 1, '=SUM(A2:A4)'); expect(hot.getDataAtRow(0)).toEqual([6030, 'Maserati', 'Mazda', 'Mercedes', 'Mini', 6030]); expect(hot.getDataAtRow(1)).toEqual([2009, 6030, 2941, 4303, 354, 5814]); expect(hot.getDataAtRow(2)).toEqual([2010, 5, 2905, 2867, 2016, 'Maserati']); expect(hot.getDataAtRow(3)).toEqual([2011, 4, 2517, 4822, 552, 6127]); expect(hot.getDataAtRow(4)).toEqual([2012, 8042, 10058, 0.333167495854063, 12, '\'=SUM(E5)']); expect(afterChange.calls.argsFor(1)).toEqual([[[1, 1, 0, '=SUM(A2:A4)']], 'edit', void 0, void 0, void 0, void 0]); }); it('should recalculate table after changing cell value from formula expression into primitive value', () => { const afterChange = jasmine.createSpy(); const hot = handsontable({ data: getDataSimpleExampleFormulas(), formulas: true, width: 500, height: 300, afterChange, }); hot.setDataAtCell(4, 1, 15); expect(hot.getDataAtRow(0)).toEqual([0, 'Maserati', 'Mazda', 'Mercedes', 'Mini', 0]); expect(hot.getDataAtRow(1)).toEqual([2009, 0, 2941, 4303, 354, 5814]); expect(hot.getDataAtRow(2)).toEqual([2010, 5, 2905, 2867, 2016, 'Maserati']); expect(hot.getDataAtRow(3)).toEqual([2011, 4, 2517, 4822, 552, 6127]); expect(hot.getDataAtRow(4)).toEqual([2012, 15, 2031, '#DIV/0!', 12, '\'=SUM(E5)']); expect(afterChange.calls.argsFor(1)).toEqual([[[4, 1, '=Sum(a2:a5)', 15]], 'edit', void 0, void 0, void 0, void 0]); }); it('should recalculate table after changing cell value from formula expression into another formula expression', () => { const afterChange = jasmine.createSpy(); const hot = handsontable({ data: getDataSimpleExampleFormulas(), formulas: true, width: 500, height: 300, afterChange, }); hot.setDataAtCell(4, 1, '=SUM(A2:A4)'); expect(hot.getDataAtRow(0)).toEqual([0, 'Maserati', 'Mazda', 'Mercedes', 'Mini', 0]); expect(hot.getDataAtRow(1)).toEqual([2009, 0, 2941, 4303, 354, 5814]); expect(hot.getDataAtRow(2)).toEqual([2010, 5, 2905, 2867, 2016, 'Maserati']); expect(hot.getDataAtRow(3)).toEqual([2011, 4, 2517, 4822, 552, 6127]); expect(hot.getDataAtRow(4)).toEqual([2012, 6030, 8046, '#DIV/0!', 12, '\'=SUM(E5)']); expect(afterChange.calls.argsFor(1)).toEqual([[[4, 1, '=Sum(a2:a5)', '=SUM(A2:A4)']], 'edit', void 0, void 0, void 0, void 0]); }); it('should correctly recalculate formulas when precedents cells are located out of table viewport', () => { const hot = handsontable({ data: getDataForFormulas(0, 'name', ['=B39']), columns: getColumnsForFormulas(), formulas: true, width: 500, height: 200 }); hot.setDataAtCell(38, 1, 'foo bar'); expect(hot.getDataAtCell(0, 1)).toBe('foo bar'); }); it('should mark cell as #REF! (circular dependency)', () => { const hot = handsontable({ data: getDataForFormulas(0, 'name', ['=B1']), columns: getColumnsForFormulas(), formulas: true, width: 500, height: 300 }); expect(hot.getDataAtCell(0, 1)).toBe('#REF!'); }); it('should mark cell as #REF! (out of data table range for columns)', () => { const hot = handsontable({ data: getDataForFormulas(0, 'name', ['=K1']), columns: getColumnsForFormulas(), formulas: true, width: 500, height: 300 }); expect(hot.getDataAtCell(0, 1)).toBe('#REF!'); }); it('should mark cell as #REF! (out of data table range for rows)', () => { const hot = handsontable({ data: getDataForFormulas(0, 'name', ['=A1000']), columns: getColumnsForFormulas(), formulas: true, width: 500, height: 300 }); expect(hot.getDataAtCell(0, 1)).toBe('#REF!'); }); it('should recalculate external variables', () => { const hot = handsontable({ data: getDataForFormulas(0, 'name', ['=TEST_1', '=TEST_1&TEST_2', '=SUM(999, TEST_2)', '=TEST_3']), columns: getColumnsForFormulas(), formulas: { variables: { TEST_1: 'foo', TEST_2: 12345, } }, width: 500, height: 300 }); expect(hot.getDataAtCell(0, 1)).toBe('foo'); expect(hot.getDataAtCell(1, 1)).toBe('foo12345'); expect(hot.getDataAtCell(2, 1)).toBe(13344); expect(hot.getDataAtCell(3, 1)).toBe('#NAME?'); }); it('should recalculate external variables (via constructor)', () => { const hot = handsontable({ data: getDataForFormulas(0, 'name', ['=TEST_1', '=TEST_1&TEST_2', '=SUM(999, TEST_2)', '=TEST_3']), columns: getColumnsForFormulas(), formulas: { variables: { TEST_1: 'foo', TEST_2: 12345, } }, width: 500, height: 300 }); expect(hot.getDataAtCell(0, 1)).toBe('foo'); expect(hot.getDataAtCell(1, 1)).toBe('foo12345'); expect(hot.getDataAtCell(2, 1)).toBe(13344); expect(hot.getDataAtCell(3, 1)).toBe('#NAME?'); }); it('should recalculate external variables (via setVariable method)', () => { const hot = handsontable({ data: getDataForFormulas(0, 'name', ['=TEST_1', '=TEST_1&TEST_2', '=SUM(999, TEST_2)', '=TEST_3']), columns: getColumnsForFormulas(), formulas: { variables: { TEST_1: 'foo' } }, width: 500, height: 300 }); hot.getPlugin('formulas').setVariable('TEST_2', 12345); hot.getPlugin('formulas').recalculateFull(); expect(hot.getDataAtCell(0, 1)).toBe('foo'); expect(hot.getDataAtCell(1, 1)).toBe('foo12345'); expect(hot.getDataAtCell(2, 1)).toBe(13344); expect(hot.getDataAtCell(3, 1)).toBe('#NAME?'); }); describe('alter table (insert row)', () => { it('should recalculate table after added new empty rows', () => { const hot = handsontable({ data: getDataSimpleExampleFormulas(), formulas: true, width: 500, height: 300, }); hot.alter('insert_row', 1, 2); expect(hot.getDataAtRow(0)).toEqual([0, 'Maserati', 'Mazda', 'Mercedes', 'Mini', 0]); expect(hot.getDataAtRow(1)).toEqual([null, null, null, null, null, null]); expect(hot.getDataAtRow(2)).toEqual([null, null, null, null, null, null]); expect(hot.getDataAtRow(3)).toEqual([2009, 0, 2941, 4303, 354, 5814]); expect(hot.getDataAtRow(4)).toEqual([2010, 5, 2905, 2867, 2016, 'Maserati']); expect(hot.getDataAtRow(5)).toEqual([2011, 4, 2517, 4822, 552, 6127]); expect(hot.getDataAtRow(6)).toEqual([2012, 8042, 10058, '#DIV/0!', 12, '\'=SUM(E5)']); }); it('should recalculate table after changing values into newly added row', () => { const hot = handsontable({ data: getDataSimpleExampleFormulas(), formulas: true, width: 500, height: 300 }); hot.alter('insert_row', 2, 3); hot.setDataAtCell(3, 0, 2234); expect(hot.getDataAtRow(0)).toEqual([0, 'Maserati', 'Mazda', 'Mercedes', 'Mini', 0]); expect(hot.getDataAtRow(1)).toEqual([2009, 0, 2941, 4303, 354, 5814]); expect(hot.getDataAtRow(2)).toEqual([null, null, null, null, null, null]); expect(hot.getDataAtRow(3)).toEqual([2234, null, null, null, null, null]); expect(hot.getDataAtRow(4)).toEqual([null, null, null, null, null, null]); expect(hot.getDataAtRow(5)).toEqual([2010, 5, 2905, 2867, 2016, 'Maserati']); expect(hot.getDataAtRow(6)).toEqual([2011, 4, 2517, 4822, 552, 6127]); expect(hot.getDataAtRow(7)).toEqual([2012, 10276, 12292, '#DIV/0!', 12, '\'=SUM(E5)']); }); }); describe('alter table (insert column)', () => { it('should recalculate table after added new empty columns', () => { const hot = handsontable({ data: getDataSimpleExampleFormulas(), formulas: true, width: 500, height: 300, contextMenu: true, }); hot.alter('insert_col', 1, 2); expect(hot.getDataAtRow(0)).toEqual([0, null, null, 'Maserati', 'Mazda', 'Mercedes', 'Mini', 0]); expect(hot.getDataAtRow(1)).toEqual([2009, null, null, 0, 2941, 4303, 354, 5814]); expect(hot.getDataAtRow(2)).toEqual([2010, null, null, 5, 2905, 2867, 2016, 'Maserati']); expect(hot.getDataAtRow(3)).toEqual([2011, null, null, 4, 2517, 4822, 552, 6127]); expect(hot.getDataAtRow(4)).toEqual([2012, null, null, 8042, 10058, '#DIV/0!', 12, '\'=SUM(E5)']); }); it('should recalculate table after changing values into newly added column', () => { const hot = handsontable({ data: getDataSimpleExampleFormulas(), formulas: true, width: 500, height: 300, contextMenu: true, }); hot.alter('insert_col', 1, 2); hot.setDataAtCell(1, 3, 2); expect(hot.getDataAtRow(0)).toEqual([2, null, null, 'Maserati', 'Mazda', 'Mercedes', 'Mini', 2]); expect(hot.getDataAtRow(1)).toEqual([2009, null, null, 2, 2941, 4303, 354, 5814]); expect(hot.getDataAtRow(2)).toEqual([2010, null, null, 5, 2905, 2867, 2016, 'Maserati']); expect(hot.getDataAtRow(3)).toEqual([2011, null, null, 4, 2517, 4822, 552, 6127]); expect(hot.getDataAtRow(4)).toEqual([2012, null, null, 8042, 10058, 1004.5, 12, '\'=SUM(E5)']); }); }); describe('alter table (remove row)', () => { it('should recalculate table after removed rows', () => { const hot = handsontable({ data: getDataSimpleExampleFormulas(), formulas: true, width: 500, height: 300 }); hot.alter('remove_row', 1, 1); expect(hot.getDataAtRow(0)).toEqual(['#REF!', 'Maserati', 'Mazda', 'Mercedes', 'Mini', '#REF!']); expect(hot.getDataAtRow(1)).toEqual([2010, 5, 2905, 2867, 2016, 'Maserati']); expect(hot.getDataAtRow(2)).toEqual([2011, 4, 2517, 4822, 552, 6127]); expect(hot.getDataAtRow(3)).toEqual([2012, 6033, 8049, '#REF!', 12, '\'=SUM(E5)']); }); it('should recalculate table and replace coordinates in formula expressions into #REF! value (removing 2 rows)', () => { const hot = handsontable({ data: getDataSimpleExampleFormulas(), formulas: true, width: 500, height: 300 }); hot.alter('remove_row', 1, 2); expect(hot.getSourceDataAtRow(0)).toEqual(['=#REF!', 'Maserati', 'Mazda', 'Mercedes', 'Mini', '=A$1']); expect(hot.getSourceDataAtRow(1)).toEqual([2011, 4, 2517, 4822, 552, 6127]); expect(hot.getSourceDataAtRow(2)).toEqual([2012, '=SUM(A2:A3)', '=SUM(B3,#REF!)', '=#REF!/#REF!', 12, '\'=SUM(E5)']); expect(hot.getDataAtRow(0)).toEqual(['#REF!', 'Maserati', 'Mazda', 'Mercedes', 'Mini', '#REF!']); expect(hot.getDataAtRow(1)).toEqual([2011, 4, 2517, 4822, 552, 6127]); expect(hot.getDataAtRow(2)).toEqual([2012, 4023, '#REF!', '#REF!', 12, '\'=SUM(E5)']); }); it('should recalculate table and replace coordinates in formula expressions into #REF! value (removing first 4 rows)', () => { const hot = handsontable({ data: getDataSimpleExampleFormulas(), formulas: true, width: 500, height: 300 }); hot.alter('remove_row', 0, 4); expect(hot.getSourceDataAtRow(0)).toEqual([2012, '=SUM(A1:A1)', '=SUM(B1,#REF!)', '=#REF!/#REF!', 12, '\'=SUM(E5)']); expect(hot.getDataAtRow(0)).toEqual([2012, 2012, '#REF!', '#REF!', 12, '\'=SUM(E5)']); }); it('should recalculate table and update formula expression after removing rows intersected on the bottom of cell range', () => { const hot = handsontable({ data: getDataSimpleExampleFormulas(), formulas: true, width: 500, height: 300 }); hot.alter('insert_row', 3, 2); hot.setDataAtCell(6, 1, '=SUM(A2:A4)'); hot.alter('remove_row', 2, 3); expect(hot.getSourceDataAtRow(0)).toEqual(['=$B$2', 'Maserati', 'Mazda', 'Mercedes', 'Mini', '=A$1']); expect(hot.getSourceDataAtRow(1)).toEqual([2009, 0, 2941, 4303, 354, 5814]); expect(hot.getSourceDataAtRow(2)).toEqual([2011, 4, 2517, 4822, 552, 6127]); expect(hot.getSourceDataAtRow(3)).toEqual([2012, '=SUM(A2:A2)', '=SUM(B4,#REF!)', '=A2/B2', 12, '\'=SUM(E5)']); expect(hot.getDataAtRow(0)).toEqual([0, 'Maserati', 'Mazda', 'Mercedes', 'Mini', 0]); expect(hot.getDataAtRow(1)).toEqual([2009, 0, 2941, 4303, 354, 5814]); expect(hot.getDataAtRow(2)).toEqual([2011, 4, 2517, 4822, 552, 6127]); expect(hot.getDataAtRow(3)).toEqual([2012, 2009, '#REF!', '#DIV/0!', 12, '\'=SUM(E5)']); }); it('should recalculate table and update formula expression after removing rows intersected on the top of cell range', () => { const hot = handsontable({ data: getDataSimpleExampleFormulas(), formulas: true, width: 500, height: 300 }); hot.setDataAtCell(4, 1, '=SUM(A2:A4)'); hot.alter('remove_row', 0, 2); expect(hot.getSourceDataAtRow(0)).toEqual([2010, 5, 2905, 2867, '=SUM(A2,2,3)', '=#REF!']); expect(hot.getSourceDataAtRow(1)).toEqual([2011, 4, 2517, 4822, 552, 6127]); expect(hot.getSourceDataAtRow(2)).toEqual([2012, '=SUM(A1:A2)', '=SUM(B3,E1)', '=#REF!/#REF!', 12, '\'=SUM(E5)']); expect(hot.getDataAtRow(0)).toEqual([2010, 5, 2905, 2867, 2016, '#REF!']); expect(hot.getDataAtRow(1)).toEqual([2011, 4, 2517, 4822, 552, 6127]); expect(hot.getDataAtRow(2)).toEqual([2012, 4021, 6037, '#REF!', 12, '\'=SUM(E5)']); }); it('should recalculate table and update formula expression after removing rows contains whole cell range', () => { const hot = handsontable({ data: getDataSimpleExampleFormulas(), formulas: true, width: 500, height: 300 }); hot.alter('insert_row', 3, 2); hot.setDataAtCell(6, 1, '=SUM(A2:A4)'); hot.alter('remove_row', 0, 4); expect(hot.getSourceDataAtRow(0)).toEqual([null, null, null, null, null, null]); expect(hot.getSourceDataAtRow(1)).toEqual([2011, 4, 2517, 4822, 552, 6127]); expect(hot.getSourceDataAtRow(2)).toEqual([2012, '=SUM(#REF!)', '=SUM(B3,#REF!)', '=#REF!/#REF!', 12, '\'=SUM(E5)']); expect(hot.getDataAtRow(0)).toEqual([null, null, null, null, null, null]); expect(hot.getDataAtRow(1)).toEqual([2011, 4, 2517, 4822, 552, 6127]); expect(hot.getDataAtRow(2)).toEqual([2012, '#REF!', '#REF!', '#REF!', 12, '\'=SUM(E5)']); }); }); describe('alter table (remove column)', () => { it('should recalculate table after removed columns', () => { const hot = handsontable({ data: getDataSimpleExampleFormulas(), formulas: true, width: 500, height: 300 }); hot.alter('remove_col', 1, 1); expect(hot.getSourceDataAtRow(0)).toEqual(['=#REF!', 'Mazda', 'Mercedes', 'Mini', '=A$1']); expect(hot.getSourceDataAtRow(1)).toEqual([2009, 2941, 4303, 354, 5814]); expect(hot.getSourceDataAtRow(2)).toEqual([2010, 2905, 2867, '=SUM(A4,2,3)', '=#REF!']); expect(hot.getSourceDataAtRow(3)).toEqual([2011, 2517, 4822, 552, 6127]); expect(hot.getSourceDataAtRow(4)).toEqual([2012, '=SUM(#REF!,D3)', '=A2/#REF!', 12, '\'=SUM(E5)']); expect(hot.getDataAtRow(0)).toEqual(['#REF!', 'Mazda', 'Mercedes', 'Mini', '#REF!']); expect(hot.getDataAtRow(1)).toEqual([2009, 2941, 4303, 354, 5814]); expect(hot.getDataAtRow(2)).toEqual([2010, 2905, 2867, 2016, '#REF!']); expect(hot.getDataAtRow(3)).toEqual([2011, 2517, 4822, 552, 6127]); expect(hot.getDataAtRow(4)).toEqual([2012, '#REF!', '#REF!', 12, '\'=SUM(E5)']); }); it('should recalculate table and replace coordinates in formula expressions into #REF! value (removing 2 columns)', () => { const hot = handsontable({ data: getDataSimpleExampleFormulas(), formulas: true, width: 500, height: 300 }); hot.alter('remove_col', 1, 2); expect(hot.getSourceDataAtRow(0)).toEqual(['=#REF!', 'Mercedes', 'Mini', '=A$1']); expect(hot.getSourceDataAtRow(1)).toEqual([2009, 4303, 354, 5814]); expect(hot.getSourceDataAtRow(2)).toEqual([2010, 2867, '=SUM(A4,2,3)', '=#REF!']); expect(hot.getSourceDataAtRow(3)).toEqual([2011, 4822, 552, 6127]); expect(hot.getSourceDataAtRow(4)).toEqual([2012, '=A2/#REF!', 12, '\'=SUM(E5)']); expect(hot.getDataAtRow(0)).toEqual(['#REF!', 'Mercedes', 'Mini', '#REF!']); expect(hot.getDataAtRow(1)).toEqual([2009, 4303, 354, 5814]); expect(hot.getDataAtRow(2)).toEqual([2010, 2867, 2016, '#REF!']); expect(hot.getDataAtRow(3)).toEqual([2011, 4822, 552, 6127]); expect(hot.getDataAtRow(4)).toEqual([2012, '#REF!', 12, '\'=SUM(E5)']); }); it('should recalculate table and replace coordinates in formula expressions into #REF! value (removing first 4 columns)', () => { const hot = handsontable({ data: getDataSimpleExampleFormulas(), formulas: true, width: 500, height: 300 }); hot.alter('remove_col', 0, 4); expect(hot.getSourceDataAtRow(0)).toEqual(['Mini', '=#REF!']); expect(hot.getSourceDataAtRow(1)).toEqual([354, 5814]); expect(hot.getSourceDataAtRow(2)).toEqual(['=SUM(#REF!,2,3)', '=#REF!']); expect(hot.getSourceDataAtRow(3)).toEqual([552, 6127]); expect(hot.getSourceDataAtRow(4)).toEqual([12, '\'=SUM(E5)']); expect(hot.getDataAtRow(0)).toEqual(['Mini', '#REF!']); expect(hot.getDataAtRow(1)).toEqual([354, 5814]); expect(hot.getDataAtRow(2)).toEqual(['#REF!', '#REF!']); expect(hot.getDataAtRow(3)).toEqual([552, 6127]); expect(hot.getDataAtRow(4)).toEqual([12, '\'=SUM(E5)']); }); it('should recalculate table and update formula expression after removing columns intersected on the right of cell range', () => { const hot = handsontable({ data: getDataSimpleExampleFormulas(), formulas: true, width: 500, height: 300 }); hot.setDataAtCell(1, 5, '=Sum(B2:D2)'); hot.alter('remove_col', 2, 3); expect(hot.getSourceDataAtRow(0)).toEqual(['=$B$2', 'Maserati', '=A$1']); expect(hot.getSourceDataAtRow(1)).toEqual([2009, 0, '=SUM(B2:B2)']); expect(hot.getSourceDataAtRow(2)).toEqual([2010, 5, '=$B1']); expect(hot.getSourceDataAtRow(3)).toEqual([2011, 4, 6127]); expect(hot.getSourceDataAtRow(4)).toEqual([2012, '=SUM(A2:A5)', '\'=SUM(E5)']); expect(hot.getDataAtRow(0)).toEqual([0, 'Maserati', 0]); expect(hot.getDataAtRow(1)).toEqual([2009, 0, 0]); expect(hot.getDataAtRow(2)).toEqual([2010, 5, 'Maserati']); expect(hot.getDataAtRow(3)).toEqual([2011, 4, 6127]); expect(hot.getDataAtRow(4)).toEqual([2012, 8042, '\'=SUM(E5)']); }); it('should recalculate table and update formula expression after removing columns intersected on the left of cell range', () => { const hot = handsontable({ data: getDataSimpleExampleFormulas(), formulas: true, width: 500, height: 300 }); hot.setDataAtCell(1, 5, '=Sum(B2:D2)'); hot.alter('remove_col', 0, 3); expect(hot.getSourceDataAtRow(0)).toEqual(['Mercedes', 'Mini', '=#REF!']); expect(hot.getSourceDataAtRow(1)).toEqual([4303, 354, '=SUM(A2:A2)']); expect(hot.getSourceDataAtRow(2)).toEqual([2867, '=SUM(#REF!,2,3)', '=#REF!']); expect(hot.getSourceDataAtRow(3)).toEqual([4822, 552, 6127]); expect(hot.getSourceDataAtRow(4)).toEqual(['=#REF!/#REF!', 12, '\'=SUM(E5)']); expect(hot.getDataAtRow(0)).toEqual(['Mercedes', 'Mini', '#REF!']); expect(hot.getDataAtRow(1)).toEqual([4303, 354, 4303]); expect(hot.getDataAtRow(2)).toEqual([2867, '#REF!', '#REF!']); expect(hot.getDataAtRow(3)).toEqual([4822, 552, 6127]); expect(hot.getDataAtRow(4)).toEqual(['#REF!', 12, '\'=SUM(E5)']); }); it('should recalculate table and update formula expression after removing columns contains whole cell range', () => { const hot = handsontable({ data: getDataSimpleExampleFormulas(), formulas: true, width: 500, height: 300 }); hot.setDataAtCell(1, 5, '=Sum(B2:D2)'); hot.alter('remove_col', 0, 4); expect(hot.getSourceDataAtRow(0)).toEqual(['Mini', '=#REF!']); expect(hot.getSourceDataAtRow(1)).toEqual([354, '=SUM(#REF!)']); expect(hot.getSourceDataAtRow(2)).toEqual(['=SUM(#REF!,2,3)', '=#REF!']); expect(hot.getSourceDataAtRow(3)).toEqual([552, 6127]); expect(hot.getSourceDataAtRow(4)).toEqual([12, '\'=SUM(E5)']); expect(hot.getDataAtRow(0)).toEqual(['Mini', '#REF!']); expect(hot.getDataAtRow(1)).toEqual([354, '#REF!']); expect(hot.getDataAtRow(2)).toEqual(['#REF!', '#REF!']); expect(hot.getDataAtRow(3)).toEqual([552, 6127]); expect(hot.getDataAtRow(4)).toEqual([12, '\'=SUM(E5)']); }); }); describe('alter table (mixed operations)', () => { it('should recalculate table and replace coordinates in formula expressions', () => { const hot = handsontable({ data: getDataSimpleExampleFormulas(), formulas: true, width: 500, height: 300 }); hot.alter('remove_col', 3); hot.alter('remove_row', 2); hot.alter('remove_row', 2); hot.alter('insert_row', 0); hot.alter('remove_col', 3); hot.alter('insert_col', 3); // Make sure that formulas are shifted correctly by recalculate whole table from scratch (after sheet altering) hot.getPlugin('formulas').recalculateFull(); hot.render(); expect(hot.getSourceDataAtRow(0)).toEqual([null, null, null, null, null]); expect(hot.getSourceDataAtRow(1)).toEqual(['=$B$3', 'Maserati', 'Mazda', null, '=A$2']); expect(hot.getSourceDataAtRow(2)).toEqual([2009, 0, 2941, null, 5814]); expect(hot.getSourceDataAtRow(3)).toEqual([2012, '=SUM(A3:A4)', '=SUM(B4,#REF!)', null, '\'=SUM(E5)']); expect(hot.getDataAtRow(0)).toEqual([null, null, null, null, null]); expect(hot.getDataAtRow(1)).toEqual([0, 'Maserati', 'Mazda', null, 0]); expect(hot.getDataAtRow(2)).toEqual([2009, 0, 2941, null, 5814]); expect(hot.getDataAtRow(3)).toEqual([2012, 4021, '#REF!', null, '\'=SUM(E5)']); }); }); describe('undo/redo', () => { it('should restore previous edited formula expression and recalculate table after that', () => { const hot = handsontable({ data: getDataSimpleExampleFormulas(), formulas: true, width: 500, height: 300 }); hot.setDataAtCell(0, 5, '=B5'); hot.undo(); expect(hot.getSourceDataAtCell(0, 5)).toBe('=A$1'); expect(hot.getDataAtCell(0, 5)).toBe(0); hot.redo(); expect(hot.getSourceDataAtCell(0, 5)).toBe('=B5'); expect(hot.getDataAtCell(0, 5)).toBe(8042); }); it('should restore previous state after alter table (mixed insert operations)', () => { const hot = handsontable({ data: getDataSimpleExampleFormulas(), formulas: true, width: 500, height: 300, contextMenu: true, }); hot.alter('insert_row', 1, 3); hot.alter('insert_col', 1); hot.alter('insert_col', 4, 2); hot.alter('insert_row', 5); hot.undo(); expect(hot.getSourceDataAtRow(0)).toEqual(['=$C$5', null, 'Maserati', 'Mazda', null, null, 'Mercedes', 'Mini', '=A$1']); expect(hot.getSourceDataAtRow(1)).toEqual([null, null, null, null, null, null, null, null, null]); expect(hot.getSourceDataAtRow(2)).toEqual([null, null, null, null, null, null, null, null, null]); expect(hot.getSourceDataAtRow(3)).toEqual([null, null, null, null, null, null, null, null, null]); expect(hot.getSourceDataAtRow(4)).toEqual([2009, null, 0, 2941, null, null, 4303, 354, 5814]); expect(hot.getSourceDataAtRow(5)).toEqual([2010, null, 5, 2905, null, null, 2867, '=SUM(A7,2,3)', '=$C1']); expect(hot.getSourceDataAtRow(6)).toEqual([2011, null, 4, 2517, null, null, 4822, 552, 6127]); expect(hot.getSourceDataAtRow(7)).toEqual([2012, null, '=SUM(A5:A8)', '=SUM(C8,H6)', null, null, '=A5/C5', 12, '\'=SUM(E5)']); hot.undo(); expect(hot.getSourceDataAtRow(0)).toEqual(['=$C$5', null, 'Maserati', 'Mazda', 'Mercedes', 'Mini', '=A$1']); expect(hot.getSourceDataAtRow(1)).toEqual([null, null, null, null, null, null, null]); expect(hot.getSourceDataAtRow(2)).toEqual([null, null, null, null, null, null, null]); expect(hot.getSourceDataAtRow(3)).toEqual([null, null, null, null, null, null, null]); expect(hot.getSourceDataAtRow(4)).toEqual([2009, null, 0, 2941, 4303, 354, 5814]); expect(hot.getSourceDataAtRow(5)).toEqual([2010, null, 5, 2905, 2867, '=SUM(A7,2,3)', '=$C1']); expect(hot.getSourceDataAtRow(6)).toEqual([2011, null, 4, 2517, 4822, 552, 6127]); expect(hot.getSourceDataAtRow(7)).toEqual([2012, null, '=SUM(A5:A8)', '=SUM(C8,F6)', '=A5/C5', 12, '\'=SUM(E5)']); hot.undo(); expect(hot.getSourceDataAtRow(0)).toEqual(['=$B$5', 'Maserati', 'Mazda', 'Mercedes', 'Mini', '=A$1']); expect(hot.getSourceDataAtRow(1)).toEqual([null, null, null, null, null, null]); expect(hot.getSourceDataAtRow(2)).toEqual([null, null, null, null, null, null]); expect(hot.getSourceDataAtRow(3)).toEqual([null, null, null, null, null, null]); expect(hot.getSourceDataAtRow(4)).toEqual([2009, 0, 2941, 4303, 354, 5814]); expect(hot.getSourceDataAtRow(5)).toEqual([2010, 5, 2905, 2867, '=SUM(A7,2,3)', '=$B1']); expect(hot.getSourceDataAtRow(6)).toEqual([2011, 4, 2517, 4822, 552, 6127]); expect(hot.getSourceDataAtRow(7)).toEqual([2012, '=SUM(A5:A8)', '=SUM(B8,E6)', '=A5/B5', 12, '\'=SUM(E5)']); hot.undo(); expect(hot.getSourceDataAtRow(0)).toEqual(['=$B$2', 'Maserati', 'Mazda', 'Mercedes', 'Mini', '=A$1']); expect(hot.getSourceDataAtRow(1)).toEqual([2009, 0, 2941, 4303, 354, 5814]); expect(hot.getSourceDataAtRow(2)).toEqual([2010, 5, 2905, 2867, '=SUM(A4,2,3)', '=$B1']); expect(hot.getSourceDataAtRow(3)).toEqual([2011, 4, 2517, 4822, 552, 6127]); expect(hot.getSourceDataAtRow(4)).toEqual([2012, '=SUM(A2:A5)', '=SUM(B5,E3)', '=A2/B2', 12, '\'=SUM(E5)']); }); it('should redo into the next state after alter table (mixed insert operations)', () => { const hot = handsontable({ data: getDataSimpleExampleFormulas(), formulas: true, width: 500, height: 300, contextMenu: true, }); hot.alter('insert_row', 1, 3); hot.alter('insert_col', 1); hot.alter('insert_col', 4, 2); hot.alter('insert_row', 5); hot.undo(); hot.undo(); hot.undo(); hot.undo(); expect(hot.getSourceDataAtRow(0)).toEqual(['=$B$2', 'Maserati', 'Mazda', 'Mercedes', 'Mini', '=A$1']); expect(hot.getSourceDataAtRow(1)).toEqual([2009, 0, 2941, 4303, 354, 5814]); expect(hot.getSourceDataAtRow(2)).toEqual([2010, 5, 2905, 2867, '=SUM(A4,2,3)', '=$B1']); expect(hot.getSourceDataAtRow(3)).toEqual([2011, 4, 2517, 4822, 552, 6127]); expect(hot.getSourceDataAtRow(4)).toEqual([2012, '=SUM(A2:A5)', '=SUM(B5,E3)', '=A2/B2', 12, '\'=SUM(E5)']); hot.redo(); expect(hot.getSourceDataAtRow(0)).toEqual(['=$B$5', 'Maserati', 'Mazda', 'Mercedes', 'Mini', '=A$1']); expect(hot.getSourceDataAtRow(1)).toEqual([null, null, null, null, null, null]); expect(hot.getSourceDataAtRow(2)).toEqual([null, null, null, null, null, null]); expect(hot.getSourceDataAtRow(3)).toEqual([null, null, null, null, null, null]); expect(hot.getSourceDataAtRow(4)).toEqual([2009, 0, 2941, 4303, 354, 5814]); expect(hot.getSourceDataAtRow(5)).toEqual([2010, 5, 2905, 2867, '=SUM(A7,2,3)', '=$B1']); expect(hot.getSourceDataAtRow(6)).toEqual([2011, 4, 2517, 4822, 552, 6127]); expect(hot.getSourceDataAtRow(7)).toEqual([2012, '=SUM(A5:A8)', '=SUM(B8,E6)', '=A5/B5', 12, '\'=SUM(E5)']); hot.redo(); expect(hot.getSourceDataAtRow(0)).toEqual(['=$C$5', null, 'Maserati', 'Mazda', 'Mercedes', 'Mini', '=A$1']); expect(hot.getSourceDataAtRow(1)).toEqual([null, null, null, null, null, null, null]); expect(hot.getSourceDataAtRow(2)).toEqual([null, null, null, null, null, null, null]); expect(hot.getSourceDataAtRow(3)).toEqual([null, null, null, null, null, null, null]); expect(hot.getSourceDataAtRow(4)).toEqual([2009, null, 0, 2941, 4303, 354, 5814]); expect(hot.getSourceDataAtRow(5)).toEqual([2010, null, 5, 2905, 2867, '=SUM(A7,2,3)', '=$C1']); expect(hot.getSourceDataAtRow(6)).toEqual([2011, null, 4, 2517, 4822, 552, 6127]); expect(hot.getSourceDataAtRow(7)).toEqual([2012, null, '=SUM(A5:A8)', '=SUM(C8,F6)', '=A5/C5', 12, '\'=SUM(E5)']); hot.redo(); expect(hot.getSourceDataAtRow(0)).toEqual(['=$C$5', null, 'Maserati', 'Mazda', null, null, 'Mercedes', 'Mini', '=A$1']); expect(hot.getSourceDataAtRow(1)).toEqual([null, null, null, null, null, null, null, null, null]); expect(hot.getSourceDataAtRow(2)).toEqual([null, null, null, null, null, null, null, null, null]); expect(hot.getSourceDataAtRow(3)).toEqual([null, null, null, null, null, null, null, null, null]); expect(hot.getSourceDataAtRow(4)).toEqual([2009, null, 0, 2941, null, null, 4303, 354, 5814]); expect(hot.getSourceDataAtRow(5)).toEqual([2010, null, 5, 2905, null, null, 2867, '=SUM(A7,2,3)', '=$C1']); expect(hot.getSourceDataAtRow(6)).toEqual([2011, null, 4, 2517, null, null, 4822, 552, 6127]); expect(hot.getSourceDataAtRow(7)).toEqual([2012, null, '=SUM(A5:A8)', '=SUM(C8,H6)', null, null, '=A5/C5', 12, '\'=SUM(E5)']); }); it('should restore previous state after alter table (mixed remove operations)', () => { const hot = handsontable({ data: getDataSimpleExampleFormulas(), formulas: true, width: 500, height: 300, contextMenu: true, }); hot.alter('remove_row', 2); hot.alter('remove_col', 2, 2); hot.alter('remove_row', 0, 2); hot.alter('remove_col', 3); hot.undo(); expect(hot.getSourceDataAtRow(0)).toEqual([2011, 4, 552, 6127]); expect(hot.getSourceDataAtRow(1)).toEqual([2012, '=SUM(A1:A2)', 12, '\'=SUM(E5)']); hot.undo(); expect(hot.getSourceDataAtRow(0)).toEqual(['=$B$2', 'Maserati', 'Mini', '=A$1']); expect(hot.getSourceDataAtRow(1)).toEqual([2009, 0, 354, 5814]); expect(hot.getSourceDataAtRow(2)).toEqual([2011, 4, 552, 6127]); expect(hot.getSourceDataAtRow(3)).toEqual([2012, '=SUM(A2:A4)', 12, '\'=SUM(E5)']); hot.undo(); expect(hot.getSourceDataAtRow(0)).toEqual(['=$B$2', 'Maserati', 'Mazda', 'Mercedes', 'Mini', '=A$1']); expect(hot.getSourceDataAtRow(1)).toEqual([2009, 0, 2941, 4303, 354, 5814]); expect(hot.getSourceDataAtRow(2)).toEqual([2011, 4, 2517, 4822, 552, 6127]); expect(hot.getSourceDataAtRow(3)).toEqual([2012, '=SUM(A2:A4)', '=SUM(B4,#REF!)', '=A2/B2', 12, '\'=SUM(E5)']); hot.undo(); expect(hot.getSourceDataAtRow(0)).toEqual(['=$B$2', 'Maserati', 'Mazda', 'Mercedes', 'Mini', '=A$1']); expect(hot.getSourceDataAtRow(1)).toEqual([2009, 0, 2941, 4303, 354, 5814]); expect(hot.getSourceDataAtRow(2)).toEqual([2010, 5, 2905, 2867, '=SUM(A4,2,3)', '=$B1']); expect(hot.getSourceDataAtRow(3)).toEqual([2011, 4, 2517, 4822, 552, 6127]); expect(hot.getSourceDataAtRow(4)).toEqual([2012, '=Sum(a2:a5)', '=SUM(B5,E3)', '=A2/B2', 12, '\'=SUM(E5)']); }); it('should redo into the next state after alter table (mixed remove operations)', () => { const hot = handsontable({ data: getDataSimpleExampleFormulas(), formulas: true, width: 500, height: 300, contextMenu: true, }); hot.alter('remove_row', 2); hot.alter('remove_col', 2, 2); hot.alter('remove_row', 0, 2); hot.alter('remove_col', 3); hot.undo(); hot.undo(); hot.undo(); hot.undo(); expect(hot.getSourceDataAtRow(0)).toEqual(['=$B$2', 'Maserati', 'Mazda', 'Mercedes', 'Mini', '=A$1']); expect(hot.getSourceDataAtRow(1)).toEqual([2009, 0, 2941, 4303, 354, 5814]); expect(hot.getSourceDataAtRow(2)).toEqual([2010, 5, 2905, 2867, '=SUM(A4,2,3)', '=$B1']); expect(hot.getSourceDataAtRow(3)).toEqual([2011, 4, 2517, 4822, 552, 6127]); expect(hot.getSourceDataAtRow(4)).toEqual([2012, '=Sum(a2:a5)', '=SUM(B5,E3)', '=A2/B2', 12, '\'=SUM(E5)']); hot.redo(); expect(hot.getSourceDataAtRow(0)).toEqual(['=$B$2', 'Maserati', 'Mazda', 'Mercedes', 'Mini', '=A$1']); expect(hot.getSourceDataAtRow(1)).toEqual([2009, 0, 2941, 4303, 354, 5814]); expect(hot.getSourceDataAtRow(2)).toEqual([2011, 4, 2517, 4822, 552, 6127]); expect(hot.getSourceDataAtRow(3)).toEqual([2012, '=SUM(A2:A4)', '=SUM(B4,#REF!)', '=A2/B2', 12, '\'=SUM(E5)']); hot.redo(); expect(hot.getSourceDataAtRow(0)).toEqual(['=$B$2', 'Maserati', 'Mini', '=A$1']); expect(hot.getSourceDataAtRow(1)).toEqual([2009, 0, 354, 5814]); expect(hot.getSourceDataAtRow(2)).toEqual([2011, 4, 552, 6127]); expect(hot.getSourceDataAtRow(3)).toEqual([2012, '=SUM(A2:A4)', 12, '\'=SUM(E5)']); hot.redo(); expect(hot.getSourceDataAtRow(0)).toEqual([2011, 4, 552, 6127]); expect(hot.getSourceDataAtRow(1)).toEqual([2012, '=SUM(A1:A2)', 12, '\'=SUM(E5)']); }); }); describe('column sorting', () => { it('should recalculate all formulas and update theirs cell coordinates if needed', () => { const hot = handsontable({ data: getDataSimpleExampleFormulas(), formulas: true, columnSorting: true, width: 500, height: 300 }); hot.updateSettings({ columnSorting: { initialConfig: { column: 2, sortOrder: 'asc' } } }); // source data is not involved in the translation process expect(hot.getSourceDataAtRow(0)).toEqual(['=$B$2', 'Maserati', 'Mazda', 'Mercedes', 'Mini', '=A$1']); expect(hot.getSourceDataAtRow(1)).toEqual([2009, 0, 2941, 4303, 354, 5814]); expect(hot.getSourceDataAtRow(2)).toEqual([2010, 5, 2905, 2867, '=SUM(A3,2,3)', '=#REF!']); expect(hot.getSourceDataAtRow(3)).toEqual([2011, 4, 2517, 4822, 552, 6127]); expect(hot.getSourceDataAtRow(4)).toEqual([2012, '=SUM(A1:A4)', '=SUM(B4,E2)', '=A1/B1', 12, '\'=SUM(E5)']); expect(hot.getDataAtRow(0)).toEqual([2011, 4, 2517, 4822, 552, 6127]); expect(hot.getDataAtRow(1)).toEqual([2010, 5, 2905, 2867, 2014, '#REF!']); expect(hot.getDataAtRow(2)).toEqual([2009, 0, 2941, 4303, 354, 5814]); expect(hot.getDataAtRow(3)).toEqual([2012, 8042, 10056, 502.75, 12, '\'=SUM(E5)']); expect(hot.getDataAtRow(4)).toEqual([5, 'Maserati', 'Mazda', 'Mercedes', 'Mini', 2011]); hot.updateSettings({ columnSorting: { initialConfig: { column: 5, sortOrder: 'desc' } } }); // source data is not involved in the translation process expect(hot.getSourceDataAtRow(0)).toEqual(['=$B$2', 'Maserati', 'Mazda', 'Mercedes', 'Mini', '=A$1']); expect(hot.getSourceDataAtRow(1)).toEqual([2009, 0, 2941, 4303, 354, 5814]); expect(hot.getSourceDataAtRow(2)).toEqual([2010, 5, 2905, 2867, '=SUM(A3,2,3)', '=#REF!']); expect(hot.getSourceDataAtRow(3)).toEqual([2011, 4, 2517, 4822, 552, 6127]); expect(hot.getSourceDataAtRow(4)).toEqual([2012, '=SUM(#REF!)', '=SUM(B1,#REF!)', '=#REF!/#REF!', 12, '\'=SUM(E5)']); expect(hot.getDataAtRow(0)).toEqual([2012, '#REF!', '#REF!', '#REF!', 12, '\'=SUM(E5)']); expect(hot.getDataAtRow(1)).toEqual([2010, 5, 2905, 2867, 2016, '#REF!']); expect(hot.getDataAtRow(2)).toEqual([2011, 4, 2517, 4822, 552, 6127]); expect(hot.getDataAtRow(3)).toEqual([2009, 0, 2941, 4303, 354, 5814]); expect(hot.getDataAtRow(4)).toEqual([5, 'Maserati', 'Mazda', 'Mercedes', 'Mini', 2012]); }); it('should recalculate formula after precedent cells value was changed', (done) => { const hot = handsontable({ data: getDataSimpleExampleFormulas(), formulas: true, columnSorting: true, width: 500, height: 300 }); hot.updateSettings({ columnSorting: { initialConfig: { column: 2, sortOrder: 'asc' } } }); setTimeout(() => { hot.setDataAtCell(4, 0, ''); expect(hot.getDataAtRow(0)).toEqual([2011, 4, 2517, 4822, 552, 6127]); expect(hot.getDataAtRow(1)).toEqual([2010, 5, 2905, 2867, 2014, '#REF!']); expect(hot.getDataAtRow(2)).toEqual([2009, 0, 2941, 4303, 354, 5814]); expect(hot.getDataAtRow(3)).toEqual([2012, 8042, 10056, 502.75, 12, '\'=SUM(E5)']); expect(hot.getDataAtRow(4)).toEqual(['', 'Maserati', 'Mazda', 'Mercedes', 'Mini', 2011]); hot.setDataAtCell(0, 0, 1); expect(hot.getDataAtRow(0)).toEqual([1, 4, 2517, 4822, 552, 6127]); expect(hot.getDataAtRow(1)).toEqual([2010, 5, 2905, 2867, 2014, '#REF!']); expect(hot.getDataAtRow(2)).toEqual([2009, 0, 2941, 4303, 354, 5814]); expect(hot.getDataAtRow(3)).toEqual([2012, 6032, 8046, 0.25, 12, '\'=SUM(E5)']); expect(hot.getDataAtRow(4)).toEqual(['', 'Maserati', 'Mazda', 'Mercedes', 'Mini', 1]); hot.setDataAtCell(1, 0, 2); expect(hot.getDataAtRow(0)).toEqual([1, 4, 2517, 4822, 552, 6127]); expect(hot.getDataAtRow(1)).toEqual([2, 5, 2905, 2867, 2014, '#REF!']); expect(hot.getDataAtRow(2)).toEqual([2009, 0, 2941, 4303, 354, 5814]); expect(hot.getDataAtRow(3)).toEqual([2012, 4024, 6038, 0.25, 12, '\'=SUM(E5)']); expect(hot.getDataAtRow(4)).toEqual(['', 'Maserati', 'Mazda', 'Mercedes', 'Mini', 1]); hot.setDataAtCell(2, 0, 3); expect(hot.getDataAtRow(0)).toEqual([1, 4, 2517, 4822, 552, 6127]); expect(hot.getDataAtRow(1)).toEqual([2, 5, 2905, 2867, 8, '#REF!']); expect(hot.getDataAtRow(2)).toEqual([3, 0, 2941, 4303, 354, 5814]); expect(hot.getDataAtRow(3)).toEqual([2012, 2018, 2026, 0.25, 12, '\'=SUM(E5)']); expect(hot.getDataAtRow(4)).toEqual(['', 'Maserati', 'Mazda', 'Mercedes', 'Mini', 1]); hot.setDataAtCell(3, 0, 4); expect(hot.getDataAtRow(0)).toEqual([1, 4, 2517, 4822, 552, 6127]); expect(hot.getDataAtRow(1)).toEqual([2, 5, 2905, 2867, 8, '#REF!']); expect(hot.getDataAtRow(2)).toEqual([3, 0, 2941, 4303, 354, 5814]); expect(hot.getDataAtRow(3)).toEqual([4, 10, 18, 0.25, 12, '\'=SUM(E5)']); expect(hot.getDataAtRow(4)).toEqual(['', 'Maserati', 'Mazda', 'Mercedes', 'Mini', 1]); done(); }, 200); }); it('should corectly recalculate formulas after changing formula expression in sorted cell', (done) => { const hot = handsontable({ data: getDataSimpleExampleFormulas(), formulas: true, columnSorting: true, width: 500, height: 300 }); hot.updateSettings({ columnSorting: { initialConfig: { column: 2, sortOrder: 'asc' } } }); setTimeout(() => { hot.setDataAtCell(3, 1, '=SUM(B1:B3)'); expect(hot.getDataAtRow(0)).toEqual([2011, 4, 2517, 4822, 552, 6127]); expect(hot.getDataAtRow(1)).toEqual([2010, 5, 2905, 2867, 2014, '#REF!']); expect(hot.getDataAtRow(2)).toEqual([2009, 0, 2941, 4303, 354, 5814]); expect(hot.getDataAtRow(3)).toEqual([2012, 9, 2023, 502.75, 12, '\'=SUM(E5)']); expect(hot.getDataAtRow(4)).toEqual([5, 'Maserati', 'Mazda', 'Mercedes', 'Mini', 2011]); done(); }, 200); }); }); });
1
16,468
The test description says it's "by reference". We should change the description
handsontable-handsontable
js
@@ -16,9 +16,15 @@ namespace AutoRest.Core.Validation { } + /// <summary> + /// Id of the Rule. + /// </summary> public virtual string Id => "!!! implement me and make me abstract !!!"; - public ValidationCategory ValidationCategory => ((ValidationCategory)0); // !!! implement me and make me abstract !!! + /// <summary> + /// Violation category of the Rule. + /// </summary> + public virtual ValidationCategory ValidationCategory => ((ValidationCategory)0); // !!! implement me and make me abstract !!! /// <summary> /// The template message for this Rule.
1
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System.Collections.Generic; using AutoRest.Core.Logging; using System; namespace AutoRest.Core.Validation { /// <summary> /// Defines validation logic for an object /// </summary> public abstract class Rule { protected Rule() { } public virtual string Id => "!!! implement me and make me abstract !!!"; public ValidationCategory ValidationCategory => ((ValidationCategory)0); // !!! implement me and make me abstract !!! /// <summary> /// The template message for this Rule. /// </summary> /// <remarks> /// This may contain placeholders '{0}' for parameterized messages. /// </remarks> public abstract string MessageTemplate { get; } /// <summary> /// The severity of this message (ie, debug/info/warning/error/fatal, etc) /// </summary> public abstract Category Severity { get; } /// <summary> /// Returns the validation messages resulting from validating this object /// </summary> /// <param name="entity">The object to validate</param> /// <returns></returns> public abstract IEnumerable<ValidationMessage> GetValidationMessages(object entity, RuleContext context); } }
1
23,911
A C# newbie question here: would it make sense to declare Id as an abstract property so any subclass Must have its own Id?
Azure-autorest
java
@@ -47,6 +47,11 @@ func (r *Repository) Proposals(filter *proposal.Filter) ([]market.ServiceProposa return []market.ServiceProposal{}, nil } +// Countries returns proposals per country matching the filter. +func (r *Repository) Countries(filter *proposal.Filter) (map[string]int, error) { + return nil, nil +} + // Start begins proposals synchronization to storage. func (r *Repository) Start() error { return nil
1
/* * Copyright (C) 2020 The "MysteriumNetwork/node" Authors. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package dhtdiscovery import ( "sync" "github.com/mysteriumnetwork/node/core/discovery/proposal" "github.com/mysteriumnetwork/node/market" ) // Repository provides proposals from the DHT. type Repository struct { stopOnce sync.Once stopChan chan struct{} } // NewRepository constructs a new proposal repository (backed by the DHT). func NewRepository() *Repository { return &Repository{ stopChan: make(chan struct{}), } } // Proposal returns a single proposal by its ID. func (r *Repository) Proposal(id market.ProposalID) (*market.ServiceProposal, error) { return nil, nil } // Proposals returns proposals matching the filter. func (r *Repository) Proposals(filter *proposal.Filter) ([]market.ServiceProposal, error) { return []market.ServiceProposal{}, nil } // Start begins proposals synchronization to storage. func (r *Repository) Start() error { return nil } // Stop ends proposals synchronization to storage. func (r *Repository) Stop() { r.stopOnce.Do(func() { close(r.stopChan) }) }
1
17,395
just looks like you should return an **empty map** with nil error
mysteriumnetwork-node
go
@@ -103,11 +103,18 @@ func main() { reloadURL := app.Flag("reload-url", "reload URL to trigger Prometheus reload on"). Default("http://127.0.0.1:9090/-/reload").URL() + version.RegisterIntoKingpinFlags(app) + if _, err := app.Parse(os.Args[1:]); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(2) } + if version.ShouldPrintVersion() { + version.Print(os.Stdout, "prometheus-config-reloader") + os.Exit(0) + } + logger := log.NewLogfmtLogger(log.NewSyncWriter(os.Stdout)) if *logFormat == logFormatJson {
1
// Copyright 2016 The prometheus-operator Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package main import ( "context" "fmt" "net/http" "os" "regexp" "strings" "time" "github.com/prometheus-operator/prometheus-operator/pkg/version" "github.com/go-kit/kit/log" "github.com/go-kit/kit/log/level" "github.com/oklog/run" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp" "github.com/thanos-io/thanos/pkg/reloader" "gopkg.in/alecthomas/kingpin.v2" ) const ( logFormatLogfmt = "logfmt" logFormatJson = "json" logLevelDebug = "debug" logLevelInfo = "info" logLevelWarn = "warn" logLevelError = "error" logLevelNone = "none" defaultWatchInterval = 3 * time.Minute // 3 minutes was the value previously hardcoded in github.com/thanos-io/thanos/pkg/reloader. defaultDelayInterval = 1 * time.Second // 1 second seems a reasonable amount of time for the kubelet to update the secrets/configmaps. defaultRetryInterval = 5 * time.Second // 5 seconds was the value previously hardcoded in github.com/thanos-io/thanos/pkg/reloader. statefulsetOrdinalEnvvar = "STATEFULSET_ORDINAL_NUMBER" statefulsetOrdinalFromEnvvarDefault = "POD_NAME" ) var ( availableLogFormats = []string{ logFormatLogfmt, logFormatJson, } availableLogLevels = []string{ logLevelDebug, logLevelInfo, logLevelWarn, logLevelError, logLevelNone, } ) func main() { app := kingpin.New("prometheus-config-reloader", "") cfgFile := app.Flag("config-file", "config file watched by the reloader"). String() cfgSubstFile := app.Flag("config-envsubst-file", "output file for environment variable substituted config file"). String() watchInterval := app.Flag("watch-interval", "how often the reloader re-reads the configuration file and directories").Default(defaultWatchInterval.String()).Duration() delayInterval := app.Flag("delay-interval", "how long the reloader waits before reloading after it has detected a change").Default(defaultDelayInterval.String()).Duration() retryInterval := app.Flag("retry-interval", "how long the reloader waits before retrying in case the endpoint returned an error").Default(defaultRetryInterval.String()).Duration() watchedDir := app.Flag("watched-dir", "directory to watch non-recursively").Strings() createStatefulsetOrdinalFrom := app.Flag( "statefulset-ordinal-from-envvar", fmt.Sprintf("parse this environment variable to create %s, containing the statefulset ordinal number", statefulsetOrdinalEnvvar)). Default(statefulsetOrdinalFromEnvvarDefault).String() listenAddress := app.Flag( "listen-address", "address on which to expose metrics (disabled when empty)"). String() logFormat := app.Flag( "log-format", fmt.Sprintf("log format to use. Possible values: %s", strings.Join(availableLogFormats, ", "))). Default(logFormatLogfmt).String() logLevel := app.Flag( "log-level", fmt.Sprintf("log level to use. Possible values: %s", strings.Join(availableLogLevels, ", "))). Default(logLevelInfo).String() reloadURL := app.Flag("reload-url", "reload URL to trigger Prometheus reload on"). Default("http://127.0.0.1:9090/-/reload").URL() if _, err := app.Parse(os.Args[1:]); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(2) } logger := log.NewLogfmtLogger(log.NewSyncWriter(os.Stdout)) if *logFormat == logFormatJson { logger = log.NewJSONLogger(log.NewSyncWriter(os.Stdout)) } switch *logLevel { case logLevelDebug: logger = level.NewFilter(logger, level.AllowDebug()) case logLevelWarn: logger = level.NewFilter(logger, level.AllowWarn()) case logLevelError: logger = level.NewFilter(logger, level.AllowError()) case logLevelNone: logger = level.NewFilter(logger, level.AllowNone()) default: logger = level.NewFilter(logger, level.AllowInfo()) } logger = log.With(logger, "ts", log.DefaultTimestampUTC) logger = log.With(logger, "caller", log.DefaultCaller) if createStatefulsetOrdinalFrom != nil { if err := createOrdinalEnvvar(*createStatefulsetOrdinalFrom); err != nil { level.Warn(logger).Log("msg", fmt.Sprintf("Failed setting %s", statefulsetOrdinalEnvvar)) } } level.Info(logger).Log("msg", fmt.Sprintf("Starting prometheus-config-reloader version '%v'.", version.Version)) r := prometheus.NewRegistry() r.MustRegister( prometheus.NewGoCollector(), prometheus.NewProcessCollector(prometheus.ProcessCollectorOpts{}), ) var g run.Group { ctx, cancel := context.WithCancel(context.Background()) rel := reloader.New( logger, r, &reloader.Options{ ReloadURL: *reloadURL, CfgFile: *cfgFile, CfgOutputFile: *cfgSubstFile, WatchedDirs: *watchedDir, DelayInterval: *delayInterval, WatchInterval: *watchInterval, RetryInterval: *retryInterval, }, ) g.Add(func() error { return rel.Watch(ctx) }, func(error) { cancel() }) } if *listenAddress != "" { g.Add(func() error { level.Info(logger).Log("msg", "Starting web server for metrics", "listen", *listenAddress) http.Handle("/metrics", promhttp.HandlerFor(r, promhttp.HandlerOpts{Registry: r})) return http.ListenAndServe(*listenAddress, nil) }, func(error) { }) } if err := g.Run(); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } func createOrdinalEnvvar(fromName string) error { reg := regexp.MustCompile(`\d+$`) val := reg.FindString(os.Getenv(fromName)) return os.Setenv(statefulsetOrdinalEnvvar, val) }
1
15,073
could you also update the starting log at L146?
prometheus-operator-prometheus-operator
go
@@ -312,6 +312,16 @@ func isUnitExists(err error) bool { return false } +// isDbusClosed returns true if the error is that connection closed. +func isDbusClosed(err error) bool { + if err != nil { + if dbusError, ok := err.(dbus.Error); ok { + return strings.Contains(dbusError.Name, "connection closed by user") + } + } + return false +} + func startUnit(dbusConnection *systemdDbus.Conn, unitName string, properties []systemdDbus.Property) error { statusChan := make(chan string, 1) if _, err := dbusConnection.StartTransientUnit(unitName, "replace", properties, statusChan); err == nil {
1
package systemd import ( "bufio" "fmt" "math" "os" "regexp" "strconv" "strings" "sync" "time" systemdDbus "github.com/coreos/go-systemd/v22/dbus" dbus "github.com/godbus/dbus/v5" cgroupdevices "github.com/opencontainers/runc/libcontainer/cgroups/devices" "github.com/opencontainers/runc/libcontainer/configs" "github.com/opencontainers/runc/libcontainer/devices" "github.com/pkg/errors" "github.com/sirupsen/logrus" ) const ( // Default kernel value for cpu quota period is 100000 us (100 ms), same for v1 and v2. // v1: https://www.kernel.org/doc/html/latest/scheduler/sched-bwc.html and // v2: https://www.kernel.org/doc/html/latest/admin-guide/cgroup-v2.html defCPUQuotaPeriod = uint64(100000) ) var ( versionOnce sync.Once version int isRunningSystemdOnce sync.Once isRunningSystemd bool ) // NOTE: This function comes from package github.com/coreos/go-systemd/util // It was borrowed here to avoid a dependency on cgo. // // IsRunningSystemd checks whether the host was booted with systemd as its init // system. This functions similarly to systemd's `sd_booted(3)`: internally, it // checks whether /run/systemd/system/ exists and is a directory. // http://www.freedesktop.org/software/systemd/man/sd_booted.html func IsRunningSystemd() bool { isRunningSystemdOnce.Do(func() { fi, err := os.Lstat("/run/systemd/system") isRunningSystemd = err == nil && fi.IsDir() }) return isRunningSystemd } // systemd represents slice hierarchy using `-`, so we need to follow suit when // generating the path of slice. Essentially, test-a-b.slice becomes // /test.slice/test-a.slice/test-a-b.slice. func ExpandSlice(slice string) (string, error) { suffix := ".slice" // Name has to end with ".slice", but can't be just ".slice". if len(slice) < len(suffix) || !strings.HasSuffix(slice, suffix) { return "", fmt.Errorf("invalid slice name: %s", slice) } // Path-separators are not allowed. if strings.Contains(slice, "/") { return "", fmt.Errorf("invalid slice name: %s", slice) } var path, prefix string sliceName := strings.TrimSuffix(slice, suffix) // if input was -.slice, we should just return root now if sliceName == "-" { return "/", nil } for _, component := range strings.Split(sliceName, "-") { // test--a.slice isn't permitted, nor is -test.slice. if component == "" { return "", fmt.Errorf("invalid slice name: %s", slice) } // Append the component to the path and to the prefix. path += "/" + prefix + component + suffix prefix += component + "-" } return path, nil } func groupPrefix(ruleType devices.Type) (string, error) { switch ruleType { case devices.BlockDevice: return "block-", nil case devices.CharDevice: return "char-", nil default: return "", errors.Errorf("device type %v has no group prefix", ruleType) } } // findDeviceGroup tries to find the device group name (as listed in // /proc/devices) with the type prefixed as required for DeviceAllow, for a // given (type, major) combination. If more than one device group exists, an // arbitrary one is chosen. func findDeviceGroup(ruleType devices.Type, ruleMajor int64) (string, error) { fh, err := os.Open("/proc/devices") if err != nil { return "", err } defer fh.Close() prefix, err := groupPrefix(ruleType) if err != nil { return "", err } scanner := bufio.NewScanner(fh) var currentType devices.Type for scanner.Scan() { // We need to strip spaces because the first number is column-aligned. line := strings.TrimSpace(scanner.Text()) // Handle the "header" lines. switch line { case "Block devices:": currentType = devices.BlockDevice continue case "Character devices:": currentType = devices.CharDevice continue case "": continue } // Skip lines unrelated to our type. if currentType != ruleType { continue } // Parse out the (major, name). var ( currMajor int64 currName string ) if n, err := fmt.Sscanf(line, "%d %s", &currMajor, &currName); err != nil || n != 2 { if err == nil { err = errors.Errorf("wrong number of fields") } return "", errors.Wrapf(err, "scan /proc/devices line %q", line) } if currMajor == ruleMajor { return prefix + currName, nil } } if err := scanner.Err(); err != nil { return "", errors.Wrap(err, "reading /proc/devices") } // Couldn't find the device group. return "", nil } // generateDeviceProperties takes the configured device rules and generates a // corresponding set of systemd properties to configure the devices correctly. func generateDeviceProperties(rules []*devices.Rule) ([]systemdDbus.Property, error) { // DeviceAllow is the type "a(ss)" which means we need a temporary struct // to represent it in Go. type deviceAllowEntry struct { Path string Perms string } properties := []systemdDbus.Property{ // Always run in the strictest white-list mode. newProp("DevicePolicy", "strict"), // Empty the DeviceAllow array before filling it. newProp("DeviceAllow", []deviceAllowEntry{}), } // Figure out the set of rules. configEmu := &cgroupdevices.Emulator{} for _, rule := range rules { if err := configEmu.Apply(*rule); err != nil { return nil, errors.Wrap(err, "apply rule for systemd") } } // systemd doesn't support blacklists. So we log a warning, and tell // systemd to act as a deny-all whitelist. This ruleset will be replaced // with our normal fallback code. This may result in spurrious errors, but // the only other option is to error out here. if configEmu.IsBlacklist() { // However, if we're dealing with an allow-all rule then we can do it. if configEmu.IsAllowAll() { return []systemdDbus.Property{ // Run in white-list mode by setting to "auto" and removing all // DeviceAllow rules. newProp("DevicePolicy", "auto"), newProp("DeviceAllow", []deviceAllowEntry{}), }, nil } logrus.Warn("systemd doesn't support blacklist device rules -- applying temporary deny-all rule") return properties, nil } // Now generate the set of rules we actually need to apply. Unlike the // normal devices cgroup, in "strict" mode systemd defaults to a deny-all // whitelist which is the default for devices.Emulator. baseEmu := &cgroupdevices.Emulator{} finalRules, err := baseEmu.Transition(configEmu) if err != nil { return nil, errors.Wrap(err, "get simplified rules for systemd") } var deviceAllowList []deviceAllowEntry for _, rule := range finalRules { if !rule.Allow { // Should never happen. return nil, errors.Errorf("[internal error] cannot add deny rule to systemd DeviceAllow list: %v", *rule) } switch rule.Type { case devices.BlockDevice, devices.CharDevice: default: // Should never happen. return nil, errors.Errorf("invalid device type for DeviceAllow: %v", rule.Type) } entry := deviceAllowEntry{ Perms: string(rule.Permissions), } // systemd has a fairly odd (though understandable) syntax here, and // because of the OCI configuration format we have to do quite a bit of // trickery to convert things: // // * Concrete rules with non-wildcard major/minor numbers have to use // /dev/{block,char} paths. This is slightly odd because it means // that we cannot add whitelist rules for devices that don't exist, // but there's not too much we can do about that. // // However, path globbing is not support for path-based rules so we // need to handle wildcards in some other manner. // // * Wildcard-minor rules have to specify a "device group name" (the // second column in /proc/devices). // // * Wildcard (major and minor) rules can just specify a glob with the // type ("char-*" or "block-*"). // // The only type of rule we can't handle is wildcard-major rules, and // so we'll give a warning in that case (note that the fallback code // will insert any rules systemd couldn't handle). What amazing fun. if rule.Major == devices.Wildcard { // "_ *:n _" rules aren't supported by systemd. if rule.Minor != devices.Wildcard { logrus.Warnf("systemd doesn't support '*:n' device rules -- temporarily ignoring rule: %v", *rule) continue } // "_ *:* _" rules just wildcard everything. prefix, err := groupPrefix(rule.Type) if err != nil { return nil, err } entry.Path = prefix + "*" } else if rule.Minor == devices.Wildcard { // "_ n:* _" rules require a device group from /proc/devices. group, err := findDeviceGroup(rule.Type, rule.Major) if err != nil { return nil, errors.Wrapf(err, "find device '%v/%d'", rule.Type, rule.Major) } if group == "" { // Couldn't find a group. logrus.Warnf("could not find device group for '%v/%d' in /proc/devices -- temporarily ignoring rule: %v", rule.Type, rule.Major, *rule) continue } entry.Path = group } else { // "_ n:m _" rules are just a path in /dev/{block,char}/. switch rule.Type { case devices.BlockDevice: entry.Path = fmt.Sprintf("/dev/block/%d:%d", rule.Major, rule.Minor) case devices.CharDevice: entry.Path = fmt.Sprintf("/dev/char/%d:%d", rule.Major, rule.Minor) } } deviceAllowList = append(deviceAllowList, entry) } properties = append(properties, newProp("DeviceAllow", deviceAllowList)) return properties, nil } func newProp(name string, units interface{}) systemdDbus.Property { return systemdDbus.Property{ Name: name, Value: dbus.MakeVariant(units), } } func getUnitName(c *configs.Cgroup) string { // by default, we create a scope unless the user explicitly asks for a slice. if !strings.HasSuffix(c.Name, ".slice") { return c.ScopePrefix + "-" + c.Name + ".scope" } return c.Name } // isUnitExists returns true if the error is that a systemd unit already exists. func isUnitExists(err error) bool { if err != nil { if dbusError, ok := err.(dbus.Error); ok { return strings.Contains(dbusError.Name, "org.freedesktop.systemd1.UnitExists") } } return false } func startUnit(dbusConnection *systemdDbus.Conn, unitName string, properties []systemdDbus.Property) error { statusChan := make(chan string, 1) if _, err := dbusConnection.StartTransientUnit(unitName, "replace", properties, statusChan); err == nil { timeout := time.NewTimer(30 * time.Second) defer timeout.Stop() select { case s := <-statusChan: close(statusChan) // Please refer to https://godoc.org/github.com/coreos/go-systemd/dbus#Conn.StartUnit if s != "done" { dbusConnection.ResetFailedUnit(unitName) return errors.Errorf("error creating systemd unit `%s`: got `%s`", unitName, s) } case <-timeout.C: dbusConnection.ResetFailedUnit(unitName) return errors.New("Timeout waiting for systemd to create " + unitName) } } else if !isUnitExists(err) { return err } return nil } func stopUnit(dbusConnection *systemdDbus.Conn, unitName string) error { statusChan := make(chan string, 1) if _, err := dbusConnection.StopUnit(unitName, "replace", statusChan); err == nil { select { case s := <-statusChan: close(statusChan) // Please refer to https://godoc.org/github.com/coreos/go-systemd/dbus#Conn.StartUnit if s != "done" { logrus.Warnf("error removing unit `%s`: got `%s`. Continuing...", unitName, s) } case <-time.After(time.Second): logrus.Warnf("Timed out while waiting for StopUnit(%s) completion signal from dbus. Continuing...", unitName) } } return nil } func systemdVersion(conn *systemdDbus.Conn) int { versionOnce.Do(func() { version = -1 verStr, err := conn.GetManagerProperty("Version") if err == nil { version, err = systemdVersionAtoi(verStr) } if err != nil { logrus.WithError(err).Error("unable to get systemd version") } }) return version } func systemdVersionAtoi(verStr string) (int, error) { // verStr should be of the form: // "v245.4-1.fc32", "245", "v245-1.fc32", "245-1.fc32" // all the input strings include quotes, and the output int should be 245 // thus, we unconditionally remove the `"v` // and then match on the first integer we can grab re := regexp.MustCompile(`"?v?([0-9]+)`) matches := re.FindStringSubmatch(verStr) if len(matches) < 2 { return 0, errors.Errorf("can't parse version %s: incorrect number of matches %v", verStr, matches) } ver, err := strconv.Atoi(matches[1]) return ver, errors.Wrapf(err, "can't parse version %s", verStr) } func addCpuQuota(conn *systemdDbus.Conn, properties *[]systemdDbus.Property, quota int64, period uint64) { if period != 0 { // systemd only supports CPUQuotaPeriodUSec since v242 sdVer := systemdVersion(conn) if sdVer >= 242 { *properties = append(*properties, newProp("CPUQuotaPeriodUSec", period)) } else { logrus.Debugf("systemd v%d is too old to support CPUQuotaPeriodSec "+ " (setting will still be applied to cgroupfs)", sdVer) } } if quota != 0 || period != 0 { // corresponds to USEC_INFINITY in systemd cpuQuotaPerSecUSec := uint64(math.MaxUint64) if quota > 0 { if period == 0 { // assume the default period = defCPUQuotaPeriod } // systemd converts CPUQuotaPerSecUSec (microseconds per CPU second) to CPUQuota // (integer percentage of CPU) internally. This means that if a fractional percent of // CPU is indicated by Resources.CpuQuota, we need to round up to the nearest // 10ms (1% of a second) such that child cgroups can set the cpu.cfs_quota_us they expect. cpuQuotaPerSecUSec = uint64(quota*1000000) / period if cpuQuotaPerSecUSec%10000 != 0 { cpuQuotaPerSecUSec = ((cpuQuotaPerSecUSec / 10000) + 1) * 10000 } } *properties = append(*properties, newProp("CPUQuotaPerSecUSec", cpuQuotaPerSecUSec)) } } func addCpuset(conn *systemdDbus.Conn, props *[]systemdDbus.Property, cpus, mems string) error { if cpus == "" && mems == "" { return nil } // systemd only supports AllowedCPUs/AllowedMemoryNodes since v244 sdVer := systemdVersion(conn) if sdVer < 244 { logrus.Debugf("systemd v%d is too old to support AllowedCPUs/AllowedMemoryNodes"+ " (settings will still be applied to cgroupfs)", sdVer) return nil } if cpus != "" { bits, err := rangeToBits(cpus) if err != nil { return fmt.Errorf("resources.CPU.Cpus=%q conversion error: %w", cpus, err) } *props = append(*props, newProp("AllowedCPUs", bits)) } if mems != "" { bits, err := rangeToBits(mems) if err != nil { return fmt.Errorf("resources.CPU.Mems=%q conversion error: %w", mems, err) } *props = append(*props, newProp("AllowedMemoryNodes", bits)) } return nil }
1
22,817
Also this probably should be `error.As()` or something like it.
opencontainers-runc
go
@@ -219,7 +219,9 @@ webdriver.CommandName = { GET_SESSION_LOGS: 'getSessionLogs', // Non-standard commands used by the standalone Selenium server. - UPLOAD_FILE: 'uploadFile' + UPLOAD_FILE: 'uploadFile', + + GET_CANVAS_URL: 'getCanvasUrl' };
1
// Copyright 2011 Software Freedom Conservancy. 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. /** * @fileoverview Contains several classes for handling commands. */ goog.provide('webdriver.Command'); goog.provide('webdriver.CommandExecutor'); goog.provide('webdriver.CommandName'); /** * Describes a command to be executed by the WebDriverJS framework. * @param {!webdriver.CommandName} name The name of this command. * @constructor */ webdriver.Command = function(name) { /** * The name of this command. * @private {!webdriver.CommandName} */ this.name_ = name; /** * The parameters to this command. * @private {!Object.<*>} */ this.parameters_ = {}; }; /** * @return {!webdriver.CommandName} This command's name. */ webdriver.Command.prototype.getName = function() { return this.name_; }; /** * Sets a parameter to send with this command. * @param {string} name The parameter name. * @param {*} value The parameter value. * @return {!webdriver.Command} A self reference. */ webdriver.Command.prototype.setParameter = function(name, value) { this.parameters_[name] = value; return this; }; /** * Sets the parameters for this command. * @param {!Object.<*>} parameters The command parameters. * @return {!webdriver.Command} A self reference. */ webdriver.Command.prototype.setParameters = function(parameters) { this.parameters_ = parameters; return this; }; /** * Returns a named command parameter. * @param {string} key The parameter key to look up. * @return {*} The parameter value, or undefined if it has not been set. */ webdriver.Command.prototype.getParameter = function(key) { return this.parameters_[key]; }; /** * @return {!Object.<*>} The parameters to send with this command. */ webdriver.Command.prototype.getParameters = function() { return this.parameters_; }; /** * Enumeration of predefined names command names that all command processors * will support. * @enum {string} */ // TODO: Delete obsolete command names. webdriver.CommandName = { GET_SERVER_STATUS: 'getStatus', NEW_SESSION: 'newSession', GET_SESSIONS: 'getSessions', DESCRIBE_SESSION: 'getSessionCapabilities', CLOSE: 'close', QUIT: 'quit', GET_CURRENT_URL: 'getCurrentUrl', GET: 'get', GO_BACK: 'goBack', GO_FORWARD: 'goForward', REFRESH: 'refresh', ADD_COOKIE: 'addCookie', GET_COOKIE: 'getCookie', GET_ALL_COOKIES: 'getCookies', DELETE_COOKIE: 'deleteCookie', DELETE_ALL_COOKIES: 'deleteAllCookies', GET_ACTIVE_ELEMENT: 'getActiveElement', FIND_ELEMENT: 'findElement', FIND_ELEMENTS: 'findElements', FIND_CHILD_ELEMENT: 'findChildElement', FIND_CHILD_ELEMENTS: 'findChildElements', CLEAR_ELEMENT: 'clearElement', CLICK_ELEMENT: 'clickElement', SEND_KEYS_TO_ELEMENT: 'sendKeysToElement', SUBMIT_ELEMENT: 'submitElement', GET_CURRENT_WINDOW_HANDLE: 'getCurrentWindowHandle', GET_WINDOW_HANDLES: 'getWindowHandles', GET_WINDOW_POSITION: 'getWindowPosition', SET_WINDOW_POSITION: 'setWindowPosition', GET_WINDOW_SIZE: 'getWindowSize', SET_WINDOW_SIZE: 'setWindowSize', MAXIMIZE_WINDOW: 'maximizeWindow', SWITCH_TO_WINDOW: 'switchToWindow', SWITCH_TO_FRAME: 'switchToFrame', GET_PAGE_SOURCE: 'getPageSource', GET_TITLE: 'getTitle', EXECUTE_SCRIPT: 'executeScript', EXECUTE_ASYNC_SCRIPT: 'executeAsyncScript', GET_ELEMENT_TEXT: 'getElementText', GET_ELEMENT_TAG_NAME: 'getElementTagName', IS_ELEMENT_SELECTED: 'isElementSelected', IS_ELEMENT_ENABLED: 'isElementEnabled', IS_ELEMENT_DISPLAYED: 'isElementDisplayed', GET_ELEMENT_LOCATION: 'getElementLocation', GET_ELEMENT_LOCATION_IN_VIEW: 'getElementLocationOnceScrolledIntoView', GET_ELEMENT_SIZE: 'getElementSize', GET_ELEMENT_ATTRIBUTE: 'getElementAttribute', GET_ELEMENT_VALUE_OF_CSS_PROPERTY: 'getElementValueOfCssProperty', ELEMENT_EQUALS: 'elementEquals', SCREENSHOT: 'screenshot', IMPLICITLY_WAIT: 'implicitlyWait', SET_SCRIPT_TIMEOUT: 'setScriptTimeout', SET_TIMEOUT: 'setTimeout', ACCEPT_ALERT: 'acceptAlert', DISMISS_ALERT: 'dismissAlert', GET_ALERT_TEXT: 'getAlertText', SET_ALERT_TEXT: 'setAlertValue', EXECUTE_SQL: 'executeSQL', GET_LOCATION: 'getLocation', SET_LOCATION: 'setLocation', GET_APP_CACHE: 'getAppCache', GET_APP_CACHE_STATUS: 'getStatus', CLEAR_APP_CACHE: 'clearAppCache', IS_BROWSER_ONLINE: 'isBrowserOnline', SET_BROWSER_ONLINE: 'setBrowserOnline', GET_LOCAL_STORAGE_ITEM: 'getLocalStorageItem', GET_LOCAL_STORAGE_KEYS: 'getLocalStorageKeys', SET_LOCAL_STORAGE_ITEM: 'setLocalStorageItem', REMOVE_LOCAL_STORAGE_ITEM: 'removeLocalStorageItem', CLEAR_LOCAL_STORAGE: 'clearLocalStorage', GET_LOCAL_STORAGE_SIZE: 'getLocalStorageSize', GET_SESSION_STORAGE_ITEM: 'getSessionStorageItem', GET_SESSION_STORAGE_KEYS: 'getSessionStorageKey', SET_SESSION_STORAGE_ITEM: 'setSessionStorageItem', REMOVE_SESSION_STORAGE_ITEM: 'removeSessionStorageItem', CLEAR_SESSION_STORAGE: 'clearSessionStorage', GET_SESSION_STORAGE_SIZE: 'getSessionStorageSize', SET_SCREEN_ORIENTATION: 'setScreenOrientation', GET_SCREEN_ORIENTATION: 'getScreenOrientation', // These belong to the Advanced user interactions - an element is // optional for these commands. CLICK: 'mouseClick', DOUBLE_CLICK: 'mouseDoubleClick', MOUSE_DOWN: 'mouseButtonDown', MOUSE_UP: 'mouseButtonUp', MOVE_TO: 'mouseMoveTo', SEND_KEYS_TO_ACTIVE_ELEMENT: 'sendKeysToActiveElement', // These belong to the Advanced Touch API TOUCH_SINGLE_TAP: 'touchSingleTap', TOUCH_DOWN: 'touchDown', TOUCH_UP: 'touchUp', TOUCH_MOVE: 'touchMove', TOUCH_SCROLL: 'touchScroll', TOUCH_DOUBLE_TAP: 'touchDoubleTap', TOUCH_LONG_PRESS: 'touchLongPress', TOUCH_FLICK: 'touchFlick', GET_AVAILABLE_LOG_TYPES: 'getAvailableLogTypes', GET_LOG: 'getLog', GET_SESSION_LOGS: 'getSessionLogs', // Non-standard commands used by the standalone Selenium server. UPLOAD_FILE: 'uploadFile' }; /** * Handles the execution of WebDriver {@link webdriver.Command commands}. * @interface */ webdriver.CommandExecutor = function() {}; /** * Executes the given {@code command}. If there is an error executing the * command, the provided callback will be invoked with the offending error. * Otherwise, the callback will be invoked with a null Error and non-null * {@link bot.response.ResponseObject} object. * @param {!webdriver.Command} command The command to execute. * @param {function(Error, !bot.response.ResponseObject=)} callback the function * to invoke when the command response is ready. */ webdriver.CommandExecutor.prototype.execute = goog.abstractMethod;
1
11,766
This is Safari specific and should be defined somewhere in the `safaridriver` namespace
SeleniumHQ-selenium
py
@@ -49,6 +49,13 @@ main(int argc, char *argv[]) exit (EXIT_SUCCESS); } + /* We conflict with the magic ostree-mount-deployment-var file for ostree-prepare-root */ + { struct stat stbuf; + if (fstatat (AT_FDCWD, "/run/ostree-mount-deployment-var", &stbuf, 0) == 0) + exit (EXIT_SUCCESS); + } + + if (argc > 1 && argc != 4) errx (EXIT_FAILURE, "This program takes three or no arguments");
1
/* * Copyright (C) 2017 Colin Walters <[email protected]> * * SPDX-License-Identifier: LGPL-2.0+ * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #include "config.h" #include <err.h> #include <unistd.h> #include <sys/stat.h> #include <fcntl.h> #include <stdlib.h> #include <libglnx.h> #include "ostree-cmdprivate.h" #include "ostree-mount-util.h" static const char *arg_dest = "/tmp"; static const char *arg_dest_late = "/tmp"; /* This program is a simple stub that calls the implementation that * lives inside libostree. */ int main(int argc, char *argv[]) { /* Important: if this isn't an ostree-booted system, do nothing; people could * have the package installed as a dependency for flatpak or whatever. */ { struct stat stbuf; if (fstatat (AT_FDCWD, "/run/ostree-booted", &stbuf, 0) < 0) exit (EXIT_SUCCESS); } if (argc > 1 && argc != 4) errx (EXIT_FAILURE, "This program takes three or no arguments"); if (argc > 1) arg_dest = argv[1]; if (argc > 3) arg_dest_late = argv[3]; char *ostree_cmdline = read_proc_cmdline_ostree (); if (!ostree_cmdline) errx (EXIT_FAILURE, "Failed to find ostree= kernel argument"); { g_autoptr(GError) local_error = NULL; if (!ostree_cmd__private__()->ostree_system_generator (ostree_cmdline, arg_dest, NULL, arg_dest_late, &local_error)) errx (EXIT_FAILURE, "%s", local_error->message); } exit (EXIT_SUCCESS); }
1
15,116
Let's maybe be nice and `unlinkat()` here in the interest of having `/run` be less littered. Or in addition/alternatively, make the file `/run/ostree/initramfs-mount-var` since we already made `/run/ostree/` for the deployment staging bits.
ostreedev-ostree
c
@@ -21,6 +21,7 @@ #include "teleport.h" #include "game.h" +#include <boost/format.hpp> extern Game g_game;
1
/** * The Forgotten Server - a free and open-source MMORPG server emulator * Copyright (C) 2019 Mark Samman <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "otpch.h" #include "teleport.h" #include "game.h" extern Game g_game; Attr_ReadValue Teleport::readAttr(AttrTypes_t attr, PropStream& propStream) { if (attr == ATTR_TELE_DEST) { if (!propStream.read<uint16_t>(destPos.x) || !propStream.read<uint16_t>(destPos.y) || !propStream.read<uint8_t>(destPos.z)) { return ATTR_READ_ERROR; } return ATTR_READ_CONTINUE; } return Item::readAttr(attr, propStream); } void Teleport::serializeAttr(PropWriteStream& propWriteStream) const { Item::serializeAttr(propWriteStream); propWriteStream.write<uint8_t>(ATTR_TELE_DEST); propWriteStream.write<uint16_t>(destPos.x); propWriteStream.write<uint16_t>(destPos.y); propWriteStream.write<uint8_t>(destPos.z); } ReturnValue Teleport::queryAdd(int32_t, const Thing&, uint32_t, uint32_t, Creature*) const { return RETURNVALUE_NOTPOSSIBLE; } ReturnValue Teleport::queryMaxCount(int32_t, const Thing&, uint32_t, uint32_t&, uint32_t) const { return RETURNVALUE_NOTPOSSIBLE; } ReturnValue Teleport::queryRemove(const Thing&, uint32_t, uint32_t) const { return RETURNVALUE_NOERROR; } Cylinder* Teleport::queryDestination(int32_t&, const Thing&, Item**, uint32_t&) { return this; } void Teleport::addThing(Thing* thing) { return addThing(0, thing); } void Teleport::addThing(int32_t, Thing* thing) { Tile* destTile = g_game.map.getTile(destPos); if (!destTile) { return; } const MagicEffectClasses effect = Item::items[id].magicEffect; if (Creature* creature = thing->getCreature()) { Position origPos = creature->getPosition(); g_game.internalCreatureTurn(creature, origPos.x > destPos.x ? DIRECTION_WEST : DIRECTION_EAST); g_game.map.moveCreature(*creature, *destTile); if (effect != CONST_ME_NONE) { g_game.addMagicEffect(origPos, effect); g_game.addMagicEffect(destTile->getPosition(), effect); } } else if (Item* item = thing->getItem()) { if (effect != CONST_ME_NONE) { g_game.addMagicEffect(destTile->getPosition(), effect); g_game.addMagicEffect(item->getPosition(), effect); } g_game.internalMoveItem(getTile(), destTile, INDEX_WHEREEVER, item, item->getItemCount(), nullptr, FLAG_NOLIMIT); } } void Teleport::updateThing(Thing*, uint16_t, uint32_t) { // } void Teleport::replaceThing(uint32_t, Thing*) { // } void Teleport::removeThing(Thing*, uint32_t) { // } void Teleport::postAddNotification(Thing* thing, const Cylinder* oldParent, int32_t index, cylinderlink_t) { getParent()->postAddNotification(thing, oldParent, index, LINK_PARENT); } void Teleport::postRemoveNotification(Thing* thing, const Cylinder* newParent, int32_t index, cylinderlink_t) { getParent()->postRemoveNotification(thing, newParent, index, LINK_PARENT); }
1
17,184
Not sure if this doesn't require explicitly adding this library to cmake.
otland-forgottenserver
cpp