// Tries to find a plan for the provided target; retrying five alternatives (calls to selectNewDestination). // If a valid plan is found; it publishes the target as a goal void findPlanFor(fd::_pose pose){ ROS_ERROR("Trying the given destination"); ros::NodeHandle n; ros::ServiceClient client = n.serviceClient<nav_msgs::GetPlan>("/move_base_node/make_plan"); nav_msgs::GetPlan srv; geometry_msgs::PoseStamped start_pose, goal_pose; tf::Quaternion q = tf::createQuaternionFromYaw(robot_pos.z); int tries = 5; bool found = false; do{ ROS_ERROR("Trying to find path"); --tries; start_pose.header.frame_id = "/map"; start_pose.pose.position.x=(robot_pos.x - mapSize[0]/2) * mapResolution; //convergence from occupancygrid indexes to map coordinates start_pose.pose.position.y=(robot_pos.y - mapSize[1]/2) * mapResolution; start_pose.pose.orientation.w = q.getW(); goal_pose.header.frame_id = "/map"; goal_pose.pose.position.x=(pose.x - mapSize[0]/2) * mapResolution; //convergence from occupancygrid indexes to map coordinates goal_pose.pose.position.y=(pose.y - mapSize[1]/2) * mapResolution; goal_pose.pose.orientation.w = q.getW(); srv.request.start = start_pose; srv.request.goal = goal_pose; found = false; if (client.call(srv)){ if (srv.response.plan.poses.size() == 0) { ROS_ERROR("... no plan found TRYING DIFFERENT!"); selectNewDestination(); pose = destination.pos; } else { found = true; ROS_ERROR("... found a plan!"); } } else { ROS_ERROR("... no communication so returning (We're still moving)!"); return; } } while(!found && tries >= 0); if(!found){ fsm = FSM_SELECT_NEW_GOAL; noPath = true; ROS_ERROR("... no goal found!"); return; } MoveBaseClient ac("move_base", true); while(!ac.waitForServer(ros::Duration(1.0))){} move_base_msgs::MoveBaseGoal goal; goal.target_pose.header.frame_id = "/map"; goal.target_pose.header.stamp = ros::Time::now(); goal.target_pose.pose.position.x=(pose.x - mapSize[0]/2) * mapResolution - 7.5 * mapResolution; //convergence from occupancygrid indexes to map coordinates goal.target_pose.pose.position.y=(pose.y - mapSize[1]/2) * mapResolution - 7.5 * mapResolution; goal.target_pose.pose.orientation.w = 1.0; { visualization_msgs::Marker goalPoint; goalPoint.header.stamp = ros::Time::now(); goalPoint.header.frame_id = "/map"; goalPoint.ns = "turtlebotSlam"; goalPoint.pose.orientation.w = 1.0; goalPoint.action = visualization_msgs::Marker::ADD; goalPoint.id = 0; goalPoint.type = visualization_msgs::Marker::POINTS; goalPoint.scale.x = mapResolution * 2.0f; goalPoint.scale.y = mapResolution * 2.0f; goalPoint.color.g = 1.0f; goalPoint.color.a = 1.0; geometry_msgs::Point p; p.x = (pose.x - mapSize[0]/2) * mapResolution - 7.5 * mapResolution; p.y = (pose.y - mapSize[1]/2) * mapResolution - 7.5 * mapResolution; //p.x = (destination.x - mapSize[0]/2) * mapResolution; //p.y= (destination.y - mapSize[1]/2) * mapResolution; p.z = 0.02; goalPoint.points.push_back(p); goalPoint.colors.push_back(goalPoint.color); goalPointPub.publish(goalPoint); ROS_ERROR("Published Goal Marker"); } { visualization_msgs::Marker goalPoint; goalPoint.header.stamp = ros::Time::now(); goalPoint.header.frame_id = "/map"; goalPoint.ns = "turtlebotSlam"; goalPoint.pose.orientation.w = 1.0; goalPoint.action = visualization_msgs::Marker::ADD; goalPoint.id = 1; goalPoint.type = visualization_msgs::Marker::POINTS; goalPoint.scale.x = mapResolution * 0.8f; goalPoint.scale.y = mapResolution * 0.8f; goalPoint.color.g = 1.0f; goalPoint.color.b = 1.0f; goalPoint.color.a = 1.0; geometry_msgs::Point p; p.x = (pose.x - mapSize[0]/2) * mapResolution - 7.5 * mapResolution; p.y = (pose.y - mapSize[1]/2) * mapResolution - 7.5 * mapResolution; //p.x = (destination.x - mapSize[0]/2) * mapResolution; //p.y= (destination.y - mapSize[1]/2) * mapResolution; p.z = 0.06; goalPoint.points.push_back(p); goalPoint.colors.push_back(goalPoint.color); goalPointPub.publish(goalPoint); ROS_ERROR("Published Goal Marker"); } goalPub.publish(goal); }
int main(int argc, char** argv){ ros::init(argc, argv, "simple_navigation_goals"); //tell the action client that we want to spin a thread by default MoveBaseClient ac("move_base", true); move_base_msgs::MoveBaseGoal goal; goal.target_pose.header.frame_id = "map"; goal.target_pose.header.stamp = ros::Time::now(); MoveBaseClient ac2("move_base", true); MoveBaseClient ac0("move_base", true); ros::Rate r(100); ros::NodeHandle n; int flag = 0; int sum = 0; ros::Publisher updown_flag = n.advertise<std_msgs::UInt8>("updown_flag",1); //std_msgs::UInt8 ud_flag; while(ros::ok()) { ROS_INFO("sum \t%d",sum); ROS_INFO("flag \t%d",flag); sum ++; switch(flag) { case 0:{ ROS_INFO("Hooray, the base moved 0 meter forward 0"); //wait for the action server to come up while(!ac.waitForServer(ros::Duration(5.0))){ ROS_INFO("Waiting for the move_base action server to come up"); } goal.target_pose.pose.position.x = 20; goal.target_pose.pose.position.y = 2.1; goal.target_pose.pose.orientation.z = 0; goal.target_pose.pose.orientation.w = 1; ROS_INFO("Sending goal"); ac.sendGoal(goal); ac.waitForResult(); if(ac.getState() == actionlib::SimpleClientGoalState::SUCCEEDED) { ROS_INFO("Hooray, the base moved 0 meter forward "); //ud_flag.data = 1; //updown_flag.publish(ud_flag); ros::Duration(120).sleep(); //ud_flag.data = 2; //updown_flag.publish(ud_flag); //ros::Duration(23).sleep(); flag = 1; } else ROS_INFO("The base failed to move forward 0 meter for some reason"); break; } case 1:{ //wait for the action server to come up while(!ac.waitForServer(ros::Duration(5.0))){ ROS_INFO("Waiting for the move_base action server to come up"); } goal.target_pose.pose.position.x = 0; goal.target_pose.pose.position.y = 0; goal.target_pose.pose.orientation.z = 0; goal.target_pose.pose.orientation.w = 1; ROS_INFO("Sending goal"); ac.sendGoal(goal); ac.waitForResult(); if(ac.getState() == actionlib::SimpleClientGoalState::SUCCEEDED) { ROS_INFO("Hooray, the base moved 1 meter forward"); //ud_flag.data = 1; //updown_flag.publish(ud_flag); ros::Duration(2000).sleep(); //ud_flag.data = 2; //updown_flag.publish(ud_flag); //ros::Duration(23).sleep(); flag = 2; } else ROS_INFO("The base failed to move forward 1 meter for some reason"); break; } case 2: { ROS_INFO("Hooray, the base moved 2 meter forward 0"); //wait for the action server to come up while(!ac.waitForServer(ros::Duration(5.0))){ ROS_INFO("Waiting for the move_base action server to come up"); } goal.target_pose.pose.position.x = 0; goal.target_pose.pose.position.y = 0; goal.target_pose.pose.orientation.z = 0; goal.target_pose.pose.orientation.w = 1; ROS_INFO("Sending goal"); ac.sendGoal(goal); ac.waitForResult(); if(ac.getState() == actionlib::SimpleClientGoalState::SUCCEEDED) { ROS_INFO("Hooray, the base moved 2 meter forward"); //ud_flag.data = 1; //updown_flag.publish(ud_flag); ros::Duration(20).sleep(); //ud_flag.data = 2; //updown_flag.publish(ud_flag); //ros::Duration(60).sleep(); flag = 0; } else ROS_INFO("The base failed to move forward 2 meter for some reason"); break; } } } return 0; }
JSObject * WrapperFactory::Rewrap(JSContext *cx, JSObject *existing, JSObject *obj, JSObject *wrappedProto, JSObject *parent, unsigned flags) { MOZ_ASSERT(!IsWrapper(obj) || GetProxyHandler(obj) == &XrayWaiver || js::GetObjectClass(obj)->ext.innerObject, "wrapped object passed to rewrap"); MOZ_ASSERT(JS_GetClass(obj) != &XrayUtils::HolderClass, "trying to wrap a holder"); MOZ_ASSERT(!js::IsInnerObject(obj)); // We sometimes end up here after nsContentUtils has been shut down but before // XPConnect has been shut down, so check the context stack the roundabout way. MOZ_ASSERT(XPCJSRuntime::Get()->GetJSContextStack()->Peek() == cx); // Compute the information we need to select the right wrapper. JSCompartment *origin = js::GetObjectCompartment(obj); JSCompartment *target = js::GetContextCompartment(cx); bool originIsChrome = AccessCheck::isChrome(origin); bool targetIsChrome = AccessCheck::isChrome(target); bool originSubsumesTarget = AccessCheck::subsumes(origin, target); bool targetSubsumesOrigin = AccessCheck::subsumes(target, origin); bool sameOrigin = targetSubsumesOrigin && originSubsumesTarget; XrayType xrayType = GetXrayType(obj); // By default we use the wrapped proto of the underlying object as the // prototype for our wrapper, but we may select something different below. JSObject *proxyProto = wrappedProto; Wrapper *wrapper; CompartmentPrivate *targetdata = EnsureCompartmentPrivate(target); // // First, handle the special cases. // // If UniversalXPConnect is enabled, this is just some dumb mochitest. Use // a vanilla CCW. if (xpc::IsUniversalXPConnectEnabled(target)) { wrapper = &CrossCompartmentWrapper::singleton; // If this is a chrome object being exposed to content without Xrays, use // a COW. } else if (originIsChrome && !targetIsChrome && xrayType == NotXray) { wrapper = &ChromeObjectWrapper::singleton; // If content is accessing a Components object or NAC, we need a special filter, // even if the object is same origin. } else if (IsComponentsObject(obj) && !AccessCheck::isChrome(target)) { wrapper = &FilteringWrapper<CrossCompartmentSecurityWrapper, ComponentsObjectPolicy>::singleton; } else if (AccessCheck::needsSystemOnlyWrapper(obj) && !(targetIsChrome || (targetSubsumesOrigin && nsContentUtils::IsCallerXBL()))) { wrapper = &FilteringWrapper<CrossCompartmentSecurityWrapper, OnlyIfSubjectIsSystem>::singleton; } // // Now, handle the regular cases. // // These are wrappers we can compute using a rule-based approach. In order // to do so, we need to compute some parameters. // else { // The wrapper is a security wrapper (protecting the wrappee) if and // only if the target does not subsume the origin. bool securityWrapper = !targetSubsumesOrigin; // Xrays are warranted if either the target or the origin don't trust // each other. This is generally the case, unless the two are same-origin // and the caller has not requested same-origin Xrays. // // Xrays are a bidirectional protection, since it affords clarity to the // caller and privacy to the callee. bool wantXrays = !(sameOrigin && !targetdata->wantXrays); // If Xrays are warranted, the caller may waive them for non-security // wrappers. bool waiveXrays = wantXrays && !securityWrapper && (flags & WAIVE_XRAY_WRAPPER_FLAG); wrapper = SelectWrapper(securityWrapper, wantXrays, xrayType, waiveXrays); } // If the prototype of a chrome object being wrapped in content is a prototype // for a standard class, use the one from the content compartment so // that we can safely take advantage of things like .forEach(). // // If the prototype chain of chrome object |obj| looks like this: // // obj => foo => bar => chromeWin.StandardClass.prototype // // The prototype chain of COW(obj) looks lke this: // // COW(obj) => COW(foo) => COW(bar) => contentWin.StandardClass.prototype if (wrapper == &ChromeObjectWrapper::singleton) { JSProtoKey key = JSProto_Null; { JSAutoCompartment ac(cx, obj); JSObject *unwrappedProto; if (!js::GetObjectProto(cx, obj, &unwrappedProto)) return NULL; if (unwrappedProto && IsCrossCompartmentWrapper(unwrappedProto)) unwrappedProto = Wrapper::wrappedObject(unwrappedProto); if (unwrappedProto) { JSAutoCompartment ac2(cx, unwrappedProto); key = JS_IdentifyClassPrototype(cx, unwrappedProto); } } if (key != JSProto_Null) { JSObject *homeProto; if (!JS_GetClassPrototype(cx, key, &homeProto)) return NULL; MOZ_ASSERT(homeProto); proxyProto = homeProto; } // This shouldn't happen, but do a quick check to make some dumb addon // doesn't expose chrome eval or Function(). JSFunction *fun = JS_GetObjectFunction(obj); if (fun) { if (JS_IsBuiltinEvalFunction(fun) || JS_IsBuiltinFunctionConstructor(fun)) { JS_ReportError(cx, "Not allowed to access chrome eval or Function from content"); return nullptr; } } } DEBUG_CheckUnwrapSafety(obj, wrapper, origin, target); if (existing && proxyProto == wrappedProto) return Wrapper::Renew(cx, existing, obj, wrapper); return Wrapper::New(cx, obj, proxyProto, parent, wrapper); }
size_t SkGlyphCache_Globals::getTotalMemoryUsed() const { SkAutoExclusive ac(fLock); return fTotalMemoryUsed; }
size_t SkGlyphCache_Globals::getCacheSizeLimit() const { SkAutoExclusive ac(fLock); return fCacheSizeLimit; }
BOOL CSocketWnd::RegisterSocket( SOCKET sock,ISocketWinListener* listener ) { Util::CAutoCS ac(m_cs); m_listeners[sock] = listener; return TRUE; }
int main(int argc, char **argv){ ros::init(argc, argv, "automap"); ros::NodeHandle nh; // create dynamic reconfigure object dynamic_reconfigure::Server<automap::ExplorationConfig> server; dynamic_reconfigure::Server<automap::ExplorationConfig>::CallbackType f; automap::ExplorationConfig dynConfig; ros::Time initTime = ros::Time::now(); nav_msgs::MapMetaData mapMetaData; cv::Mat map; simulation::telemetry_msg telemetry; sensor_msgs::ImagePtr edgeImageMsg; MoveBaseClient ac("move_base", true); while(!ac.waitForServer(ros::Duration(5.0)) && ros::ok()) { ROS_INFO("Waiting for the move_base action server to come up..."); } //control_On : motion control on/off / detection_On : sensing on/off / NBV_On : nbv on/off automap::automap_ctrl_msg ctrlSignals; tf::TransformListener listener; geometry_msgs::Pose position; std::vector<double> rpy(3, 0.0); cv::Point gridPose; ros::Subscriber mapMetaSub = nh.subscribe<nav_msgs::MapMetaData>("map_metadata", 10, boost::bind(mapMetaCallback, _1, &mapMetaData)); ros::Subscriber ctrlSub = nh.subscribe<automap::automap_ctrl_msg>("automap/ctrl_msg", 10, boost::bind(ctrlCallback, _1, &ctrlSignals)); ros::Subscriber mapSub = nh.subscribe<nav_msgs::OccupancyGrid>("map", 10, boost::bind(mapCallback, _1, &map)); ros::Publisher pathPub = nh.advertise<nav_msgs::Path>("pathtransformPlanner/path", 10); ros::Subscriber robotInfo = nh.subscribe<simulation::telemetry_msg>("telemetry", 10, boost::bind(telemetryCallback, _1, &telemetry)); image_transport::ImageTransport it(nh); image_transport::Publisher edgePub = it.advertise("floatingEdges", 1); //wait for map - server ros::Duration d = ros::Duration(2, 0); ros::spinOnce(); while(mapMetaData.resolution == 0 && ros::ok()) { ROS_INFO("Waiting for the map server to come up..."); d.sleep(); ros::spinOnce(); } while(map.cols==0 && map.rows==0 && ros::ok()) { ROS_INFO("Waiting for the map server to come up..."); d.sleep(); ros::spinOnce(); } PathtransformPlanner pPlanner(mapMetaData); ExplorationPlanner ePlanner(&pPlanner); // Begin: exploration metrics // array for drawing the robots path std::vector<cv::Point> explorationPath; // average planner time ros::Time planner_timer; double t_planner = 0; unsigned int t_planner_counter = 0; // average ex-planner time ros::Time explanner_timer; double t_explanner = 0; unsigned int t_explanner_counter = 0; // average busy loop time ros::Time loop_timer; double t_loop = 0; unsigned int t_loop_counter = 0; double timediff = 0; f = boost::bind(&configCallback, _1, _2, &pPlanner, &ePlanner, &dynConfig); server.setCallback(f); ctrlSignals.control_On=dynConfig.node_control_on; ctrlSignals.detection_On=dynConfig.node_sensing_on; ctrlSignals.NBV_On=dynConfig.node_use_nbv; bool finished = false; bool finalCheck = false; int retry = dynConfig.node_retries; cv::Mat old = cv::Mat::zeros(map.rows, map.cols, CV_8UC1); // Loop starts here: ros::Rate loop_rate(dynConfig.node_loop_rate); while(ros::ok() && !finished) { //start measure processing time loop_timer = ros::Time::now(); //calculate information gain double gain = cv::norm(old, map, CV_L2); //Get Position Information... getPositionInfo("map", "base_footprint", listener, &position, &rpy); setGridPosition(position, mapMetaData, &gridPose); //Remember path explorationPath.push_back(gridPose); if(gain>dynConfig.node_information_gain || retry==0) { ROS_INFO("Enough information gained: %lf",gain); old = map.clone(); retry = dynConfig.node_retries; //Feed pathtransformPlanner... try{ ROS_INFO("Feeding PathtransformPlanner..."); //start measure processing time planner_timer = ros::Time::now(); pPlanner.updateTransformMatrices(map, gridPose); //stop measure processing time timediff = (ros::Time::now()-planner_timer).toNSec()/NSEC_PER_SEC; t_planner += timediff; t_planner_counter++; ROS_INFO("Path planning took: %lf",timediff); }catch(std::exception& e) { std::cout<<e.what()<<std::endl; } bool w = false; if(ctrlSignals.detection_On) { //start measure processing time explanner_timer = ros::Time::now(); w = ePlanner.findBestPlan(map, gridPose, rpy[2], ctrlSignals.NBV_On); //stop measure processing time timediff = (ros::Time::now()-explanner_timer).toNSec()/NSEC_PER_SEC; t_explanner += timediff; t_explanner_counter++; ROS_INFO("Exploration planning took: %lf",timediff); if(!w && !finalCheck){ finalCheck = true; continue; } }else{ w = true; } if(w) { finalCheck =false; ROS_INFO("Best next Plan found!"); std_msgs::Header genericHeader; genericHeader.stamp = ros::Time::now(); genericHeader.frame_id = "map"; // send map with valid detected Edges if(dynConfig.node_show_exploration_planner_result){ cv::Mat out = ePlanner.drawFrontiers(); edgeImageMsg = cv_bridge::CvImage(std_msgs::Header(), "bgr8", out).toImageMsg(); edgePub.publish(edgeImageMsg); } nav_msgs::Path frontierPath; if(ctrlSignals.detection_On) { frontierPath = ePlanner.getBestPlan(genericHeader); } if(ctrlSignals.control_On && ctrlSignals.detection_On) { ROS_INFO("Sending Plan.."); pathPub.publish(frontierPath); ros::spinOnce(); ROS_INFO("Sending Goal.."); sendGoal(frontierPath, ac); } }else{ ROS_INFO("Map exploration finished, aborting loop..."); //ac.waitForResult(); ac.cancelGoal(); ac.waitForResult(); std::string imgMetaPath = ros::package::getPath("automap") + "/data/output/map.yaml"; std::string imgStatPath = ros::package::getPath("automap") + "/data/output/exploration_statistics.txt"; std::string imgPath = ros::package::getPath("automap") + "/data/output/map.pgm"; std::string recordedPathPath = ros::package::getPath("automap") + "/data/output/path.png"; //Save explored map std::vector<int> com_param; com_param.push_back(CV_IMWRITE_PNG_COMPRESSION); com_param.push_back(9); try { cv::imwrite(imgPath, map, com_param); ROS_INFO("Map written to: %s", imgPath.c_str()); } catch (std::runtime_error& ex) { std::cout << "Exception converting img to PNG: " << ex.what() << std::endl; } //Save exploration path cv::Mat pathMap = map.clone(); cv::cvtColor(pathMap, pathMap, CV_GRAY2RGB); cv::polylines(pathMap, explorationPath, false, cv::Scalar(0, 0, 255), 1, 8); try { cv::imwrite(recordedPathPath, pathMap, com_param); ROS_INFO("Path written to: %s", recordedPathPath.c_str()); } catch (std::runtime_error& ex) { std::cout << "Exception converting img to PNG: " << ex.what() << std::endl; } YAML::Emitter Y_out; Y_out << YAML::BeginMap; Y_out << YAML::Key << "image"; Y_out << YAML::Value << "map.pgm"; Y_out << YAML::Key << "resolution"; Y_out << YAML::Value << mapMetaData.resolution; Y_out << YAML::Key << "origin"; Y_out << YAML::Flow; Y_out << YAML::BeginSeq << mapMetaData.origin.position.x<<mapMetaData.origin.position.y <<mapMetaData.origin.position.z << YAML::EndSeq; Y_out << YAML::Key << "negate"; Y_out << YAML::Value << 0; Y_out << YAML::Key << "occupied_thresh"; Y_out << YAML::Value << 0.65; Y_out << YAML::Key << "free_thresh"; Y_out << YAML::Value << 0.196; Y_out << YAML::EndMap; YAML::Emitter Y_out_statistics; Y_out_statistics << YAML::BeginMap; Y_out_statistics << YAML::Key << "driven distance during exploration(m)"; Y_out_statistics << YAML::Value << telemetry.radial_distance; Y_out_statistics << YAML::Key << "time elapsed during exploration(s)"; Y_out_statistics << YAML::Value << (ros::Time::now()-initTime).toNSec()/NSEC_PER_SEC; Y_out_statistics << YAML::Key << "average path planner processing time(s)"; Y_out_statistics << YAML::Value << t_planner/t_planner_counter; Y_out_statistics << YAML::Key << "average exploration planner processing time(s)"; Y_out_statistics << YAML::Value << t_explanner/t_explanner_counter; Y_out_statistics << YAML::Key << "average busy loop processing time(s)"; Y_out_statistics << YAML::Value << t_loop/t_loop_counter; // calc quality of map std::string godMapPath = ros::package::getPath("simulation") + "/data/map/map.pgm"; cv::Mat godMap = cv::imread(godMapPath,1); cv::cvtColor(godMap, godMap, CV_RGB2GRAY); double diffMap = cv::norm(godMap, map, CV_L2); Y_out_statistics << YAML::Key << "in comparison to god map (L2Norm)"; Y_out_statistics << YAML::Value << diffMap; Y_out_statistics << YAML::EndMap; std::ofstream outfile_yaml(imgMetaPath); try{ outfile_yaml<<Y_out.c_str(); ROS_INFO("MapMetaData written to: %s", imgMetaPath.c_str()); }catch (std::runtime_error& ex) { std::cout << "Exception writing .yaml-file: " << ex.what() << std::endl; } outfile_yaml.close(); std::ofstream outfile_statistics(imgStatPath); try{ outfile_statistics<<Y_out_statistics.c_str(); ROS_INFO("Statistics data written to: %s", imgStatPath.c_str()); }catch (std::runtime_error& ex) { std::cout << "Exception writing .txt-file: " << ex.what() << std::endl; } outfile_statistics.close(); finished = true; ros::shutdown(); } }else{ ROS_INFO("Not enough information gained: %lf",gain); retry--; } // resend map with valid detected Edges if(dynConfig.node_show_exploration_planner_result){ cv::Mat out = ePlanner.drawFrontiers(); edgeImageMsg = cv_bridge::CvImage(std_msgs::Header(), "bgr8", out).toImageMsg(); edgePub.publish(edgeImageMsg); } //stop measure processing time timediff = (ros::Time::now()-loop_timer).toNSec()/NSEC_PER_SEC; t_loop += timediff; t_loop_counter++; ROS_INFO("Whole loop took: %lf",timediff); ros::spinOnce(); loop_rate.sleep(); } ros::spin(); }
nsresult EventListenerManager::CompileEventHandlerInternal(Listener* aListener, const nsAString* aBody, Element* aElement) { NS_PRECONDITION(aListener->GetJSListener(), "Why do we not have a JS listener?"); NS_PRECONDITION(aListener->mHandlerIsString, "Why are we compiling a non-string JS listener?"); nsresult result = NS_OK; nsIJSEventListener* jsListener = aListener->GetJSListener(); NS_ASSERTION(!jsListener->GetHandler().HasEventHandler(), "What is there to compile?"); nsCOMPtr<nsIDocument> doc; nsCOMPtr<nsIScriptGlobalObject> global = GetScriptGlobalAndDocument(getter_AddRefs(doc)); NS_ENSURE_STATE(global); nsIScriptContext* context = global->GetScriptContext(); NS_ENSURE_STATE(context); // Push a context to make sure exceptions are reported in the right place. AutoPushJSContext cx(context->GetNativeContext()); JS::Rooted<JSObject*> handler(cx); JS::Rooted<JSObject*> scope(cx, jsListener->GetEventScope()); nsCOMPtr<nsIAtom> typeAtom = aListener->mTypeAtom; nsIAtom* attrName = typeAtom; if (aListener->mHandlerIsString) { // OK, we didn't find an existing compiled event handler. Flag us // as not a string so we don't keep trying to compile strings // which can't be compiled aListener->mHandlerIsString = false; // mTarget may not be an Element if it's a window and we're // getting an inline event listener forwarded from <html:body> or // <html:frameset> or <xul:window> or the like. // XXX I don't like that we have to reference content from // here. The alternative is to store the event handler string on // the nsIJSEventListener itself, and that still doesn't address // the arg names issue. nsCOMPtr<Element> element = do_QueryInterface(mTarget); MOZ_ASSERT(element || aBody, "Where will we get our body?"); nsAutoString handlerBody; const nsAString* body = aBody; if (!aBody) { if (aListener->mTypeAtom == nsGkAtoms::onSVGLoad) { attrName = nsGkAtoms::onload; } else if (aListener->mTypeAtom == nsGkAtoms::onSVGUnload) { attrName = nsGkAtoms::onunload; } else if (aListener->mTypeAtom == nsGkAtoms::onSVGResize) { attrName = nsGkAtoms::onresize; } else if (aListener->mTypeAtom == nsGkAtoms::onSVGScroll) { attrName = nsGkAtoms::onscroll; } else if (aListener->mTypeAtom == nsGkAtoms::onSVGZoom) { attrName = nsGkAtoms::onzoom; } else if (aListener->mTypeAtom == nsGkAtoms::onbeginEvent) { attrName = nsGkAtoms::onbegin; } else if (aListener->mTypeAtom == nsGkAtoms::onrepeatEvent) { attrName = nsGkAtoms::onrepeat; } else if (aListener->mTypeAtom == nsGkAtoms::onendEvent) { attrName = nsGkAtoms::onend; } element->GetAttr(kNameSpaceID_None, attrName, handlerBody); body = &handlerBody; aElement = element; } aListener = nullptr; uint32_t lineNo = 0; nsAutoCString url (NS_LITERAL_CSTRING("-moz-evil:lying-event-listener")); MOZ_ASSERT(body); MOZ_ASSERT(aElement); nsIURI *uri = aElement->OwnerDoc()->GetDocumentURI(); if (uri) { uri->GetSpec(url); lineNo = 1; } uint32_t argCount; const char **argNames; nsContentUtils::GetEventArgNames(aElement->GetNameSpaceID(), typeAtom, &argCount, &argNames); JSAutoCompartment ac(cx, context->GetWindowProxy()); JS::CompileOptions options(cx); options.setIntroductionType("eventHandler") .setFileAndLine(url.get(), lineNo) .setVersion(SCRIPTVERSION_DEFAULT); JS::Rooted<JS::Value> targetVal(cx); // Go ahead and wrap into the current compartment of cx directly. JS::Rooted<JSObject*> wrapScope(cx, JS::CurrentGlobalOrNull(cx)); if (WrapNewBindingObject(cx, wrapScope, aElement, &targetVal)) { MOZ_ASSERT(targetVal.isObject()); nsDependentAtomString str(attrName); // Most of our names are short enough that we don't even have to malloc // the JS string stuff, so don't worry about playing games with // refcounting XPCOM stringbuffers. JS::Rooted<JSString*> jsStr(cx, JS_NewUCStringCopyN(cx, str.BeginReading(), str.Length())); NS_ENSURE_TRUE(jsStr, NS_ERROR_OUT_OF_MEMORY); options.setElement(&targetVal.toObject()) .setElementAttributeName(jsStr); } JS::Rooted<JSObject*> handlerFun(cx); result = nsJSUtils::CompileFunction(cx, JS::NullPtr(), options, nsAtomCString(typeAtom), argCount, argNames, *body, handlerFun.address()); NS_ENSURE_SUCCESS(result, result); handler = handlerFun; NS_ENSURE_TRUE(handler, NS_ERROR_FAILURE); } else { aListener = nullptr; } if (handler) { nsCOMPtr<nsPIDOMWindow> win = do_QueryInterface(mTarget); // Bind it JS::Rooted<JSObject*> boundHandler(cx); context->BindCompiledEventHandler(mTarget, scope, handler, &boundHandler); // Note - We pass null for aIncumbentGlobal below. We could also pass the // compilation global, but since the handler is guaranteed to be scripted, // there's no need to use an override, since the JS engine will always give // us the right answer. if (!boundHandler) { jsListener->ForgetHandler(); } else if (jsListener->EventName() == nsGkAtoms::onerror && win) { nsRefPtr<OnErrorEventHandlerNonNull> handlerCallback = new OnErrorEventHandlerNonNull(boundHandler, /* aIncumbentGlobal = */ nullptr); jsListener->SetHandler(handlerCallback); } else if (jsListener->EventName() == nsGkAtoms::onbeforeunload && win) { nsRefPtr<OnBeforeUnloadEventHandlerNonNull> handlerCallback = new OnBeforeUnloadEventHandlerNonNull(boundHandler, /* aIncumbentGlobal = */ nullptr); jsListener->SetHandler(handlerCallback); } else { nsRefPtr<EventHandlerNonNull> handlerCallback = new EventHandlerNonNull(boundHandler, /* aIncumbentGlobal = */ nullptr); jsListener->SetHandler(handlerCallback); } } return result; }
NS_IMETHODIMP nsSpeechTask::SendAudio(JS::Handle<JS::Value> aData, JS::Handle<JS::Value> aLandmarks, JSContext* aCx) { MOZ_ASSERT(XRE_IsParentProcess()); if(NS_WARN_IF(!(mStream))) { return NS_ERROR_NOT_AVAILABLE; } if(NS_WARN_IF(mStream->IsDestroyed())) { return NS_ERROR_NOT_AVAILABLE; } if(NS_WARN_IF(!(mChannels))) { return NS_ERROR_FAILURE; } if(NS_WARN_IF(!(aData.isObject()))) { return NS_ERROR_INVALID_ARG; } if (mIndirectAudio) { NS_WARNING("Can't call SendAudio from an indirect audio speech service."); return NS_ERROR_FAILURE; } JS::Rooted<JSObject*> darray(aCx, &aData.toObject()); JSAutoCompartment ac(aCx, darray); JS::Rooted<JSObject*> tsrc(aCx, nullptr); // Allow either Int16Array or plain JS Array if (JS_IsInt16Array(darray)) { tsrc = darray; } else { bool isArray; if (!JS_IsArrayObject(aCx, darray, &isArray)) { return NS_ERROR_UNEXPECTED; } if (isArray) { tsrc = JS_NewInt16ArrayFromArray(aCx, darray); } } if (!tsrc) { return NS_ERROR_DOM_TYPE_MISMATCH_ERR; } uint32_t dataLen = JS_GetTypedArrayLength(tsrc); RefPtr<mozilla::SharedBuffer> samples; { JS::AutoCheckCannotGC nogc; bool isShared; int16_t* data = JS_GetInt16ArrayData(tsrc, &isShared, nogc); if (isShared) { // Must opt in to using shared data. return NS_ERROR_DOM_TYPE_MISMATCH_ERR; } samples = makeSamples(data, dataLen); } SendAudioImpl(samples, dataLen); return NS_OK; }
int main (int argc, char **argv) { ros::init(argc, argv, "test_movearm"); // create the action client // true causes the client to spin its own thread actionlib::SimpleActionClient<race_move_arms::MovearmAction> ac("race_movearm", true); ROS_INFO("Waiting for action server to start."); // wait for the action server to start ac.waitForServer(); //will wait for infinite time ROS_INFO("Action server started, sending goal."); // send a goal to the action race_move_arms::MovearmGoal goal; const uint8_t armposturecount = 4; uint8_t armpostures [armposturecount]; armpostures[0] = race_move_arms::MovearmPosture::ARMTOSIDEPOSTURE; armpostures[1] = race_move_arms::MovearmPosture::ARMTUCKEDPOSTURE; armpostures[2] = race_move_arms::MovearmPosture::ARMUNTUCKEDPOSTURE; armpostures[3] = race_move_arms::MovearmPosture::ARMCARRYPOSTURE; uint8_t leftarm; uint8_t rightarm; // parse command line arguments if (argc == 3) { leftarm = atoi(argv[1]); rightarm = atoi(argv[2]); assert(leftarm < armposturecount); assert(rightarm < armposturecount); //assert(leftarm >= 0); //assert(rightarm >= 0); ROS_INFO("sending leftarm: %d, rightarm: %d", armpostures[leftarm], armpostures[rightarm]); goal.leftarm.armposture = armpostures[leftarm]; goal.rightarm.armposture = armpostures[rightarm]; ac.sendGoal(goal); //wait for the action to return bool finished_before_timeout = ac.waitForResult(ros::Duration(200.0)); if (finished_before_timeout) { actionlib::SimpleClientGoalState state = ac.getState(); bool success = (state == actionlib::SimpleClientGoalState::SUCCEEDED); if (success) ROS_INFO("Action finished: %s",state.toString().c_str()); else ROS_INFO("Action failed: %s",state.toString().c_str()); } else { ac.cancelGoal(); ROS_INFO("Action did not finish before the time out."); } } else // default values { ROS_INFO("Sending %d goals", armposturecount * armposturecount); for (uint32_t i=0; i < armposturecount; i++) { for (uint32_t j=0; j < armposturecount; j++) { goal.leftarm.armposture = armpostures[i]; goal.rightarm.armposture = armpostures[j]; ROS_INFO("sending leftarm: %d, rightarm: %d", armpostures[i], armpostures[j]); ac.sendGoal(goal); //wait for the action to return bool finished_before_timeout = ac.waitForResult(ros::Duration(200.0)); if (finished_before_timeout) { actionlib::SimpleClientGoalState state = ac.getState(); ROS_INFO("Action finished: %s",state.toString().c_str()); } else { ROS_INFO("Action did not finish before the time out."); } //ros::Duration(0.5).sleep(); } } } //exit return 0; }
int main(int argc, char** argv) { ros::init(argc, argv, "waypoint_client"); ros::NodeHandle nh; float maxSpeed; float accuracy; ros::Duration timeout(15); if (argc == 5) { maxSpeed = 0.5; accuracy = 0.3; } else if (argc == 6) { maxSpeed = atof(argv[5]); accuracy = 0.3; } else if (argc == 7) { maxSpeed = atof(argv[5]); accuracy = atof(argv[6]); } else if (argc == 8) { maxSpeed = atof(argv[5]); accuracy = atof(argv[6]); timeout = ros::Duration(atof(argv[7])); } else { std::cout << "Wrong number of arguments! \nusage:" << "\twpclient x y z yaw \n" << "\twpclient x y z yaw max_speed\n" << "\twpclient x y z yaw max_speed accuracy\n" << "\twpclient x y z yaw max_speed accuracy timeout\n" << std::endl; return -1; } actionlib::SimpleActionClient<asctec_hl_comm::WaypointAction> ac(nh, "fcu/waypoint", true); asctec_hl_comm::WaypointGoal goal; ROS_INFO("Waiting for action server to start."); ac.waitForServer(); //will wait for infinite time ROS_INFO("Action server started, sending goal."); goal.goal_pos.x = atof(argv[1]); goal.goal_pos.y = atof(argv[2]); goal.goal_pos.z = atof(argv[3]); goal.max_speed.x = maxSpeed; goal.max_speed.y = maxSpeed; goal.max_speed.z = maxSpeed; goal.goal_yaw = atof(argv[4]); goal.accuracy_position = accuracy; goal.accuracy_orientation = 0; goal.timeout = timeout.toSec(); ac.sendGoal(goal, &doneCb, &activeCb, &feedbackCB); //wait for the action to return bool finished_before_timeout = ac.waitForResult(timeout); if (!finished_before_timeout) { ROS_WARN("Action did not finish before the time out."); } return 0; }
void imageCB(const sensor_msgs::ImageConstPtr& msg) { actionlib::SimpleActionClient<pan_tilt_image_processing::AutoFocusAction> ac("auto_focus", true); //ROS_INFO("Waiting for action server to start."); // wait for the action server to start ac.waitForServer(); //will wait for infinite time pan_tilt_image_processing::AutoFocusGoal goal; if (init_) { // send a goal to the action goal.order = _direction; ac.sendGoal(goal); init_ = false; } if ( (time(¤tTime_) - initTime_ ) > SECONDS && !_salir) { initTime_ = currentTime_; if (!_cambio) { goal.order = 3; //paro el enfoque cuando abre ac.sendGoal(goal); sleep(1); //pausa para asegurarnos de que no hay conflicto entre el envio de la orden parar y marcha _cambio = true; initTime_ = currentTime_; goal.order = _direction = 2; std::cout << "CAMBIO!" << std::endl; ac.sendGoal(goal); //cambio el sentido del enfoque } else { goal.order = 4; //paro el enfoque cuando cierra ac.sendGoal(goal); sleep(1); _salir = true; goal.order = _direction = 1; //volvemos a enfocar al inifinito ROS_INFO("The maximum Sobel is %f", maxValue_); ac.sendGoal(goal); } } if(!_salir) { double resSobel = calculateSobel(msg); if ( resSobel > maxValue_){ maxValue_ = resSobel; std::cout << "entra aki?" << std::endl; } } else { goal.order = 3; //paro el enfoque cuando abre if((abs(maxValue_ - calculateSobel(msg)) < 0.1) ) { ac.sendGoal(goal); sleep(1); ROS_INFO("FOCUSED %f", maxValue_); goal.order = _direction = 0; ac.sendGoal(goal); exit(EXIT_SUCCESS); } else if( (time(¤tTime_) - initTime_ ) > SECONDS ) { ROS_INFO ("DONT FUCUSED :("); ac.sendGoal(goal); usleep(1500); exit(0); } } }
void AutoJSAPI::ReportException() { if (!HasException()) { return; } // AutoJSAPI uses a JSAutoNullableCompartment, and may be in a null // compartment when the destructor is called. However, the JS engine // requires us to be in a compartment when we fetch the pending exception. // In this case, we enter the privileged junk scope and don't dispatch any // error events. JS::Rooted<JSObject*> errorGlobal(cx(), JS::CurrentGlobalOrNull(cx())); if (!errorGlobal) { if (mIsMainThread) { errorGlobal = xpc::PrivilegedJunkScope(); } else { errorGlobal = workers::GetCurrentThreadWorkerGlobal(); } } JSAutoCompartment ac(cx(), errorGlobal); JS::Rooted<JS::Value> exn(cx()); js::ErrorReport jsReport(cx()); if (StealException(&exn) && jsReport.init(cx(), exn, js::ErrorReport::WithSideEffects)) { if (mIsMainThread) { RefPtr<xpc::ErrorReport> xpcReport = new xpc::ErrorReport(); RefPtr<nsGlobalWindow> win = xpc::WindowGlobalOrNull(errorGlobal); if (!win) { // We run addons in a separate privileged compartment, but they still // expect to trigger the onerror handler of their associated DOM Window. win = xpc::AddonWindowOrNull(errorGlobal); } nsPIDOMWindowInner* inner = win ? win->AsInner() : nullptr; xpcReport->Init(jsReport.report(), jsReport.toStringResult().c_str(), nsContentUtils::IsCallerChrome(), inner ? inner->WindowID() : 0); if (inner && jsReport.report()->errorNumber != JSMSG_OUT_OF_MEMORY) { JS::RootingContext* rcx = JS::RootingContext::get(cx()); DispatchScriptErrorEvent(inner, rcx, xpcReport, exn); } else { JS::Rooted<JSObject*> stack(cx(), xpc::FindExceptionStackForConsoleReport(inner, exn)); xpcReport->LogToConsoleWithStack(stack); } } else { // On a worker, we just use the worker error reporting mechanism and don't // bother with xpc::ErrorReport. This will ensure that all the right // events (which are a lot more complicated than in the window case) get // fired. workers::WorkerPrivate* worker = workers::GetCurrentThreadWorkerPrivate(); MOZ_ASSERT(worker); MOZ_ASSERT(worker->GetJSContext() == cx()); // Before invoking ReportError, put the exception back on the context, // because it may want to put it in its error events and has no other way // to get hold of it. After we invoke ReportError, clear the exception on // cx(), just in case ReportError didn't. JS_SetPendingException(cx(), exn); worker->ReportError(cx(), jsReport.toStringResult(), jsReport.report()); ClearException(); } } else { NS_WARNING("OOMed while acquiring uncaught exception from JSAPI"); ClearException(); } }
int main() { int pid1 = 0; int pid2 = 0; try { std::cout << "Cancel before" << std::endl; io::io_service srv; the_service = &srv; io::acceptor ac(srv); the_socket = ∾ ac.open(io::pf_inet); ac.set_option(io::basic_socket::reuse_address,true); io::endpoint ep("127.0.0.1",8080); ac.bind(ep); ac.listen(5); io::stream_socket s1(srv); ac.async_accept(s1,socket_accept_failer); ac.cancel(); srv.run(); TEST(called); called=false; srv.reset(); std::cout << "Cancel by timer" << std::endl; io::deadline_timer dt(srv); dt.expires_from_now(booster::ptime::milliseconds(100)); dt.async_wait(socket_canceler); ac.async_accept(s1,socket_accept_failer); srv.run(); TEST(called); called=false; srv.reset(); std::cout << "Cancel by thread" << std::endl; booster::thread t1(thread_socket_canceler); ac.async_accept(s1,socket_accept_failer); srv.run(); TEST(called); called=false; t1.join(); srv.reset(); std::cout << "Accept by thread" << std::endl; booster::thread t2(thread_socket_connector); ac.async_accept(s1,async_socket_writer); accepted_socket=&s1; srv.run(); TEST(called); called=false; t2.join(); srv.reset(); s1.close(); std::cout << "Acceptor is shared" << std::endl; pid1=fork(); if(pid1==0) { child(); return 0; } pid2=fork(); if(pid2==0) { child(); return 0; } booster::ptime::millisleep(100); s1.open(io::pf_inet); s1.connect(ep); int in_pid1=0; s1.read(io::buffer(&in_pid1,sizeof(int))); s1.close(); s1.open(io::pf_inet); s1.connect(ep); int in_pid2=0; s1.read(io::buffer(&in_pid2,sizeof(int))); s1.close(); TEST((in_pid1==pid1 && in_pid2==pid2) || (in_pid1==pid2 && in_pid2==pid1)); } catch(std::exception const &e) { std::cerr << e.what() << std::endl; if(pid1!=0) { kill(pid1,SIGKILL); int r; wait(&r); } if(pid2!=0) { kill(pid2,SIGKILL); int r; wait(&r); } return 1; } if(pid1!=0 && pid2!=0) { int r1=0,r2=0; ::wait(&r1); ::wait(&r2); if( WIFEXITED(r1) && WEXITSTATUS(r1)==0 && WIFEXITED(r2) && WEXITSTATUS(r2)==0) { std::cerr << "Ok" <<std::endl; return 0; } return 1; } return 0; }
NS_IMETHODIMP PostMessageEvent::Run() { MOZ_ASSERT(mTargetWindow->IsOuterWindow(), "should have been passed an outer window!"); MOZ_ASSERT(!mSource || mSource->IsOuterWindow(), "should have been passed an outer window!"); AutoJSAPI jsapi; jsapi.Init(); JSContext* cx = jsapi.cx(); // The document is just used for the principal mismatch error message below. // Use a stack variable so mSourceDocument is not held onto after this method // finishes, regardless of the method outcome. nsCOMPtr<nsIDocument> sourceDocument; sourceDocument.swap(mSourceDocument); // If we bailed before this point we're going to leak mMessage, but // that's probably better than crashing. RefPtr<nsGlobalWindow> targetWindow; if (mTargetWindow->IsClosedOrClosing() || !(targetWindow = mTargetWindow->GetCurrentInnerWindowInternal()) || targetWindow->IsClosedOrClosing()) return NS_OK; MOZ_ASSERT(targetWindow->IsInnerWindow(), "we ordered an inner window!"); JSAutoCompartment ac(cx, targetWindow->GetWrapperPreserveColor()); // Ensure that any origin which might have been provided is the origin of this // window's document. Note that we do this *now* instead of when postMessage // is called because the target window might have been navigated to a // different location between then and now. If this check happened when // postMessage was called, it would be fairly easy for a malicious webpage to // intercept messages intended for another site by carefully timing navigation // of the target window so it changed location after postMessage but before // now. if (mProvidedPrincipal) { // Get the target's origin either from its principal or, in the case the // principal doesn't carry a URI (e.g. the system principal), the target's // document. nsIPrincipal* targetPrin = targetWindow->GetPrincipal(); if (NS_WARN_IF(!targetPrin)) return NS_OK; // Note: This is contrary to the spec with respect to file: URLs, which // the spec groups into a single origin, but given we intentionally // don't do that in other places it seems better to hold the line for // now. Long-term, we want HTML5 to address this so that we can // be compliant while being safer. if (!targetPrin->Equals(mProvidedPrincipal)) { nsAutoString providedOrigin, targetOrigin; nsresult rv = nsContentUtils::GetUTFOrigin(targetPrin, targetOrigin); NS_ENSURE_SUCCESS(rv, rv); rv = nsContentUtils::GetUTFOrigin(mProvidedPrincipal, providedOrigin); NS_ENSURE_SUCCESS(rv, rv); const char16_t* params[] = { providedOrigin.get(), targetOrigin.get() }; nsContentUtils::ReportToConsole(nsIScriptError::errorFlag, NS_LITERAL_CSTRING("DOM Window"), sourceDocument, nsContentUtils::eDOM_PROPERTIES, "TargetPrincipalDoesNotMatch", params, ArrayLength(params)); return NS_OK; } } ErrorResult rv; JS::Rooted<JS::Value> messageData(cx); nsCOMPtr<nsPIDOMWindowInner> window = targetWindow->AsInner(); Read(window, cx, &messageData, rv); if (NS_WARN_IF(rv.Failed())) { return rv.StealNSResult(); } // Create the event nsCOMPtr<mozilla::dom::EventTarget> eventTarget = do_QueryObject(targetWindow); RefPtr<MessageEvent> event = new MessageEvent(eventTarget, nullptr, nullptr); Nullable<WindowProxyOrMessagePort> source; source.SetValue().SetAsWindowProxy() = mSource ? mSource->AsOuter() : nullptr; event->InitMessageEvent(nullptr, NS_LITERAL_STRING("message"), false /*non-bubbling */, false /*cancelable */, messageData, mCallerOrigin, EmptyString(), source, nullptr); nsTArray<RefPtr<MessagePort>> ports = TakeTransferredPorts(); event->SetPorts(new MessagePortList(static_cast<dom::Event*>(event.get()), ports)); // We can't simply call dispatchEvent on the window because doing so ends // up flipping the trusted bit on the event, and we don't want that to // happen because then untrusted content can call postMessage on a chrome // window if it can get a reference to it. nsIPresShell *shell = targetWindow->GetExtantDoc()->GetShell(); RefPtr<nsPresContext> presContext; if (shell) presContext = shell->GetPresContext(); event->SetTrusted(mTrustedCaller); WidgetEvent* internalEvent = event->WidgetEventPtr(); nsEventStatus status = nsEventStatus_eIgnore; EventDispatcher::Dispatch(window, presContext, internalEvent, static_cast<dom::Event*>(event.get()), &status); return NS_OK; }
bool ExposedPropertiesOnly::check(JSContext *cx, HandleObject wrapper, HandleId id, Wrapper::Action act) { RootedObject wrappedObject(cx, Wrapper::wrappedObject(wrapper)); if (act == Wrapper::CALL) return true; // For the case of getting a property descriptor, we allow if either GET or SET // is allowed, and rely on FilteringWrapper to filter out any disallowed accessors. if (act == Wrapper::GET_PROPERTY_DESCRIPTOR) { return check(cx, wrapper, id, Wrapper::GET) || check(cx, wrapper, id, Wrapper::SET); } RootedId exposedPropsId(cx, GetRTIdByIndex(cx, XPCJSRuntime::IDX_EXPOSEDPROPS)); // We need to enter the wrappee's compartment to look at __exposedProps__, // but we want to be in the wrapper's compartment if we call Deny(). // // Unfortunately, |cx| can be in either compartment when we call ::check. :-( JSAutoCompartment ac(cx, wrappedObject); bool found = false; if (!JS_HasPropertyById(cx, wrappedObject, exposedPropsId, &found)) return false; // Always permit access to "length" and indexed properties of arrays. if ((JS_IsArrayObject(cx, wrappedObject) || JS_IsTypedArrayObject(wrappedObject)) && ((JSID_IS_INT(id) && JSID_TO_INT(id) >= 0) || (JSID_IS_STRING(id) && JS_FlatStringEqualsAscii(JSID_TO_FLAT_STRING(id), "length")))) { return true; // Allow } // If no __exposedProps__ existed, deny access. if (!found) { return false; } if (id == JSID_VOID) return true; RootedValue exposedProps(cx); if (!JS_LookupPropertyById(cx, wrappedObject, exposedPropsId, &exposedProps)) return false; if (exposedProps.isNullOrUndefined()) return false; if (!exposedProps.isObject()) { EnterAndThrow(cx, wrapper, "__exposedProps__ must be undefined, null, or an Object"); return false; } RootedObject hallpass(cx, &exposedProps.toObject()); if (!AccessCheck::subsumes(js::UncheckedUnwrap(hallpass), wrappedObject)) { EnterAndThrow(cx, wrapper, "Invalid __exposedProps__"); return false; } Access access = NO_ACCESS; Rooted<JSPropertyDescriptor> desc(cx); if (!JS_GetPropertyDescriptorById(cx, hallpass, id, &desc)) { return false; // Error } if (!desc.object() || !desc.isEnumerable()) return false; if (!desc.value().isString()) { EnterAndThrow(cx, wrapper, "property must be a string"); return false; } JSFlatString *flat = JS_FlattenString(cx, desc.value().toString()); if (!flat) return false; size_t length = JS_GetStringLength(JS_FORGET_STRING_FLATNESS(flat)); for (size_t i = 0; i < length; ++i) { char16_t ch = JS_GetFlatStringCharAt(flat, i); switch (ch) { case 'r': if (access & READ) { EnterAndThrow(cx, wrapper, "duplicate 'readable' property flag"); return false; } access = Access(access | READ); break; case 'w': if (access & WRITE) { EnterAndThrow(cx, wrapper, "duplicate 'writable' property flag"); return false; } access = Access(access | WRITE); break; default: EnterAndThrow(cx, wrapper, "properties can only be readable or read and writable"); return false; } } if (access == NO_ACCESS) { EnterAndThrow(cx, wrapper, "specified properties must have a permission bit set"); return false; } if ((act == Wrapper::SET && !(access & WRITE)) || (act != Wrapper::SET && !(access & READ))) { return false; } return true; }
static void Validate() { SkAutoMutexAcquire ac(get_block_mutex()); InMutexValidate(); }
void Chaser::UnitFinished(int unit){ const UnitDef* ud = G->cb->GetUnitDef(unit); if(ud == 0){ G->L->print("UnitDef call filed, was this unit blown up as soon as it was created?"); return; } Command Cmd; if(ud->weapons.empty() == false){ if(ud->weapons.front().def->stockpile == true){ Cmd.id = CMD_STOCKPILE; for(int i = 0;i<110;i++){ G->cb->GiveOrder(unit, &Cmd); } sweap.insert(unit); } } vector<string> v; v = bds::set_cont(v, "CORKROG, CORPYRO, CORSUMO, CORHRK, TLLAAK, TLLPBOT, TLLPRIVATE, ARMZEUS, ARMFIDO, ARMMAV, ARMPW, ARMJETH, ARMHAM, TLLLASBOT, TLLARTYBOT, CORBATS, CORCRUS, CORSHARK, CORSSUB, CORMSHIP, CORSUB, CORROY, CORGOL, CORSENT, CORRAID, CORAK, CORTHUD, CORMIST, CORLEVLR, CORSEAL, CORCAN, CORMORT, CORSTORM, CORCRASH"); bool atk = false; for(vector<string>::iterator vi = v.begin(); vi != v.end();++vi){ if(*vi == ud->name){ atk = true; break; } } if(atk == true){ Command* c = new Command; c->id = CMD_MOVE_STATE; c->params.push_back(3); G->cb->GiveOrder(unit,c); Command* c2 = new Command; c2->id = CMD_TRAJECTORY; c2->params.push_back(3); G->cb->GiveOrder(unit,c); Add(unit); string mess = "new attacker added :"; mess += ud->name.c_str(); G->L->print(mess.c_str()); acknum++; if(acknum>threshold){ bool idled = false; if((groups.empty() == false)&&(groups.back().gid != groups.front().gid)){ for(vector<ackforce>::iterator ad = groups.begin();ad != groups.end();++ad){ if(ad->idle){ ad->acknum += acknum; for(set<int>::iterator acf = Attackers.begin();acf != Attackers.end();++acf){ ad->units.insert(*acf); } idled = true; Attackers.clear(); acknum = 0; FindTarget(&*ad); break; } } } if(idled == false){ ackforce ac(G); ac.acknum = this->acknum; forces++; ac.gid = forces; ac.idle = true; ac.units = Attackers; groups.push_back(ac); Attackers.clear(); acknum = 0; FindTarget(&groups.back()); } } else { Attackers.insert(unit); } } }
int main (int argc, char **argv) { ros::init(argc, argv, "test_tray_pickup"); // create the action client // true causes the client to spin its own thread actionlib::SimpleActionClient<tray_pick_place::TrayPickPlaceAction> ac("tray_pick_place", true); ROS_INFO("Waiting for action server to start."); // wait for the action server to start ac.waitForServer(); //will wait for infinite time ROS_INFO("Action server started, sending goal."); // send a goal to the action tray_pick_place::TrayPickPlaceGoal goal; uint8_t action; uint8_t arm; uint8_t slot; double height = 0.0; // parse command line arguments if (argc == 4) { action = atoi(argv[1]); arm = atoi(argv[2]); slot = atoi(argv[3]); // slot number } else if (argc == 5) { action = atoi(argv[1]); arm = atoi(argv[2]); slot = atoi(argv[3]); // slot number height = atof(argv[4]); } else // default values { action = tray_pick_place::TrayPickPlaceGoal::PICK_SIDE; arm = tray_pick_place::TrayPickPlaceGoal::LEFT_ARM; slot = tray_pick_place::TrayPickPlaceGoal::MIDDLE_SLOT; } ROS_INFO("action: %d, arm: %s, slot: %d", action, arm ? "left" : "right", slot); goal.action = action; goal.arm = arm; goal.slot = slot; goal.bbox_dims.z = height; goal.use_place_pose = false; goal.place_pose.pose.orientation.x = 0.0; goal.place_pose.pose.orientation.y = 0.0; goal.place_pose.pose.orientation.z = 0.0; goal.place_pose.pose.orientation.w = 1.0; ac.sendGoal(goal); //wait for the action to return bool finished_before_timeout = ac.waitForResult(ros::Duration(20.0)); if (finished_before_timeout) { actionlib::SimpleClientGoalState state = ac.getState(); ROS_INFO("Action finished: %s",state.toString().c_str()); } else ROS_INFO("Action did not finish before the time out."); //exit return 0; }
void ResStarlingAtlas::loadAtlas(CreateResourceContext& context) { std::string xml_path = context.walker.getPath("file"); file::buffer fb; file::read(xml_path.c_str(), fb); pugi::xml_document doc; doc.load_buffer_inplace(&fb.data[0], fb.data.size()); pugi::xml_node starling_xml = doc.first_child(); pugi::xml_node root = doc.root().first_child(); const std::string& img = root.attribute("imagePath").as_string(); char head[255]; char tail[255]; path::split(xml_path.c_str(), head, tail); _imagePath = std::string(head) + img; _texture = IVideoDriver::instance->createTexture(); pugi::xml_node meta = context.walker.getMeta(); if (!meta.empty()) { int textureWidth = meta.attribute("tw").as_int(); int textureHeight = meta.attribute("th").as_int(); _texture->init(0, textureWidth, textureHeight, TF_R8G8B8A8); } else { unsigned char buff[64]; unsigned int size = 0; { file::autoClose ac(file::open(_imagePath.c_str(), "rb")); size = file::read(ac.getHandle(), buff, sizeof(buff)); } int width = 0; int height = 0; ImageType type; if (getImageInfo(buff, size, img.c_str(), type, width, height)) { _texture->init(0, width, height, TF_R8G8B8A8); } else { spMemoryTexture mt = new MemoryTexture; ImageData im; file::buffer bf; file::read(_imagePath.c_str(), bf); mt->init(bf, true, _texture->getFormat()); im = mt->lock(); _texture->init(mt->lock(), false); } } float iw = 1.0f / _texture->getWidth(); float ih = 1.0f / _texture->getHeight(); ResAnim* resAnim = 0; pugi::xml_node sub = starling_xml.first_child(); animationFrames frames; while (sub) { const char* name = sub.attribute("name").value(); char id[255]; strcpy(id, name); //int frame_index = atoi(index); //todo optimize attributes int x = sub.attribute("x").as_int(); int y = sub.attribute("y").as_int(); int width = sub.attribute("width").as_int(); int height = sub.attribute("height").as_int(); int frameX = sub.attribute("frameX").as_int(); int frameY = sub.attribute("frameY").as_int(); int frameWidth = sub.attribute("frameWidth").as_int(width); int frameHeight = sub.attribute("frameHeight").as_int(height); if (!resAnim || resAnim->getName() != id) { if (resAnim) { resAnim->init(frames, (int)frames.size()); resAnim->setParent(this); context.resources->add(resAnim); frames.clear(); } resAnim = new ResAnim(this); setNode(resAnim, context.walker.getNode()); resAnim->setName(id); } AnimationFrame frame; RectF srcRect(x * iw, y * ih, width * iw, height * ih); RectF destF = Rect(-frameX, -frameY, width, height).cast<RectF>(); Diffuse df; df.base = _texture; frame.init(resAnim, df, srcRect, destF, Vector2((float)frameWidth, (float)frameHeight)); frames.push_back(frame); sub = sub.next_sibling(); } if (resAnim) { resAnim->init(frames, (int)frames.size()); resAnim->setParent(this); context.resources->add(resAnim); } }
DptfBuffer ActiveRelationshipTable::toArtBinary() const { esif_data_variant revisionField; revisionField.integer.type = esif_data_type::ESIF_DATA_UINT64; revisionField.integer.value = 1; DptfBuffer packages; UInt32 offset = 0; for (auto entry = m_entries.begin(); entry != m_entries.end(); entry++) { auto artEntry = std::dynamic_pointer_cast<ActiveRelationshipTableEntry>(*entry); if (artEntry) { UInt32 sourceScopeLength = (UInt32)(*entry)->getSourceDeviceScope().size(); UInt32 targetScopeLength = (UInt32)(*entry)->getTargetDeviceScope().size(); DptfBuffer packageBuffer; packageBuffer.allocate(sizeof(EsifDataBinaryArtPackage) + sourceScopeLength + targetScopeLength); EsifDataBinaryArtPackage entryPackage; UInt32 dataAddress = 0; // Source Scope entryPackage.sourceDevice.string.length = sourceScopeLength; entryPackage.sourceDevice.type = esif_data_type::ESIF_DATA_STRING; packageBuffer.put(dataAddress, (UInt8*)(&(entryPackage.sourceDevice)), sizeof(entryPackage.sourceDevice)); dataAddress += sizeof(entryPackage.sourceDevice); packageBuffer.put(dataAddress, (UInt8*)((*entry)->getSourceDeviceScope().c_str()), sourceScopeLength); dataAddress += sourceScopeLength; // Target Scope entryPackage.targetDevice.string.length = targetScopeLength; entryPackage.targetDevice.type = esif_data_type::ESIF_DATA_STRING; packageBuffer.put(dataAddress, (UInt8*)(&(entryPackage.targetDevice)), sizeof(entryPackage.targetDevice)); dataAddress += sizeof(entryPackage.targetDevice); packageBuffer.put(dataAddress, (UInt8*)((*entry)->getTargetDeviceScope().c_str()), targetScopeLength); dataAddress += targetScopeLength; // Weight entryPackage.weight.integer.type = esif_data_type::ESIF_DATA_UINT64; entryPackage.weight.integer.value = artEntry->getWeight(); packageBuffer.put(dataAddress, (UInt8*)(&(entryPackage.weight)), sizeof(entryPackage.weight)); dataAddress += sizeof(entryPackage.weight); // AC0 entryPackage.ac0MaxFanSpeed.integer.type = esif_data_type::ESIF_DATA_UINT64; entryPackage.ac0MaxFanSpeed.integer.value = artEntry->ac(0); packageBuffer.put(dataAddress, (UInt8*)(&(entryPackage.ac0MaxFanSpeed)), sizeof(entryPackage.ac0MaxFanSpeed)); dataAddress += sizeof(entryPackage.ac0MaxFanSpeed); // AC1 entryPackage.ac1MaxFanSpeed.integer.type = esif_data_type::ESIF_DATA_UINT64; entryPackage.ac1MaxFanSpeed.integer.value = artEntry->ac(1); packageBuffer.put(dataAddress, (UInt8*)(&(entryPackage.ac1MaxFanSpeed)), sizeof(entryPackage.ac1MaxFanSpeed)); dataAddress += sizeof(entryPackage.ac1MaxFanSpeed); // AC2 entryPackage.ac2MaxFanSpeed.integer.type = esif_data_type::ESIF_DATA_UINT64; entryPackage.ac2MaxFanSpeed.integer.value = artEntry->ac(2); packageBuffer.put(dataAddress, (UInt8*)(&(entryPackage.ac2MaxFanSpeed)), sizeof(entryPackage.ac2MaxFanSpeed)); dataAddress += sizeof(entryPackage.ac2MaxFanSpeed); // AC3 entryPackage.ac3MaxFanSpeed.integer.type = esif_data_type::ESIF_DATA_UINT64; entryPackage.ac3MaxFanSpeed.integer.value = artEntry->ac(3); packageBuffer.put(dataAddress, (UInt8*)(&(entryPackage.ac3MaxFanSpeed)), sizeof(entryPackage.ac3MaxFanSpeed)); dataAddress += sizeof(entryPackage.ac3MaxFanSpeed); // AC4 entryPackage.ac4MaxFanSpeed.integer.type = esif_data_type::ESIF_DATA_UINT64; entryPackage.ac4MaxFanSpeed.integer.value = artEntry->ac(4); packageBuffer.put(dataAddress, (UInt8*)(&(entryPackage.ac4MaxFanSpeed)), sizeof(entryPackage.ac4MaxFanSpeed)); dataAddress += sizeof(entryPackage.ac4MaxFanSpeed); // AC5 entryPackage.ac5MaxFanSpeed.integer.type = esif_data_type::ESIF_DATA_UINT64; entryPackage.ac5MaxFanSpeed.integer.value = artEntry->ac(5); packageBuffer.put(dataAddress, (UInt8*)(&(entryPackage.ac5MaxFanSpeed)), sizeof(entryPackage.ac5MaxFanSpeed)); dataAddress += sizeof(entryPackage.ac5MaxFanSpeed); // AC6 entryPackage.ac6MaxFanSpeed.integer.type = esif_data_type::ESIF_DATA_UINT64; entryPackage.ac6MaxFanSpeed.integer.value = artEntry->ac(6); packageBuffer.put(dataAddress, (UInt8*)(&(entryPackage.ac6MaxFanSpeed)), sizeof(entryPackage.ac6MaxFanSpeed)); dataAddress += sizeof(entryPackage.ac6MaxFanSpeed); // AC7 entryPackage.ac7MaxFanSpeed.integer.type = esif_data_type::ESIF_DATA_UINT64; entryPackage.ac7MaxFanSpeed.integer.value = artEntry->ac(7); packageBuffer.put(dataAddress, (UInt8*)(&(entryPackage.ac7MaxFanSpeed)), sizeof(entryPackage.ac7MaxFanSpeed)); dataAddress += sizeof(entryPackage.ac7MaxFanSpeed); // AC8 entryPackage.ac8MaxFanSpeed.integer.type = esif_data_type::ESIF_DATA_UINT64; entryPackage.ac8MaxFanSpeed.integer.value = artEntry->ac(8); packageBuffer.put(dataAddress, (UInt8*)(&(entryPackage.ac8MaxFanSpeed)), sizeof(entryPackage.ac8MaxFanSpeed)); dataAddress += sizeof(entryPackage.ac8MaxFanSpeed); // AC9 entryPackage.ac9MaxFanSpeed.integer.type = esif_data_type::ESIF_DATA_UINT64; entryPackage.ac9MaxFanSpeed.integer.value = artEntry->ac(9); packageBuffer.put(dataAddress, (UInt8*)(&(entryPackage.ac9MaxFanSpeed)), sizeof(entryPackage.ac9MaxFanSpeed)); dataAddress += sizeof(entryPackage.ac9MaxFanSpeed); packages.put(offset, packageBuffer.get(), packageBuffer.size()); offset += packageBuffer.size(); } } UInt32 sizeOfRevision = (UInt32)sizeof(revisionField); DptfBuffer buffer(sizeOfRevision + packages.size()); buffer.put(0, (UInt8*)&revisionField, sizeOfRevision); buffer.put(sizeOfRevision, packages.get(), packages.size()); return buffer; }
void WrapperPromiseCallback::Call(JS::Handle<JS::Value> aValue) { ThreadsafeAutoSafeJSContext cx; JSAutoCompartment ac(cx, mGlobal); JS::Rooted<JS::Value> value(cx, aValue); if (!JS_WrapValue(cx, &value)) { NS_WARNING("Failed to wrap value into the right compartment."); return; } ErrorResult rv; // If invoking callback threw an exception, run resolver's reject with the // thrown exception as argument and the synchronous flag set. JS::Rooted<JS::Value> retValue(cx, mCallback->Call(value, rv, CallbackObject::eRethrowExceptions)); rv.WouldReportJSException(); if (rv.Failed() && rv.IsJSException()) { JS::Rooted<JS::Value> value(cx); rv.StealJSException(cx, &value); if (!JS_WrapValue(cx, &value)) { NS_WARNING("Failed to wrap value into the right compartment."); return; } mNextPromise->RejectInternal(cx, value, Promise::SyncTask); return; } // If the return value is the same as the promise itself, throw TypeError. if (retValue.isObject()) { JS::Rooted<JSObject*> valueObj(cx, &retValue.toObject()); Promise* returnedPromise; nsresult r = UNWRAP_OBJECT(Promise, valueObj, returnedPromise); if (NS_SUCCEEDED(r) && returnedPromise == mNextPromise) { const char* fileName = nullptr; uint32_t lineNumber = 0; // Try to get some information about the callback to report a sane error, // but don't try too hard (only deals with scripted functions). JS::Rooted<JSObject*> unwrapped(cx, js::CheckedUnwrap(mCallback->Callback())); if (unwrapped) { JSAutoCompartment ac(cx, unwrapped); if (JS_ObjectIsFunction(cx, unwrapped)) { JS::Rooted<JS::Value> asValue(cx, JS::ObjectValue(*unwrapped)); JS::Rooted<JSFunction*> func(cx, JS_ValueToFunction(cx, asValue)); MOZ_ASSERT(func); JSScript* script = JS_GetFunctionScript(cx, func); if (script) { fileName = JS_GetScriptFilename(script); lineNumber = JS_GetScriptBaseLineNumber(cx, script); } } } // We're back in aValue's compartment here. JS::Rooted<JSString*> stack(cx, JS_GetEmptyString(JS_GetRuntime(cx))); JS::Rooted<JSString*> fn(cx, JS_NewStringCopyZ(cx, fileName)); if (!fn) { // Out of memory. Promise will stay unresolved. JS_ClearPendingException(cx); return; } JS::Rooted<JSString*> message(cx, JS_NewStringCopyZ(cx, "then() cannot return same Promise that it resolves.")); if (!message) { // Out of memory. Promise will stay unresolved. JS_ClearPendingException(cx); return; } JS::Rooted<JS::Value> typeError(cx); if (!JS::CreateTypeError(cx, stack, fn, lineNumber, 0, nullptr, message, &typeError)) { // Out of memory. Promise will stay unresolved. JS_ClearPendingException(cx); return; } mNextPromise->RejectInternal(cx, typeError, Promise::SyncTask); return; } } // Otherwise, run resolver's resolve with value and the synchronous flag // set. if (!JS_WrapValue(cx, &retValue)) { NS_WARNING("Failed to wrap value into the right compartment."); return; } mNextPromise->ResolveInternal(cx, retValue, Promise::SyncTask); }
int SkGlyphCache_Globals::getCacheCountLimit() const { SkAutoExclusive ac(fLock); return fCacheCountLimit; }
/*static*/ BrowserElementParent::OpenWindowResult BrowserElementParent::DispatchOpenWindowEvent(Element* aOpenerFrameElement, Element* aPopupFrameElement, const nsAString& aURL, const nsAString& aName, const nsAString& aFeatures) { // Dispatch a CustomEvent at aOpenerFrameElement with a detail object // (OpenWindowEventDetail) containing aPopupFrameElement, aURL, aName, and // aFeatures. // Create the event's detail object. OpenWindowEventDetail detail; if (aURL.IsEmpty()) { // URL should never be empty. Assign about:blank as default. detail.mUrl = NS_LITERAL_STRING("about:blank"); } else { detail.mUrl = aURL; } detail.mName = aName; detail.mFeatures = aFeatures; detail.mFrameElement = aPopupFrameElement; AutoJSContext cx; JS::Rooted<JS::Value> val(cx); nsIGlobalObject* sgo = aPopupFrameElement->OwnerDoc()->GetScopeObject(); if (!sgo) { return BrowserElementParent::OPEN_WINDOW_IGNORED; } JS::Rooted<JSObject*> global(cx, sgo->GetGlobalJSObject()); JSAutoCompartment ac(cx, global); if (!ToJSValue(cx, detail, &val)) { MOZ_CRASH("Failed to convert dictionary to JS::Value due to OOM."); return BrowserElementParent::OPEN_WINDOW_IGNORED; } // Do not dispatch a mozbrowseropenwindow event of a widget to its embedder nsCOMPtr<nsIMozBrowserFrame> browserFrame = do_QueryInterface(aOpenerFrameElement); if (browserFrame && browserFrame->GetReallyIsWidget()) { return BrowserElementParent::OPEN_WINDOW_CANCELLED; } nsEventStatus status = nsEventStatus_eIgnore; bool dispatchSucceeded = DispatchCustomDOMEvent(aOpenerFrameElement, NS_LITERAL_STRING("mozbrowseropenwindow"), cx, val, &status); if (dispatchSucceeded) { if (aPopupFrameElement->IsInUncomposedDoc()) { return BrowserElementParent::OPEN_WINDOW_ADDED; } else if (status == nsEventStatus_eConsumeNoDefault) { // If the frame was not added to a document, report to callers whether // preventDefault was called on or not return BrowserElementParent::OPEN_WINDOW_CANCELLED; } } return BrowserElementParent::OPEN_WINDOW_IGNORED; }
void SkGlyphCache_Globals::purgeAll() { SkAutoExclusive ac(fLock); this->internalPurge(fTotalMemoryUsed); }
bool Edge3D::intercept(const Point3D &p1, const Point3D &p2) const { double min, max, pmin, pmax; //if the bounding boxes of the two edges do not intercept, then // the two edges do not intercept Point3D *tp1 = (Point3D *)this->getP1(); Point3D *tp2 = (Point3D *)this->getP2(); if (tp1->getX() > tp2->getX()) { min = tp2->getX(); max = tp1->getX(); } else { min = tp1->getX(); max = tp2->getX(); } if (p1.getX() > p2.getX()) { pmin = p2.getX(); pmax = p1.getX(); } else { pmin = p1.getX(); pmax = p2.getX(); } if ((min > pmax) || (max < pmin)) { return false; } if (tp1->getY() > tp2->getY()) { min = tp2->getY(); max = tp1->getY(); } else { min = tp1->getY(); max = tp2->getY(); } if (p1.getY() > p2.getY()) { pmin = p2.getY(); pmax = p1.getY(); } else { pmin = p1.getY(); pmax = p2.getY(); } if ((min > pmax) || (max < pmin)) { return false; } Vector3D ab(this->vector()); Vector3D ac(*tp1, p1); Vector3D ad(*tp1, p2); Vector3D cd(p1, p2); Vector3D ca(p1, *tp1); Vector3D cb(p1, *tp2); return ( (ab.cross(ac).getX() * ab.cross(ad).getX() + ab.cross(ac).getY() * ab.cross(ad).getY() + ab.cross(ac).getZ() * ab.cross(ad).getZ() < 0.0) && (cd.cross(ca).getX() * cd.cross(cb).getX() + cd.cross(ca).getY() * cd.cross(cb).getY() + cd.cross(ca).getZ() * cd.cross(cb).getZ() < 0.0) ); }
JSObject * WrapperFactory::PrepareForWrapping(JSContext *cx, JSObject *scope, JSObject *obj, unsigned flags) { // Outerize any raw inner objects at the entry point here, so that we don't // have to worry about them for the rest of the wrapping code. if (js::IsInnerObject(obj)) { JSAutoCompartment ac(cx, obj); obj = JS_ObjectToOuterObject(cx, obj); NS_ENSURE_TRUE(obj, nullptr); // The outerization hook wraps, which means that we can end up with a // CCW here if |obj| was a navigated-away-from inner. Strip any CCWs. obj = js::UnwrapObject(obj); MOZ_ASSERT(js::IsOuterObject(obj)); } // If we've got an outer window, there's nothing special that needs to be // done here, and we can move on to the next phase of wrapping. We handle // this case first to allow us to assert against wrappers below. if (js::IsOuterObject(obj)) return DoubleWrap(cx, obj, flags); // Here are the rules for wrapping: // We should never get a proxy here (the JS engine unwraps those for us). MOZ_ASSERT(!IsWrapper(obj)); // As soon as an object is wrapped in a security wrapper, it morphs to be // a fat wrapper. (see also: bug XXX). if (IS_SLIM_WRAPPER(obj) && !MorphSlimWrapper(cx, obj)) return nullptr; // Now, our object is ready to be wrapped, but several objects (notably // nsJSIIDs) have a wrapper per scope. If we are about to wrap one of // those objects in a security wrapper, then we need to hand back the // wrapper for the new scope instead. Also, global objects don't move // between scopes so for those we also want to return the wrapper. So... if (!IS_WN_WRAPPER(obj) || !js::GetObjectParent(obj)) return DoubleWrap(cx, obj, flags); XPCWrappedNative *wn = static_cast<XPCWrappedNative *>(xpc_GetJSPrivate(obj)); JSAutoCompartment ac(cx, obj); XPCCallContext ccx(JS_CALLER, cx, obj); { if (NATIVE_HAS_FLAG(&ccx, WantPreCreate)) { // We have a precreate hook. This object might enforce that we only // ever create JS object for it. // Note: this penalizes objects that only have one wrapper, but are // being accessed across compartments. We would really prefer to // replace the above code with a test that says "do you only have one // wrapper?" JSObject *originalScope = scope; nsresult rv = wn->GetScriptableInfo()->GetCallback()-> PreCreate(wn->Native(), cx, scope, &scope); NS_ENSURE_SUCCESS(rv, DoubleWrap(cx, obj, flags)); // If the handed back scope differs from the passed-in scope and is in // a separate compartment, then this object is explicitly requesting // that we don't create a second JS object for it: create a security // wrapper. if (js::GetObjectCompartment(originalScope) != js::GetObjectCompartment(scope)) return DoubleWrap(cx, obj, flags); JSObject *currentScope = JS_GetGlobalForObject(cx, obj); if (MOZ_UNLIKELY(scope != currentScope)) { // The wrapper claims it wants to be in the new scope, but // currently has a reflection that lives in the old scope. This // can mean one of two things, both of which are rare: // // 1 - The object has a PreCreate hook (we checked for it above), // but is deciding to request one-wrapper-per-scope (rather than // one-wrapper-per-native) for some reason. Usually, a PreCreate // hook indicates one-wrapper-per-native. In this case we want to // make a new wrapper in the new scope. // // 2 - We're midway through wrapper reparenting. The document has // moved to a new scope, but |wn| hasn't been moved yet, and // we ended up calling JS_WrapObject() on its JS object. In this // case, we want to return the existing wrapper. // // So we do a trick: call PreCreate _again_, but say that we're // wrapping for the old scope, rather than the new one. If (1) is // the case, then PreCreate will return the scope we pass to it // (the old scope). If (2) is the case, PreCreate will return the // scope of the document (the new scope). JSObject *probe; rv = wn->GetScriptableInfo()->GetCallback()-> PreCreate(wn->Native(), cx, currentScope, &probe); // Check for case (2). if (probe != currentScope) { MOZ_ASSERT(probe == scope); return DoubleWrap(cx, obj, flags); } // Ok, must be case (1). Fall through and create a new wrapper. } // Nasty hack for late-breaking bug 781476. This will confuse identity checks, // but it's probably better than any of our alternatives. // // Note: We have to ignore domain here. The JS engine assumes that, given a // compartment c, if c->wrap(x) returns a cross-compartment wrapper at time t0, // it will also return a cross-compartment wrapper for any time t1 > t0 unless // an explicit transplant is performed. In particular, wrapper recomputation // assumes that recomputing a wrapper will always result in a wrapper. // // This doesn't actually pose a security issue, because we'll still compute // the correct (opaque) wrapper for the object below given the security // characteristics of the two compartments. if (!AccessCheck::isChrome(js::GetObjectCompartment(scope)) && AccessCheck::subsumesIgnoringDomain(js::GetObjectCompartment(scope), js::GetObjectCompartment(obj))) { return DoubleWrap(cx, obj, flags); } } } // NB: Passing a holder here inhibits slim wrappers under // WrapNativeToJSVal. nsCOMPtr<nsIXPConnectJSObjectHolder> holder; // This public WrapNativeToJSVal API enters the compartment of 'scope' // so we don't have to. jsval v; nsresult rv = nsXPConnect::FastGetXPConnect()->WrapNativeToJSVal(cx, scope, wn->Native(), nullptr, &NS_GET_IID(nsISupports), false, &v, getter_AddRefs(holder)); if (NS_SUCCEEDED(rv)) { obj = JSVAL_TO_OBJECT(v); NS_ASSERTION(IS_WN_WRAPPER(obj), "bad object"); // Because the underlying native didn't have a PreCreate hook, we had // to a new (or possibly pre-existing) XPCWN in our compartment. // This could be a problem for chrome code that passes XPCOM objects // across compartments, because the effects of QI would disappear across // compartments. // // So whenever we pull an XPCWN across compartments in this manner, we // give the destination object the union of the two native sets. We try // to do this cleverly in the common case to avoid too much overhead. XPCWrappedNative *newwn = static_cast<XPCWrappedNative *>(xpc_GetJSPrivate(obj)); XPCNativeSet *unionSet = XPCNativeSet::GetNewOrUsed(ccx, newwn->GetSet(), wn->GetSet(), false); if (!unionSet) return nullptr; newwn->SetSet(unionSet); } return DoubleWrap(cx, obj, flags); }
TEST(HMWSoln, fromScratch_HKFT) { HMWSoln p; auto sH2O = make_species("H2O(l)", "H:2, O:1", h2oliq_nasa_coeffs); auto sNa = make_species("Na+", "Na:1, E:-1", 0.0, 298.15, -125.5213, 333.15, -125.5213, 1e5); sNa->charge = 1; auto sCl = make_species("Cl-", "Cl:1, E:1", 0.0, 298.15, -52.8716, 333.15, -52.8716, 1e5); sCl->charge = -1; auto sH = make_species("H+", "H:1, E:-1", 0.0, 298.15, 0.0, 333.15, 0.0, 1e5); sH->charge = 1; auto sOH = make_species("OH-", "O:1, H:1, E:1", 0.0, 298.15, -91.523, 333.15, -91.523, 1e5); sOH->charge = -1; for (auto& s : {sH2O, sNa, sCl, sH, sOH}) { p.addSpecies(s); } double h0[] = {-57433, Undef, 0.0, -54977}; double g0[] = {Undef, -31379, 0.0, -37595}; double s0[] = {13.96, 13.56, Undef, -2.56}; double a[][4] = {{0.1839, -228.5, 3.256, -27260}, {0.4032, 480.1, 5.563, -28470}, {0.0, 0.0, 0.0, 0.0}, {0.12527, 7.38, 1.8423, -27821}}; double c[][2] = {{18.18, -29810}, {-4.4, -57140}, {0.0, 0.0}, {4.15, -103460}}; double omega[] = {33060, 145600, 0.0, 172460}; std::unique_ptr<PDSS_Water> ss(new PDSS_Water()); p.installPDSS(0, std::move(ss)); for (size_t k = 0; k < 4; k++) { std::unique_ptr<PDSS_HKFT> ss(new PDSS_HKFT()); if (h0[k] != Undef) { ss->setDeltaH0(h0[k] * toSI("cal/gmol")); } if (g0[k] != Undef) { ss->setDeltaG0(g0[k] * toSI("cal/gmol")); } if (s0[k] != Undef) { ss->setS0(s0[k] * toSI("cal/gmol/K")); } a[k][0] *= toSI("cal/gmol/bar"); a[k][1] *= toSI("cal/gmol"); a[k][2] *= toSI("cal-K/gmol/bar"); a[k][3] *= toSI("cal-K/gmol"); c[k][0] *= toSI("cal/gmol/K"); c[k][1] *= toSI("cal-K/gmol"); ss->set_a(a[k]); ss->set_c(c[k]); ss->setOmega(omega[k] * toSI("cal/gmol")); p.installPDSS(k+1, std::move(ss)); } p.setPitzerTempModel("complex"); p.setA_Debye(-1); p.initThermo(); set_hmw_interactions(p); p.setMolalitiesByName("Na+:6.0954 Cl-:6.0954 H+:2.1628E-9 OH-:1.3977E-6"); p.setState_TP(50 + 273.15, 101325); size_t N = p.nSpecies(); vector_fp mv(N), h(N), mu(N), ac(N), acoeff(N); p.getPartialMolarVolumes(mv.data()); p.getPartialMolarEnthalpies(h.data()); p.getChemPotentials(mu.data()); p.getActivities(ac.data()); p.getActivityCoefficients(acoeff.data()); double mvRef[] = {0.01815224, 0.00157182, 0.01954605, 0.00173137, -0.0020266}; for (size_t k = 0; k < N; k++) { EXPECT_NEAR(mv[k], mvRef[k], 2e-8); } }
static void EnterAndThrowASCII(JSContext* cx, JSObject* wrapper, const char* msg) { JSAutoCompartment ac(cx, wrapper); JS_ReportErrorASCII(cx, "%s", msg); }
MozJSImplScope::MozJSImplScope(MozJSScriptEngine* engine) : _engine(engine), _mr(), _runtime(_mr._runtime), _context(_mr._context), _globalProto(_context), _global(_globalProto.getProto()), _funcs(), _internedStrings(_context), _pendingKill(false), _opId(0), _opCtx(nullptr), _pendingGC(false), _connectState(ConnectState::Not), _status(Status::OK()), _quickExit(false), _generation(0), _binDataProto(_context), _bsonProto(_context), _countDownLatchProto(_context), _cursorProto(_context), _cursorHandleProto(_context), _dbCollectionProto(_context), _dbPointerProto(_context), _dbQueryProto(_context), _dbProto(_context), _dbRefProto(_context), _errorProto(_context), _jsThreadProto(_context), _maxKeyProto(_context), _minKeyProto(_context), _mongolExternalProto(_context), _mongolHelpersProto(_context), _mongolLocalProto(_context), _nativeFunctionProto(_context), _numberIntProto(_context), _numberLongProto(_context), _numberDecimalProto(_context), _objectProto(_context), _oidProto(_context), _regExpProto(_context), _timestampProto(_context) { kCurrentScope = this; // The default is quite low and doesn't seem to directly correlate with // malloc'd bytes. Set it to MAX_INT here and catching things in the // jscustomallocator.cpp JS_SetGCParameter(_runtime, JSGC_MAX_BYTES, 0xffffffff); JS_SetInterruptCallback(_runtime, _interruptCallback); JS_SetGCCallback(_runtime, _gcCallback, this); JS_SetContextPrivate(_context, this); JSAutoRequest ar(_context); JS_SetErrorReporter(_runtime, _reportError); JSAutoCompartment ac(_context, _global); _checkErrorState(JS_InitStandardClasses(_context, _global)); installBSONTypes(); JS_FireOnNewGlobalObject(_context, _global); execSetup(JSFiles::assert); execSetup(JSFiles::types); // install process-specific utilities in the global scope (dependancy: types.js, assert.js) if (_engine->getScopeInitCallback()) _engine->getScopeInitCallback()(*this); // install global utility functions installGlobalUtils(*this); _mongolHelpersProto.install(_global); }