code
stringlengths
4
1.01M
language
stringclasses
2 values
package tpe.exceptions.trycatchfinally; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Point; import de.smits_net.games.framework.board.Board; /** * Spielfeld. */ public class GameBoard extends Board { /** Sprite, das durch das Bild läuft. */ private Professor sprite; /** * Erzeugt ein neues Board. */ public GameBoard() { // neues Spielfeld anlegen super(10, new Dimension(400, 400), Color.BLACK); // Sprite initialisieren sprite = new Professor(this, new Point(300, 200)); } /** * Spielfeld neu zeichnen. Wird vom Framework aufgerufen. */ @Override public void drawGame(Graphics g) { sprite.draw(g, this); } /** * Spielsituation updaten. Wird vom Framework aufgerufen. */ @Override public boolean updateGame() { sprite.move(); return sprite.isVisible(); } }
Java
<?= form_open('', array("class"=>"form-horizontal", "id"=>"frm_menu")); ?> <div class="form-group <?= form_error('title') ? ' error' : ''; ?>"> <label for="title" class="control-label col-sm-2"><?= lang('menus_title'); ?></label> <div class="col-sm-4"> <input type="hidden" id="menuid" name="menuid" value="<?php echo set_value('menuid', isset($data->id) ? $data->id : ''); ?>"> <input type="hidden" id="type" name="type" value="<?= isset($type) ? $type : 'add' ?>"> <input id="title" type="text" name="title" class="form-control" maxlength="100" value="<?php echo set_value('title', isset($data->title) ? $data->title : ''); ?>" /> </div> <div class="col-sm-10 col-sm-offset-2"> <span class="help-inline"><?php echo form_error('title'); ?></span> </div> </div> <div class="form-group <?= form_error('link') ? ' error' : ''; ?>"> <label for="link" class="control-label col-sm-2"><?= lang('menus_link'); ?></label> <div class="col-sm-4"> <input id="link" type="text" name="link" class="form-control" maxlength="255" value="<?php echo set_value('link', isset($data->link) ? $data->link : ''); ?>" /> </div> <div class="col-sm-10 col-sm-offset-2"> <span class="help-inline"><?php echo form_error('link'); ?></span> </div> </div> <div class="form-group <?= form_error('icon') ? ' error' : ''; ?>"> <label for="icon" class="control-label col-sm-2"><?= lang('menus_icon'); ?></label> <div class="col-sm-4"> <input id="icon" type="text" name="icon" class="form-control" maxlength="255" value="<?php echo set_value('icon', isset($data->icon) ? $data->icon : ''); ?>" /> <span>e.g. "fa fa-angle-right"</span> </div> <div class="col-sm-10 col-sm-offset-2"> <span class="help-inline"><?php echo form_error('icon'); ?></span> </div> </div> <div class="form-group <?= form_error('target') ? ' error' : ''; ?>"> <label for="target" class="control-label col-sm-2"><?= lang('menus_target'); ?></label> <div class="col-sm-3"> <select id="target" name="target" class="form-control"> <option value="sametab" <?php echo set_select('target', 'sametab', isset($data->target) && $data->target=="sametab"); ?>>Same Tab</option> <option value="_blank" <?php echo set_select('target', '_blank', isset($data->target) && $data->target=="_blank"); ?>>New Tab</option> </select> </div> <div class="col-sm-10 col-sm-offset-2"> <span class="help-inline"><?php echo form_error('target'); ?></span> </div> </div> <div class="form-group <?= form_error('group_menu') ? ' error' : ''; ?>"> <label for="group_menu" class="control-label col-sm-2"><?= lang('menus_group'); ?></label> <div class="col-sm-3"> <select id="group_menu" name="group_menu" class="form-control"> <?php foreach ($group_menus as $key => $gr) : ?> <option value="<?= $gr->id; ?>" <?= set_select('group_menu', $gr->id, isset($data->group_menu) && $data->group_menu == $gr->id) ?>><?= $gr->group_name ?></option> <?php endforeach; ?> </select> </div> <div class="col-sm-10 col-sm-offset-2"> <span class="help-inline"><?php echo form_error('group_menu'); ?></span> </div> </div> <div class="form-group <?= form_error('parent_id') ? ' error' : ''; ?>"> <label for="parent_id" class="control-label col-sm-2"><?= lang('menus_parent'); ?></label> <div class="col-sm-4"> <select id="parent_id" name="parent_id" class="form-control"> <option value="0">This is parent menu</option> <?php foreach ($parents as $key => $parent) : ?> <option value="<?= $parent->id; ?>" <?= set_select('parent_id', $parent->id, isset($data->parent_id) && $data->parent_id == $parent->id) ?>><?= $parent->title ?></option> <?php endforeach; ?> </select> </div> <div class="col-sm-10 col-sm-offset-2"> <span class="help-inline"><?php echo form_error('parent_id'); ?></span> </div> </div> <div class="form-group <?= form_error('permission_id') ? ' error' : ''; ?>"> <label for="permission_id" class="control-label col-sm-2"><?= lang('menus_permissions'); ?></label> <div class="col-sm-4"> <select id="permission_id" name="permission_id" class="form-control"> <?php foreach ($permissions as $key => $permission) : ?> <option value="<?= $permission->id_permission; ?>" <?= set_select('permission_id', $permission->id_permission, isset($data->permission_id) && $data->permission_id == $permission->id_permission) ?>><?= $permission->nm_permission ?></option> <?php endforeach; ?> </select> </div> <div class="col-sm-10 col-sm-offset-2"> <span class="help-inline"><?php echo form_error('permission_id'); ?></span> </div> </div> <div class="form-group "> <label for="status" class="control-label col-sm-2"><?php echo lang('menus_status'); ?></label> <div class="col-sm-2"> <select name="status" id="status" class="form-control"> <option value="1" <?php echo set_select('status', '1', isset($data->status) && $data->status == 1); ?>><?php echo lang('menus_active'); ?></option> <option value="0" <?php echo set_select('status', '0', isset($data->status) && $data->status == 0); ?>><?php echo lang('menus_inactive'); ?></option> </select> </div> </div> <div class="form-group" style="margin-bottom: 5px;"> <div class="col-sm-offset-2 col-sm-6"> <input type="button" name="save" onclick="save_menu()" class="btn btn-primary btn-flat" value="<?php echo lang('menus_save'); ?>" /> <?php echo lang('menus_or').' ' . "<input type='button' name='btn_cancel' class='btn btn-danger btn-flat' onclick='cancel()' value='".lang('menus_cancel')."' />"; ?> <div id='alert_edit' class='alert-success text-center col-md-5 pull-right' style="padding: 5px;display: none;">Menu saved</div> </div> </div> <?= form_close();?> <script type="text/javascript"> $().ready(function(){ var ns = $('ol.sortable').nestedSortable({ forcePlaceholderSize: true, handle: 'div', helper: 'clone', items: 'li', opacity: .6, placeholder: 'placeholder', revert: 250, tabSize: 20, tolerance: 'pointer', toleranceElement: '> div', maxLevels: 2, isTree: true, startCollapsed: false }); $('.disclose').on('click', function() { $(this).closest('li').toggleClass('mjs-nestedSortable-collapsed').toggleClass('mjs-nestedSortable-expanded'); $(this).toggleClass('ui-icon-plusthick').toggleClass('ui-icon-minusthick'); }); $("#title").focus(); }); //Edit Menu function editmenu(idmenu){ if(idmenu!=""){ var url = 'menus/edit/'+idmenu; $("#frm_menu_head").html("Edit Menu"); $("#form-area").load(siteurl+url); $("#title").focus(); } } function save_order_menu(){ var formdata = $('ol.sortable').nestedSortable('serialize'); token_hash = $("#frm_menu_order [name='ci_csrf_token']").val(); formdata = formdata+'&ci_csrf_token='+token_hash; $.ajax({ url : siteurl+"menus/save_order", data : formdata, dataType : "json", type : "post", success: function(msg){ if(msg['save']==1){ $("#frm_menu_order [name='ci_csrf_token']").val(msg['token']); $("#alert_save").html("Menu order saved"); $("#alert_save").removeClass("alert-danger"); $("#alert_save").removeClass("alert-success"); $("#alert_save").addClass("alert-success"); $("#alert_save").show(); setTimeout(function(){ $("#alert_save").hide(); window.location.reload(); },2000); }else{ $("#frm_menu_order [name='ci_csrf_token']").val(msg['token']); $("#alert_save").html("Menu saving failed"); $("#alert_save").removeClass("alert-danger"); $("#alert_save").removeClass("alert-success"); $("#alert_save").addClass("alert-danger"); $("#alert_save").show(); setTimeout(function(){ $("#alert_save").hide(); },2000); } } }); } //Cancel Edit or Add function cancel(){ $("#menuid").val(""); $("#type").val("add"); $("#title").val(""); $("#link").val(""); $("#icon").val(""); $("#taget").val("sametab"); $("#group_menu").val($("#group_menu option:first").val()); $("#parent_id").val(0); $("#parent_id").prop("disabled",false); $("#permission_id").val($("#permission_id option:first").val()); $("#taget").val(1); $("#frm_menu_head").html("Add New Menu"); } //Save Menu function save_menu(){ var title = $("#title").val().trim(); var formdata = $("#frm_menu").serialize(); if(title!=""){ $.ajax({ url : siteurl+"menus/save_menus_ajax", data : formdata, dataType : "json", type : "post", success: function(msg){ if(msg['save']==1){ $("#frm_menu [name='ci_csrf_token']").val(msg['token']); $("#alert_edit").html("Menu saved"); $("#alert_edit").removeClass("alert-danger"); $("#alert_edit").removeClass("alert-success"); $("#alert_edit").addClass("alert-success"); $("#alert_edit").show(); setTimeout(function(){ $("#alert_edit").hide(); window.location.reload(); //reset form cancel(); },2000); }else{ $("#frm_menu [name='ci_csrf_token']").val(msg['token']); $("#alert_edit").html("Menu saving failed"); $("#alert_edit").removeClass("alert-danger"); $("#alert_edit").removeClass("alert-success"); $("#alert_edit").addClass("alert-danger"); $("#alert_edit").show(); setTimeout(function(){ $("#alert_edit").hide(); },2000); } } }); }else{ $("#alert_edit").html("Title must be filled"); $("#alert_edit").removeClass("alert-danger"); $("#alert_edit").removeClass("alert-success"); $("#alert_edit").addClass("alert-danger"); $("#alert_edit").show(); setTimeout(function(){ $("#alert_edit").hide(); },2000); } } //Delete Menu function delete_menu(id){ var idmenu = id; var token_hash = $("#frm_menu_order [name='ci_csrf_token']").val(); var conf = confirm("Are you sure you want to delete this menu ?"); if(idmenu!=="") { if(conf){ $.ajax({ url : siteurl+"menus/delete", data : ({id: idmenu, ci_csrf_token: token_hash}), type : "post", dataType : "json", success : function(msg){ if(msg['delete']==1) { $("#frm_menu_order [name='ci_csrf_token']").val(msg['token']); $("#alert_save").html("Menu deleted"); $("#alert_save").removeClass("alert-danger"); $("#alert_save").removeClass("alert-success"); $("#alert_save").addClass("alert-success"); $("#alert_save").show(); setTimeout(function(){ $("#alert_save").hide(); window.location.reload(); },2000); }else if(msg['delete']==2){ $("#frm_menu_order [name='ci_csrf_token']").val(msg['token']); $("#alert_save").html("Delete child first"); $("#alert_save").removeClass("alert-danger"); $("#alert_save").removeClass("alert-success"); $("#alert_save").addClass("alert-danger"); $("#alert_save").show(); setTimeout(function(){ $("#alert_save").hide(); },2000); }else{ $("#frm_menu_order [name='ci_csrf_token']").val(msg['token']); $("#alert_save").html("Deletion failed"); $("#alert_save").removeClass("alert-danger"); $("#alert_save").removeClass("alert-success"); $("#alert_save").addClass("alert-danger"); $("#alert_save").show(); setTimeout(function(){ $("#alert_save").hide(); },2000); } } }); } } } </script>
Java
/** * @license Highcharts JS v8.2.2 (2020-10-22) * @module highcharts/modules/funnel3d * @requires highcharts * @requires highcharts/highcharts-3d * @requires highcharts/modules/cylinder * * Highcharts funnel module * * (c) 2010-2019 Kacper Madej * * License: www.highcharts.com/license */ 'use strict'; import '../../Series/Funnel3DSeries.js';
Java
#!/bin/bash # # Postfix (SMTP) # -------------- # # Postfix handles the transmission of email between servers # using the SMTP protocol. It is a Mail Transfer Agent (MTA). # # Postfix listens on port 25 (SMTP) for incoming mail from # other servers on the Internet. It is responsible for very # basic email filtering such as by IP address and greylisting, # it checks that the destination address is valid, rewrites # destinations according to aliases, and passses email on to # another service for local mail delivery. # # The first hop in local mail delivery is to Spamassassin via # LMTP. Spamassassin then passes mail over to Dovecot for # storage in the user's mailbox. # # Postfix also listens on port 587 (SMTP+STARTLS) for # connections from users who can authenticate and then sends # their email out to the outside world. Postfix queries Dovecot # to authenticate users. # # Address validation, alias rewriting, and user authentication # is configured in a separate setup script mail-users.sh # because of the overlap of this part with the Dovecot # configuration. source setup/functions.sh # load our functions source /etc/mailinabox.conf # load global vars # ### Install packages. # Install postfix's packages. # # * `postfix`: The SMTP server. # * `postfix-pcre`: Enables header filtering. # * `postgrey`: A mail policy service that soft-rejects mail the first time # it is received. Spammers don't usually try agian. Legitimate mail # always will. # * `ca-certificates`: A trust store used to squelch postfix warnings about # untrusted opportunistically-encrypted connections. # # postgrey is going to come in via the Mail-in-a-Box PPA, which publishes # a modified version of postgrey that lets senders whitelisted by dnswl.org # pass through without being greylisted. So please note [dnswl's license terms](https://www.dnswl.org/?page_id=9): # > Every user with more than 100’000 queries per day on the public nameserver # > infrastructure and every commercial vendor of dnswl.org data (eg through # > anti-spam solutions) must register with dnswl.org and purchase a subscription. echo "Installing Postfix (SMTP server)..." apt_install postfix postfix-pcre postgrey ca-certificates # ### Basic Settings # Set some basic settings... # # * Have postfix listen on all network interfaces. # * Make outgoing connections on a particular interface (if multihomed) so that SPF passes on the receiving side. # * Set our name (the Debian default seems to be "localhost" but make it our hostname). # * Set the name of the local machine to localhost, which means xxx@localhost is delivered locally, although we don't use it. # * Set the SMTP banner (which must have the hostname first, then anything). tools/editconf.py /etc/postfix/main.cf \ inet_interfaces=all \ smtp_bind_address=$PRIVATE_IP \ smtp_bind_address6=$PRIVATE_IPV6 \ myhostname=$PRIMARY_HOSTNAME\ smtpd_banner="\$myhostname ESMTP Hi, I'm a Mail-in-a-Box (Ubuntu/Postfix; see https://mailinabox.email/)" \ mydestination=localhost # Tweak some queue settings: # * Inform users when their e-mail delivery is delayed more than 3 hours (default is not to warn). # * Stop trying to send an undeliverable e-mail after 2 days (instead of 5), and for bounce messages just try for 1 day. tools/editconf.py /etc/postfix/main.cf \ delay_warning_time=3h \ maximal_queue_lifetime=2d \ bounce_queue_lifetime=1d # ### Outgoing Mail # Enable the 'submission' port 587 smtpd server and tweak its settings. # # * Do not add the OpenDMAC Authentication-Results header. That should only be added # on incoming mail. Omit the OpenDMARC milter by re-setting smtpd_milters to the # OpenDKIM milter only. See dkim.sh. # * Even though we dont allow auth over non-TLS connections (smtpd_tls_auth_only below, and without auth the client cant # send outbound mail), don't allow non-TLS mail submission on this port anyway to prevent accidental misconfiguration. # * Require the best ciphers for incoming connections per http://baldric.net/2013/12/07/tls-ciphers-in-postfix-and-dovecot/. # By putting this setting here we leave opportunistic TLS on incoming mail at default cipher settings (any cipher is better than none). # * Give it a different name in syslog to distinguish it from the port 25 smtpd server. # * Add a new cleanup service specific to the submission service ('authclean') # that filters out privacy-sensitive headers on mail being sent out by # authenticated users. tools/editconf.py /etc/postfix/master.cf -s -w \ "submission=inet n - - - - smtpd -o syslog_name=postfix/submission -o smtpd_milters=inet:127.0.0.1:8891 -o smtpd_tls_security_level=encrypt -o smtpd_tls_ciphers=high -o smtpd_tls_exclude_ciphers=aNULL,DES,3DES,MD5,DES+MD5,RC4 -o smtpd_tls_mandatory_protocols=!SSLv2,!SSLv3 -o cleanup_service_name=authclean" \ "authclean=unix n - - - 0 cleanup -o header_checks=pcre:/etc/postfix/outgoing_mail_header_filters" # Install the `outgoing_mail_header_filters` file required by the new 'authclean' service. cp conf/postfix_outgoing_mail_header_filters /etc/postfix/outgoing_mail_header_filters # Modify the `outgoing_mail_header_filters` file to use the local machine name and ip # on the first received header line. This may help reduce the spam score of email by # removing the 127.0.0.1 reference. sed -i "s/PRIMARY_HOSTNAME/$PRIMARY_HOSTNAME/" /etc/postfix/outgoing_mail_header_filters sed -i "s/PUBLIC_IP/$PUBLIC_IP/" /etc/postfix/outgoing_mail_header_filters # Enable TLS on these and all other connections (i.e. ports 25 *and* 587) and # require TLS before a user is allowed to authenticate. This also makes # opportunistic TLS available on *incoming* mail. # Set stronger DH parameters, which via openssl tend to default to 1024 bits # (see ssl.sh). tools/editconf.py /etc/postfix/main.cf \ smtpd_tls_security_level=may\ smtpd_tls_auth_only=yes \ smtpd_tls_cert_file=$STORAGE_ROOT/ssl/ssl_certificate.pem \ smtpd_tls_key_file=$STORAGE_ROOT/ssl/ssl_private_key.pem \ smtpd_tls_dh1024_param_file=$STORAGE_ROOT/ssl/dh2048.pem \ smtpd_tls_protocols=\!SSLv2,\!SSLv3 \ smtpd_tls_ciphers=medium \ smtpd_tls_exclude_ciphers=aNULL,RC4 \ smtpd_tls_received_header=yes # Prevent non-authenticated users from sending mail that requires being # relayed elsewhere. We don't want to be an "open relay". On outbound # mail, require one of: # # * `permit_sasl_authenticated`: Authenticated users (i.e. on port 587). # * `permit_mynetworks`: Mail that originates locally. # * `reject_unauth_destination`: No one else. (Permits mail whose destination is local and rejects other mail.) tools/editconf.py /etc/postfix/main.cf \ smtpd_relay_restrictions=permit_sasl_authenticated,permit_mynetworks,reject_unauth_destination # ### DANE # When connecting to remote SMTP servers, prefer TLS and use DANE if available. # # Prefering ("opportunistic") TLS means Postfix will use TLS if the remote end # offers it, otherwise it will transmit the message in the clear. Postfix will # accept whatever SSL certificate the remote end provides. Opportunistic TLS # protects against passive easvesdropping (but not man-in-the-middle attacks). # DANE takes this a step further: # # Postfix queries DNS for the TLSA record on the destination MX host. If no TLSA records are found, # then opportunistic TLS is used. Otherwise the server certificate must match the TLSA records # or else the mail bounces. TLSA also requires DNSSEC on the MX host. Postfix doesn't do DNSSEC # itself but assumes the system's nameserver does and reports DNSSEC status. Thus this also # relies on our local bind9 server being present and `smtp_dns_support_level=dnssec`. # # The `smtp_tls_CAfile` is superflous, but it eliminates warnings in the logs about untrusted certs, # which we don't care about seeing because Postfix is doing opportunistic TLS anyway. Better to encrypt, # even if we don't know if it's to the right party, than to not encrypt at all. Instead we'll # now see notices about trusted certs. The CA file is provided by the package `ca-certificates`. tools/editconf.py /etc/postfix/main.cf \ smtp_tls_protocols=\!SSLv2,\!SSLv3 \ smtp_tls_mandatory_protocols=\!SSLv2,\!SSLv3 \ smtp_tls_ciphers=medium \ smtp_tls_exclude_ciphers=aNULL,RC4 \ smtp_tls_security_level=dane \ smtp_dns_support_level=dnssec \ smtp_tls_CAfile=/etc/ssl/certs/ca-certificates.crt \ smtp_tls_loglevel=2 # ### Incoming Mail # Pass any incoming mail over to a local delivery agent. Spamassassin # will act as the LDA agent at first. It is listening on port 10025 # with LMTP. Spamassassin will pass the mail over to Dovecot after. # # In a basic setup we would pass mail directly to Dovecot by setting # virtual_transport to `lmtp:unix:private/dovecot-lmtp`. # tools/editconf.py /etc/postfix/main.cf virtual_transport=lmtp:[127.0.0.1]:10025 # Who can send mail to us? Some basic filters. # # * `reject_non_fqdn_sender`: Reject not-nice-looking return paths. # * `reject_unknown_sender_domain`: Reject return paths with invalid domains. # * `reject_authenticated_sender_login_mismatch`: Reject if mail FROM address does not match the client SASL login # * `reject_rhsbl_sender`: Reject return paths that use blacklisted domains. # * `permit_sasl_authenticated`: Authenticated users (i.e. on port 587) can skip further checks. # * `permit_mynetworks`: Mail that originates locally can skip further checks. # * `reject_rbl_client`: Reject connections from IP addresses blacklisted in zen.spamhaus.org # * `reject_unlisted_recipient`: Although Postfix will reject mail to unknown recipients, it's nicer to reject such mail ahead of greylisting rather than after. # * `check_policy_service`: Apply greylisting using postgrey. # # Notes: #NODOC # permit_dnswl_client can pass through mail from whitelisted IP addresses, which would be good to put before greylisting #NODOC # so these IPs get mail delivered quickly. But when an IP is not listed in the permit_dnswl_client list (i.e. it is not #NODOC # whitelisted) then postfix does a DEFER_IF_REJECT, which results in all "unknown user" sorts of messages turning into #NODOC # "450 4.7.1 Client host rejected: Service unavailable". This is a retry code, so the mail doesn't properly bounce. #NODOC tools/editconf.py /etc/postfix/main.cf \ smtpd_sender_restrictions="reject_non_fqdn_sender,reject_unknown_sender_domain,reject_authenticated_sender_login_mismatch,reject_rhsbl_sender dbl.spamhaus.org" \ smtpd_recipient_restrictions=permit_sasl_authenticated,permit_mynetworks,"reject_rbl_client zen.spamhaus.org",reject_unlisted_recipient,"check_policy_service inet:127.0.0.1:10023" # Postfix connects to Postgrey on the 127.0.0.1 interface specifically. Ensure that # Postgrey listens on the same interface (and not IPv6, for instance). # A lot of legit mail servers try to resend before 300 seconds. # As a matter of fact RFC is not strict about retry timer so postfix and # other MTA have their own intervals. To fix the problem of receiving # e-mails really latter, delay of greylisting has been set to # 180 seconds (default is 300 seconds). tools/editconf.py /etc/default/postgrey \ POSTGREY_OPTS=\"'--inet=127.0.0.1:10023 --delay=180'\" # Increase the message size limit from 10MB to 128MB. # The same limit is specified in nginx.conf for mail submitted via webmail and Z-Push. tools/editconf.py /etc/postfix/main.cf \ message_size_limit=134217728 # Allow the two SMTP ports in the firewall. ufw_allow smtp ufw_allow submission # Restart services restart_service postfix restart_service postgrey
Java
<!DOCTYPE html> <html> <head> <title>onChange / onSelectionChange</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=edge"/> <link rel="stylesheet" type="text/css" href="../../../codebase/fonts/font_roboto/roboto.css"/> <link rel="stylesheet" type="text/css" href="../../../codebase/dhtmlxgrid.css"/> <script src="../../../codebase/dhtmlxgrid.js"></script> <style> #log_here { font-size: 8pt; font-family: Tahoma; width: 500px; height: 120px; border: 1px solid #cecece; padding: 2px 5px; overflow: auto; } </style> <script> var myCombo; var eventIndex = 1; function doOnLoad() { myCombo = new dhtmlXCombo("combo_zone", null, null, "image"); myCombo.setImagePath("../common/flags/"); myCombo.load("../common/data_countries.json"); myCombo.allowFreeText(true); myCombo.attachEvent("onChange", function(value, text){ log("onChange event, value: "+value+", text: "+text); }); myCombo.attachEvent("onSelectionChange", function(){ log("onSelectionChange event"); }); } function log(text) { var t = document.getElementById("log_here"); t.innerHTML += (eventIndex++)+") "+text+"<br>"; t.scrollTop = t.scrollHeight; } </script> </head> <body onload="doOnLoad();"> <h3>onChange / onSelectionChange</h3> <div id="combo_zone" style="width:230px;"></div> <br><br><br><br><br><br><br><br><br><br> <div id="log_here"></div> </body> </html>
Java
#pragma once #include "AudioData.h" #include <string> //2D indexing: column-major order, 0-based: #define IDX2D(row, column) (((column) * rows) + (row)) class ImageToSoundscapeConverter { private: double freq_lowest; double freq_highest; int sample_freq_Hz; double total_time_s; bool use_exponential; bool use_stereo; bool use_delay; bool use_fade; bool use_diffraction; bool use_bspline; float speed_of_sound_m_s; float acoustical_size_of_head_m; int rows; int columns; const uint32_t sampleCount; const uint32_t samplesPerColumn; const float timePerSample_s; const float scale; std::vector<float> omega; std::vector<float> phi0; std::vector<float> waveformCacheLeftChannel; std::vector<float> waveformCacheRightChannel; AudioData audioData; float rnd(void); void initWaveformCacheStereo(); void processMono(const std::vector<float> &image); void processStereo(const std::vector<float> &image); public: ImageToSoundscapeConverter(int rows, int columns, double freq_lowest = 500, double freq_highest = 5000, int sample_freq_Hz = 44100, double total_time_s = 1.05, bool use_exponential = true, bool use_stereo = true, bool use_delay = true, bool use_fade = true, bool use_diffraction = true, bool use_bspline = true, float speed_of_sound_m_s = 340, float acoustical_size_of_head_m = 0.20); void Process(const std::vector<float> &image); AudioData& GetAudioData() { return audioData; } };
Java
--- title: "Proporción de mujeres en edad de procrear (de 15 a 49 años) que practican la planificación familiar con métodos modernos" lang: es permalink: /es/3-7-1/ sdg_goal: 3 layout: indicator indicator: "3.7.1" target_id: "3.7" ---
Java
/* * Copyright 2012 Red Hat, Inc. and/or its affiliates. * * Licensed under the Eclipse Public License version 1.0, available at * http://www.eclipse.org/legal/epl-v10.html */ package test.org.jboss.forge.furnace.lifecycle; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.forge.arquillian.archive.AddonArchive; import org.jboss.forge.arquillian.services.LocalServices; import org.jboss.forge.furnace.Furnace; import org.jboss.forge.furnace.addons.Addon; import org.jboss.forge.furnace.addons.AddonId; import org.jboss.forge.furnace.addons.AddonRegistry; import org.jboss.forge.furnace.repositories.AddonDependencyEntry; import org.jboss.forge.furnace.repositories.MutableAddonRepository; import org.jboss.forge.furnace.util.Addons; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import test.org.jboss.forge.furnace.mocks.MockImpl1; import test.org.jboss.forge.furnace.mocks.MockInterface; @RunWith(Arquillian.class) public class PreShutdownEventTest { @Deployment(order = 2) public static AddonArchive getDeployment() { AddonArchive archive = ShrinkWrap.create(AddonArchive.class) .addAsAddonDependencies( AddonDependencyEntry.create("dep1") ); archive.addAsLocalServices(PreShutdownEventTest.class); return archive; } @Deployment(name = "dep2,2", testable = false, order = 1) public static AddonArchive getDeployment2() { AddonArchive archive = ShrinkWrap.create(AddonArchive.class) .addAsLocalServices(MockImpl1.class) .addClasses(MockImpl1.class, MockInterface.class) .addBeansXML(); return archive; } @Deployment(name = "dep1,1", testable = false, order = 0) public static AddonArchive getDeployment1() { AddonArchive archive = ShrinkWrap.create(AddonArchive.class) .addClass(RecordingEventManager.class) .addAsLocalServices(RecordingEventManager.class); return archive; } @Test(timeout = 5000) public void testPreShutdownIsCalled() throws Exception { Furnace furnace = LocalServices.getFurnace(getClass().getClassLoader()); AddonRegistry registry = furnace.getAddonRegistry(); Addon dep2 = registry.getAddon(AddonId.from("dep2", "2")); RecordingEventManager manager = registry.getServices(RecordingEventManager.class).get(); Assert.assertEquals(3, manager.getPostStartupCount()); MutableAddonRepository repository = (MutableAddonRepository) furnace.getRepositories().get(0); repository.disable(dep2.getId()); Addons.waitUntilStopped(dep2); Assert.assertEquals(1, manager.getPreShutdownCount()); } }
Java
/** * Copyright (c) 2014-2015 openHAB UG (haftungsbeschraenkt) and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.eclipse.smarthome.io.rest.core.link; import java.util.ArrayList; import java.util.Collection; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import javax.ws.rs.core.UriInfo; import org.eclipse.smarthome.core.thing.ChannelUID; import org.eclipse.smarthome.core.thing.link.AbstractLink; import org.eclipse.smarthome.core.thing.link.ItemChannelLink; import org.eclipse.smarthome.core.thing.link.ItemChannelLinkRegistry; import org.eclipse.smarthome.core.thing.link.ThingLinkManager; import org.eclipse.smarthome.core.thing.link.dto.AbstractLinkDTO; import org.eclipse.smarthome.core.thing.link.dto.ItemChannelLinkDTO; import org.eclipse.smarthome.io.rest.JSONResponse; import org.eclipse.smarthome.io.rest.RESTResource; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; /** * This class acts as a REST resource for links. * * @author Dennis Nobel - Initial contribution * @author Yordan Zhelev - Added Swagger annotations * @author Kai Kreuzer - Removed Thing links and added auto link url */ @Path(ItemChannelLinkResource.PATH_LINKS) @Api(value = ItemChannelLinkResource.PATH_LINKS) public class ItemChannelLinkResource implements RESTResource { /** The URI path to this resource */ public static final String PATH_LINKS = "links"; private ItemChannelLinkRegistry itemChannelLinkRegistry; private ThingLinkManager thingLinkManager; @Context UriInfo uriInfo; @GET @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "Gets all available links.", response = ItemChannelLinkDTO.class, responseContainer = "Collection") @ApiResponses(value = { @ApiResponse(code = 200, message = "OK") }) public Response getAll() { Collection<ItemChannelLink> channelLinks = itemChannelLinkRegistry.getAll(); return Response.ok(toBeans(channelLinks)).build(); } @GET @Path("/auto") @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "Tells whether automatic link mode is active or not", response = Boolean.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "OK") }) public Response isAutomatic() { return Response.ok(thingLinkManager.isAutoLinksEnabled()).build(); } @PUT @Path("/{itemName}/{channelUID}") @ApiOperation(value = "Links item to a channel.") @ApiResponses(value = { @ApiResponse(code = 200, message = "OK"), @ApiResponse(code = 400, message = "Item already linked to the channel.") }) public Response link(@PathParam("itemName") @ApiParam(value = "itemName") String itemName, @PathParam("channelUID") @ApiParam(value = "channelUID") String channelUid) { itemChannelLinkRegistry.add(new ItemChannelLink(itemName, new ChannelUID(channelUid))); return Response.ok().build(); } @DELETE @Path("/{itemName}/{channelUID}") @ApiOperation(value = "Unlinks item from a channel.") @ApiResponses(value = { @ApiResponse(code = 200, message = "OK"), @ApiResponse(code = 404, message = "Link not found."), @ApiResponse(code = 405, message = "Link not editable.") }) public Response unlink(@PathParam("itemName") @ApiParam(value = "itemName") String itemName, @PathParam("channelUID") @ApiParam(value = "channelUID") String channelUid) { String linkId = AbstractLink.getIDFor(itemName, new ChannelUID(channelUid)); if (itemChannelLinkRegistry.get(linkId) == null) { String message = "Link " + linkId + " does not exist!"; return JSONResponse.createResponse(Status.NOT_FOUND, null, message); } ItemChannelLink result = itemChannelLinkRegistry .remove(AbstractLink.getIDFor(itemName, new ChannelUID(channelUid))); if (result != null) { return Response.ok().build(); } else { return JSONResponse.createErrorResponse(Status.METHOD_NOT_ALLOWED, "Channel is read-only."); } } protected void setThingLinkManager(ThingLinkManager thingLinkManager) { this.thingLinkManager = thingLinkManager; } protected void unsetThingLinkManager(ThingLinkManager thingLinkManager) { this.thingLinkManager = null; } protected void setItemChannelLinkRegistry(ItemChannelLinkRegistry itemChannelLinkRegistry) { this.itemChannelLinkRegistry = itemChannelLinkRegistry; } protected void unsetItemChannelLinkRegistry(ItemChannelLinkRegistry itemChannelLinkRegistry) { this.itemChannelLinkRegistry = null; } private Collection<AbstractLinkDTO> toBeans(Iterable<ItemChannelLink> links) { Collection<AbstractLinkDTO> beans = new ArrayList<>(); for (AbstractLink link : links) { ItemChannelLinkDTO bean = new ItemChannelLinkDTO(link.getItemName(), link.getUID().toString()); beans.add(bean); } return beans; } }
Java
/******************************************************************************* * Copyright (c) 2017, 2021 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package com.ibm.ws.security.social.fat.LibertyOP; import java.util.ArrayList; import java.util.List; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.runner.RunWith; import com.ibm.websphere.simplicity.log.Log; import com.ibm.ws.security.oauth_oidc.fat.commonTest.RSCommonTestTools; import com.ibm.ws.security.social.fat.LibertyOP.CommonTests.LibertyOPRepeatActions; import com.ibm.ws.security.social.fat.commonTests.Social_BasicTests; import com.ibm.ws.security.social.fat.utils.SocialConstants; import com.ibm.ws.security.social.fat.utils.SocialTestSettings; import componenttest.custom.junit.runner.FATRunner; import componenttest.custom.junit.runner.Mode; import componenttest.custom.junit.runner.Mode.TestMode; import componenttest.rules.repeater.RepeatTests; import componenttest.topology.impl.LibertyServerWrapper; @RunWith(FATRunner.class) @LibertyServerWrapper @Mode(TestMode.FULL) public class LibertyOP_BasicTests_oauth_usingSocialConfig extends Social_BasicTests { public static Class<?> thisClass = LibertyOP_BasicTests_oauth_usingSocialConfig.class; public static RSCommonTestTools rsTools = new RSCommonTestTools(); @ClassRule public static RepeatTests r = RepeatTests.with(LibertyOPRepeatActions.usingUserInfo()).andWith(LibertyOPRepeatActions.usingIntrospect()); @BeforeClass public static void setUp() throws Exception { classOverrideValidationEndpointValue = FATSuite.UserApiEndpoint; List<String> startMsgs = new ArrayList<String>(); startMsgs.add("CWWKT0016I.*" + SocialConstants.SOCIAL_DEFAULT_CONTEXT_ROOT); List<String> extraApps = new ArrayList<String>(); extraApps.add(SocialConstants.HELLOWORLD_SERVLET); // TODO fix List<String> opStartMsgs = new ArrayList<String>(); // opStartMsgs.add("CWWKS1600I.*" + SocialConstants.OIDCCONFIGMEDIATOR_APP); opStartMsgs.add("CWWKS1631I.*"); // TODO fix List<String> opExtraApps = new ArrayList<String>(); opExtraApps.add(SocialConstants.OP_SAMPLE_APP); String[] propagationTokenTypes = rsTools.chooseTokenSettings(SocialConstants.OIDC_OP); String tokenType = propagationTokenTypes[0]; String certType = propagationTokenTypes[1]; Log.info(thisClass, "setupBeforeTest", "inited tokenType to: " + tokenType); socialSettings = new SocialTestSettings(); testSettings = socialSettings; testOPServer = commonSetUp(SocialConstants.SERVER_NAME + ".LibertyOP.op", "op_server_orig.xml", SocialConstants.OIDC_OP, null, SocialConstants.DO_NOT_USE_DERBY, opStartMsgs, null, SocialConstants.OIDC_OP, true, true, tokenType, certType); genericTestServer = commonSetUp(SocialConstants.SERVER_NAME + ".LibertyOP.social", "server_LibertyOP_basicTests_oauth_usingSocialConfig.xml", SocialConstants.GENERIC_SERVER, extraApps, SocialConstants.DO_NOT_USE_DERBY, startMsgs); setActionsForProvider(SocialConstants.LIBERTYOP_PROVIDER, SocialConstants.OAUTH_OP); setGenericVSSpeicificProviderFlags(GenericConfig, "server_LibertyOP_basicTests_oauth_usingSocialConfig"); socialSettings = updateLibertyOPSettings(socialSettings); } }
Java
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vIBM 2.2.3-11/28/2011 06:21 AM(foreman)- // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2014.06.11 at 05:49:00 PM EDT // package com.ibm.jbatch.jsl.model.v2; import javax.annotation.Generated; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for Batchlet complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="Batchlet"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="properties" type="{https://jakarta.ee/xml/ns/jakartaee}Properties" minOccurs="0"/> * &lt;/sequence> * &lt;attribute name="ref" use="required" type="{https://jakarta.ee/xml/ns/jakartaee}artifactRef" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "Batchlet", propOrder = { "properties" }) @Generated(value = "com.ibm.jtc.jax.tools.xjc.Driver", date = "2014-06-11T05:49:00-04:00", comments = "JAXB RI v2.2.3-11/28/2011 06:21 AM(foreman)-") public class Batchlet extends com.ibm.jbatch.jsl.model.Batchlet { @Generated(value = "com.ibm.jtc.jax.tools.xjc.Driver", date = "2014-06-11T05:49:00-04:00", comments = "JAXB RI v2.2.3-11/28/2011 06:21 AM(foreman)-") protected JSLProperties properties; @XmlAttribute(name = "ref", required = true) @Generated(value = "com.ibm.jtc.jax.tools.xjc.Driver", date = "2014-06-11T05:49:00-04:00", comments = "JAXB RI v2.2.3-11/28/2011 06:21 AM(foreman)-") protected String ref; /** {@inheritDoc} */ @Override @Generated(value = "com.ibm.jtc.jax.tools.xjc.Driver", date = "2014-06-11T05:49:00-04:00", comments = "JAXB RI v2.2.3-11/28/2011 06:21 AM(foreman)-") public JSLProperties getProperties() { return properties; } /** {@inheritDoc} */ @Override @Generated(value = "com.ibm.jtc.jax.tools.xjc.Driver", date = "2014-06-11T05:49:00-04:00", comments = "JAXB RI v2.2.3-11/28/2011 06:21 AM(foreman)-") public void setProperties(com.ibm.jbatch.jsl.model.JSLProperties value) { this.properties = (JSLProperties) value; } /** {@inheritDoc} */ @Override @Generated(value = "com.ibm.jtc.jax.tools.xjc.Driver", date = "2014-06-11T05:49:00-04:00", comments = "JAXB RI v2.2.3-11/28/2011 06:21 AM(foreman)-") public String getRef() { return ref; } /** {@inheritDoc} */ @Override @Generated(value = "com.ibm.jtc.jax.tools.xjc.Driver", date = "2014-06-11T05:49:00-04:00", comments = "JAXB RI v2.2.3-11/28/2011 06:21 AM(foreman)-") public void setRef(String value) { this.ref = value; } /** * Copyright 2013 International Business Machines Corp. * * See the NOTICE file distributed with this work for additional information * regarding copyright ownership. 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. */ /* * Appended by build tooling. */ @Override public String toString() { StringBuilder buf = new StringBuilder(100); buf.append("Batchlet: ref=" + ref); buf.append("\n"); buf.append("Properties = " + com.ibm.jbatch.jsl.model.helper.PropertiesToStringHelper.getString(properties)); return buf.toString(); } }
Java
/* * Copyright (c) 2012-2017 Red Hat, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Red Hat, Inc. - initial API and implementation */ package org.eclipse.che.multiuser.machine.authentication.server; import static com.google.common.base.Strings.nullToEmpty; import java.io.IOException; import java.security.Principal; import javax.inject.Inject; import javax.inject.Singleton; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import org.eclipse.che.api.core.NotFoundException; import org.eclipse.che.api.core.ServerException; import org.eclipse.che.api.core.model.user.User; import org.eclipse.che.api.user.server.UserManager; import org.eclipse.che.commons.auth.token.RequestTokenExtractor; import org.eclipse.che.commons.env.EnvironmentContext; import org.eclipse.che.commons.subject.Subject; import org.eclipse.che.commons.subject.SubjectImpl; import org.eclipse.che.multiuser.api.permission.server.AuthorizedSubject; import org.eclipse.che.multiuser.api.permission.server.PermissionChecker; /** @author Max Shaposhnik (mshaposhnik@codenvy.com) */ @Singleton public class MachineLoginFilter implements Filter { @Inject private RequestTokenExtractor tokenExtractor; @Inject private MachineTokenRegistry machineTokenRegistry; @Inject private UserManager userManager; @Inject private PermissionChecker permissionChecker; @Override public void init(FilterConfig filterConfig) throws ServletException {} @Override public void doFilter( ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { final HttpServletRequest httpRequest = (HttpServletRequest) servletRequest; if (httpRequest.getScheme().startsWith("ws") || !nullToEmpty(tokenExtractor.getToken(httpRequest)).startsWith("machine")) { filterChain.doFilter(servletRequest, servletResponse); return; } else { String tokenString; User user; try { tokenString = tokenExtractor.getToken(httpRequest); String userId = machineTokenRegistry.getUserId(tokenString); user = userManager.getById(userId); } catch (NotFoundException | ServerException e) { throw new ServletException("Cannot find user by machine token."); } final Subject subject = new AuthorizedSubject( new SubjectImpl(user.getName(), user.getId(), tokenString, false), permissionChecker); try { EnvironmentContext.getCurrent().setSubject(subject); filterChain.doFilter(addUserInRequest(httpRequest, subject), servletResponse); } finally { EnvironmentContext.reset(); } } } private HttpServletRequest addUserInRequest( final HttpServletRequest httpRequest, final Subject subject) { return new HttpServletRequestWrapper(httpRequest) { @Override public String getRemoteUser() { return subject.getUserName(); } @Override public Principal getUserPrincipal() { return subject::getUserName; } }; } @Override public void destroy() {} }
Java
/******************************************************************************* * Copyright (c) 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package com.ibm.ws.cdi.services.impl; import javax.enterprise.context.Dependent; /** * This class only needs to be here to make sure this is a BDA with a BeanManager */ @Dependent public class MyPojoUser { public String getUser() { String s = "DefaultPojoUser"; return s; } }
Java
/* * 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 javax.faces; import java.lang.reflect.Method; import java.security.AccessController; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.logging.Level; import java.util.logging.Logger; import javax.faces.context.ExternalContext; /** * Provide utility methods used by FactoryFinder class to lookup for SPI interface FactoryFinderProvider. * * @since 2.0.5 */ class _FactoryFinderProviderFactory { public static final String FACTORY_FINDER_PROVIDER_FACTORY_CLASS_NAME = "org.apache.myfaces.spi" + ".FactoryFinderProviderFactory"; public static final String FACTORY_FINDER_PROVIDER_CLASS_NAME = "org.apache.myfaces.spi.FactoryFinderProvider"; public static final String INJECTION_PROVIDER_FACTORY_CLASS_NAME = "org.apache.myfaces.spi.InjectionProviderFactory"; // INJECTION_PROVIDER_CLASS_NAME to provide use of new Injection Provider methods which take a // a class as an input. This is required for CDI 1.2, particularly in regard to constructor injection/ public static final String INJECTION_PROVIDER_CLASS_NAME = "com.ibm.ws.jsf.spi.WASInjectionProvider"; // MANAGED_OBJECT_CLASS_NAME added for CDI 1.2 support. Because CDI now creates the class, inject needs // to return two objects : the instance of the required class and the creational context. To do this // an Managed object is returned from which both of the required objects can be obtained. public static final String MANAGED_OBJECT_CLASS_NAME = "com.ibm.ws.managedobject.ManagedObject"; public static final Class<?> FACTORY_FINDER_PROVIDER_FACTORY_CLASS; public static final Method FACTORY_FINDER_PROVIDER_GET_INSTANCE_METHOD; public static final Method FACTORY_FINDER_PROVIDER_FACTORY_GET_FACTORY_FINDER_METHOD; public static final Class<?> FACTORY_FINDER_PROVIDER_CLASS; public static final Method FACTORY_FINDER_PROVIDER_GET_FACTORY_METHOD; public static final Method FACTORY_FINDER_PROVIDER_SET_FACTORY_METHOD; public static final Method FACTORY_FINDER_PROVIDER_RELEASE_FACTORIES_METHOD; public static final Class<?> INJECTION_PROVIDER_FACTORY_CLASS; public static final Method INJECTION_PROVIDER_FACTORY_GET_INSTANCE_METHOD; public static final Method INJECTION_PROVIDER_FACTORY_GET_INJECTION_PROVIDER_METHOD; public static final Class<?> INJECTION_PROVIDER_CLASS; public static final Method INJECTION_PROVIDER_INJECT_OBJECT_METHOD; public static final Method INJECTION_PROVIDER_INJECT_CLASS_METHOD; public static final Method INJECTION_PROVIDER_POST_CONSTRUCT_METHOD; public static final Method INJECTION_PROVIDER_PRE_DESTROY_METHOD; // New for CDI 1.2 public static final Class<?> MANAGED_OBJECT_CLASS; public static final Method MANAGED_OBJECT_GET_OBJECT_METHOD; public static final Method MANAGED_OBJECT_GET_CONTEXT_DATA_METHOD; static { Class factoryFinderFactoryClass = null; Method factoryFinderproviderFactoryGetMethod = null; Method factoryFinderproviderFactoryGetFactoryFinderMethod = null; Class<?> factoryFinderProviderClass = null; Method factoryFinderProviderGetFactoryMethod = null; Method factoryFinderProviderSetFactoryMethod = null; Method factoryFinderProviderReleaseFactoriesMethod = null; Class injectionProviderFactoryClass = null; Method injectionProviderFactoryGetInstanceMethod = null; Method injectionProviderFactoryGetInjectionProviderMethod = null; Class injectionProviderClass = null; Method injectionProviderInjectObjectMethod = null; Method injectionProviderInjectClassMethod = null; Method injectionProviderPostConstructMethod = null; Method injectionProviderPreDestroyMethod = null; Class managedObjectClass = null; Method managedObjectGetObjectMethod = null; Method managedObjectGetContextDataMethod = null; try { factoryFinderFactoryClass = classForName(FACTORY_FINDER_PROVIDER_FACTORY_CLASS_NAME); if (factoryFinderFactoryClass != null) { factoryFinderproviderFactoryGetMethod = factoryFinderFactoryClass.getMethod ("getInstance", null); factoryFinderproviderFactoryGetFactoryFinderMethod = factoryFinderFactoryClass .getMethod("getFactoryFinderProvider", null); } factoryFinderProviderClass = classForName(FACTORY_FINDER_PROVIDER_CLASS_NAME); if (factoryFinderProviderClass != null) { factoryFinderProviderGetFactoryMethod = factoryFinderProviderClass.getMethod("getFactory", new Class[]{String.class}); factoryFinderProviderSetFactoryMethod = factoryFinderProviderClass.getMethod("setFactory", new Class[]{String.class, String.class}); factoryFinderProviderReleaseFactoriesMethod = factoryFinderProviderClass.getMethod ("releaseFactories", null); } injectionProviderFactoryClass = classForName(INJECTION_PROVIDER_FACTORY_CLASS_NAME); if (injectionProviderFactoryClass != null) { injectionProviderFactoryGetInstanceMethod = injectionProviderFactoryClass. getMethod("getInjectionProviderFactory", null); injectionProviderFactoryGetInjectionProviderMethod = injectionProviderFactoryClass. getMethod("getInjectionProvider", ExternalContext.class); } injectionProviderClass = classForName(INJECTION_PROVIDER_CLASS_NAME); if (injectionProviderClass != null) { injectionProviderInjectObjectMethod = injectionProviderClass. getMethod("inject", Object.class); injectionProviderInjectClassMethod = injectionProviderClass. getMethod("inject", Class.class); injectionProviderPostConstructMethod = injectionProviderClass. getMethod("postConstruct", Object.class, Object.class); injectionProviderPreDestroyMethod = injectionProviderClass. getMethod("preDestroy", Object.class, Object.class); } // get managed object and getObject and getContextData methods for CDI 1.2 support. // getObject() is used to the created object instance // getContextData(Class) is used to get the creational context managedObjectClass = classForName(MANAGED_OBJECT_CLASS_NAME); if (managedObjectClass != null) { managedObjectGetObjectMethod = managedObjectClass.getMethod("getObject", null); managedObjectGetContextDataMethod = managedObjectClass.getMethod("getContextData", Class.class); } } catch (Exception e) { // no op } FACTORY_FINDER_PROVIDER_FACTORY_CLASS = factoryFinderFactoryClass; FACTORY_FINDER_PROVIDER_GET_INSTANCE_METHOD = factoryFinderproviderFactoryGetMethod; FACTORY_FINDER_PROVIDER_FACTORY_GET_FACTORY_FINDER_METHOD = factoryFinderproviderFactoryGetFactoryFinderMethod; FACTORY_FINDER_PROVIDER_CLASS = factoryFinderProviderClass; FACTORY_FINDER_PROVIDER_GET_FACTORY_METHOD = factoryFinderProviderGetFactoryMethod; FACTORY_FINDER_PROVIDER_SET_FACTORY_METHOD = factoryFinderProviderSetFactoryMethod; FACTORY_FINDER_PROVIDER_RELEASE_FACTORIES_METHOD = factoryFinderProviderReleaseFactoriesMethod; INJECTION_PROVIDER_FACTORY_CLASS = injectionProviderFactoryClass; INJECTION_PROVIDER_FACTORY_GET_INSTANCE_METHOD = injectionProviderFactoryGetInstanceMethod; INJECTION_PROVIDER_FACTORY_GET_INJECTION_PROVIDER_METHOD = injectionProviderFactoryGetInjectionProviderMethod; INJECTION_PROVIDER_CLASS = injectionProviderClass; INJECTION_PROVIDER_INJECT_OBJECT_METHOD = injectionProviderInjectObjectMethod; INJECTION_PROVIDER_INJECT_CLASS_METHOD = injectionProviderInjectClassMethod; INJECTION_PROVIDER_POST_CONSTRUCT_METHOD = injectionProviderPostConstructMethod; INJECTION_PROVIDER_PRE_DESTROY_METHOD = injectionProviderPreDestroyMethod; MANAGED_OBJECT_CLASS = managedObjectClass; MANAGED_OBJECT_GET_OBJECT_METHOD = managedObjectGetObjectMethod; MANAGED_OBJECT_GET_CONTEXT_DATA_METHOD = managedObjectGetContextDataMethod; } public static Object getInstance() { if (FACTORY_FINDER_PROVIDER_GET_INSTANCE_METHOD != null) { try { return FACTORY_FINDER_PROVIDER_GET_INSTANCE_METHOD.invoke(FACTORY_FINDER_PROVIDER_FACTORY_CLASS, null); } catch (Exception e) { //No op Logger log = Logger.getLogger(_FactoryFinderProviderFactory.class.getName()); if (log.isLoggable(Level.WARNING)) { log.log(Level.WARNING, "Cannot retrieve current FactoryFinder instance from " + "FactoryFinderProviderFactory." + " Default strategy using thread context class loader will be used.", e); } } } return null; } // ~ Methods Copied from _ClassUtils // ------------------------------------------------------------------------------------ /** * Tries a Class.loadClass with the context class loader of the current thread first and automatically falls back * to * the ClassUtils class loader (i.e. the loader of the myfaces.jar lib) if necessary. * * @param type fully qualified name of a non-primitive non-array class * @return the corresponding Class * @throws NullPointerException if type is null * @throws ClassNotFoundException */ public static Class<?> classForName(String type) throws ClassNotFoundException { if (type == null) { throw new NullPointerException("type"); } try { // Try WebApp ClassLoader first return Class.forName(type, false, // do not initialize for faster startup getContextClassLoader()); } catch (ClassNotFoundException ignore) { // fallback: Try ClassLoader for ClassUtils (i.e. the myfaces.jar lib) return Class.forName(type, false, // do not initialize for faster startup _FactoryFinderProviderFactory.class.getClassLoader()); } } /** * Gets the ClassLoader associated with the current thread. Returns the class loader associated with the specified * default object if no context loader is associated with the current thread. * * @return ClassLoader */ protected static ClassLoader getContextClassLoader() { if (System.getSecurityManager() != null) { try { Object cl = AccessController.doPrivileged(new PrivilegedExceptionAction() { public Object run() throws PrivilegedActionException { return Thread.currentThread().getContextClassLoader(); } }); return (ClassLoader) cl; } catch (PrivilegedActionException pae) { throw new FacesException(pae); } } else { return Thread.currentThread().getContextClassLoader(); } } }
Java
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.http.internal.config; import java.math.BigDecimal; import java.util.HashMap; import java.util.Map; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.Nullable; import org.openhab.binding.http.internal.converter.ColorItemConverter; import org.openhab.core.library.types.IncreaseDecreaseType; import org.openhab.core.library.types.NextPreviousType; import org.openhab.core.library.types.OnOffType; import org.openhab.core.library.types.OpenClosedType; import org.openhab.core.library.types.PlayPauseType; import org.openhab.core.library.types.RewindFastforwardType; import org.openhab.core.library.types.StopMoveType; import org.openhab.core.library.types.UpDownType; import org.openhab.core.types.Command; import org.openhab.core.types.State; /** * The {@link HttpChannelConfig} class contains fields mapping channel configuration parameters. * * @author Jan N. Klug - Initial contribution */ @NonNullByDefault public class HttpChannelConfig { private final Map<String, State> stringStateMap = new HashMap<>(); private final Map<Command, @Nullable String> commandStringMap = new HashMap<>(); private boolean initialized = false; public @Nullable String stateExtension; public @Nullable String commandExtension; public @Nullable String stateTransformation; public @Nullable String commandTransformation; public HttpChannelMode mode = HttpChannelMode.READWRITE; // switch, dimmer, color public @Nullable String onValue; public @Nullable String offValue; // dimmer, color public BigDecimal step = BigDecimal.ONE; public @Nullable String increaseValue; public @Nullable String decreaseValue; // color public ColorItemConverter.ColorMode colorMode = ColorItemConverter.ColorMode.RGB; // contact public @Nullable String openValue; public @Nullable String closedValue; // rollershutter public @Nullable String upValue; public @Nullable String downValue; public @Nullable String stopValue; public @Nullable String moveValue; // player public @Nullable String playValue; public @Nullable String pauseValue; public @Nullable String nextValue; public @Nullable String previousValue; public @Nullable String rewindValue; public @Nullable String fastforwardValue; /** * maps a command to a user-defined string * * @param command the command to map * @return a string or null if no mapping found */ public @Nullable String commandToFixedValue(Command command) { if (!initialized) { createMaps(); } return commandStringMap.get(command); } /** * maps a user-defined string to a state * * @param string the string to map * @return the state or null if no mapping found */ public @Nullable State fixedValueToState(String string) { if (!initialized) { createMaps(); } return stringStateMap.get(string); } private void createMaps() { addToMaps(this.onValue, OnOffType.ON); addToMaps(this.offValue, OnOffType.OFF); addToMaps(this.openValue, OpenClosedType.OPEN); addToMaps(this.closedValue, OpenClosedType.CLOSED); addToMaps(this.upValue, UpDownType.UP); addToMaps(this.downValue, UpDownType.DOWN); commandStringMap.put(IncreaseDecreaseType.INCREASE, increaseValue); commandStringMap.put(IncreaseDecreaseType.DECREASE, decreaseValue); commandStringMap.put(StopMoveType.STOP, stopValue); commandStringMap.put(StopMoveType.MOVE, moveValue); commandStringMap.put(PlayPauseType.PLAY, playValue); commandStringMap.put(PlayPauseType.PAUSE, pauseValue); commandStringMap.put(NextPreviousType.NEXT, nextValue); commandStringMap.put(NextPreviousType.PREVIOUS, previousValue); commandStringMap.put(RewindFastforwardType.REWIND, rewindValue); commandStringMap.put(RewindFastforwardType.FASTFORWARD, fastforwardValue); initialized = true; } private void addToMaps(@Nullable String value, State state) { if (value != null) { commandStringMap.put((Command) state, value); stringStateMap.put(value, state); } } }
Java
/******************************************************************************* * Copyright (c) 2012 Max Hohenegger. * All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse * Public License v1.0 which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Max Hohenegger - initial implementation ******************************************************************************/ package eu.hohenegger.c0ffee_tips.tests; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; import eu.hohenegger.c0ffee_tips.TestBasic; @RunWith(Suite.class) @SuiteClasses({TestBasic.class}) public class AllTests { }
Java
/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Middleware LLC. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA * */ package org.hibernate.hql.ast.util; import java.util.ArrayList; import java.util.Iterator; import java.util.ListIterator; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import java.util.Collection; import org.hibernate.AssertionFailure; import org.hibernate.dialect.Dialect; import org.hibernate.impl.FilterImpl; import org.hibernate.type.Type; import org.hibernate.param.DynamicFilterParameterSpecification; import org.hibernate.param.CollectionFilterKeyParameterSpecification; import org.hibernate.engine.JoinSequence; import org.hibernate.engine.SessionFactoryImplementor; import org.hibernate.engine.LoadQueryInfluencers; import org.hibernate.hql.antlr.SqlTokenTypes; import org.hibernate.hql.ast.HqlSqlWalker; import org.hibernate.hql.ast.tree.FromClause; import org.hibernate.hql.ast.tree.FromElement; import org.hibernate.hql.ast.tree.QueryNode; import org.hibernate.hql.ast.tree.DotNode; import org.hibernate.hql.ast.tree.ParameterContainer; import org.hibernate.hql.classic.ParserHelper; import org.hibernate.sql.JoinFragment; import org.hibernate.util.StringHelper; import org.hibernate.util.ArrayHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Performs the post-processing of the join information gathered during semantic analysis. * The join generating classes are complex, this encapsulates some of the JoinSequence-related * code. * * @author Joshua Davis */ public class JoinProcessor implements SqlTokenTypes { private static final Logger log = LoggerFactory.getLogger( JoinProcessor.class ); private final HqlSqlWalker walker; private final SyntheticAndFactory syntheticAndFactory; /** * Constructs a new JoinProcessor. * * @param walker The walker to which we are bound, giving us access to needed resources. */ public JoinProcessor(HqlSqlWalker walker) { this.walker = walker; this.syntheticAndFactory = new SyntheticAndFactory( walker ); } /** * Translates an AST join type (i.e., the token type) into a JoinFragment.XXX join type. * * @param astJoinType The AST join type (from HqlSqlTokenTypes or SqlTokenTypes) * @return a JoinFragment.XXX join type. * @see JoinFragment * @see SqlTokenTypes */ public static int toHibernateJoinType(int astJoinType) { switch ( astJoinType ) { case LEFT_OUTER: return JoinFragment.LEFT_OUTER_JOIN; case INNER: return JoinFragment.INNER_JOIN; case RIGHT_OUTER: return JoinFragment.RIGHT_OUTER_JOIN; default: throw new AssertionFailure( "undefined join type " + astJoinType ); } } public void processJoins(QueryNode query) { final FromClause fromClause = query.getFromClause(); final List fromElements; if ( DotNode.useThetaStyleImplicitJoins ) { // for regression testing against output from the old parser... // found it easiest to simply reorder the FromElements here into ascending order // in terms of injecting them into the resulting sql ast in orders relative to those // expected by the old parser; this is definitely another of those "only needed // for regression purposes". The SyntheticAndFactory, then, simply injects them as it // encounters them. fromElements = new ArrayList(); ListIterator liter = fromClause.getFromElements().listIterator( fromClause.getFromElements().size() ); while ( liter.hasPrevious() ) { fromElements.add( liter.previous() ); } } else { fromElements = fromClause.getFromElements(); } // Iterate through the alias,JoinSequence pairs and generate SQL token nodes. Iterator iter = fromElements.iterator(); while ( iter.hasNext() ) { final FromElement fromElement = ( FromElement ) iter.next(); JoinSequence join = fromElement.getJoinSequence(); join.setSelector( new JoinSequence.Selector() { public boolean includeSubclasses(String alias) { // The uber-rule here is that we need to include subclass joins if // the FromElement is in any way dereferenced by a property from // the subclass table; otherwise we end up with column references // qualified by a non-existent table reference in the resulting SQL... boolean containsTableAlias = fromClause.containsTableAlias( alias ); if ( fromElement.isDereferencedBySubclassProperty() ) { // TODO : or should we return 'containsTableAlias'?? log.trace( "forcing inclusion of extra joins [alias=" + alias + ", containsTableAlias=" + containsTableAlias + "]" ); return true; } boolean shallowQuery = walker.isShallowQuery(); boolean includeSubclasses = fromElement.isIncludeSubclasses(); boolean subQuery = fromClause.isSubQuery(); return includeSubclasses && containsTableAlias && !subQuery && !shallowQuery; } } ); addJoinNodes( query, join, fromElement ); } } private void addJoinNodes(QueryNode query, JoinSequence join, FromElement fromElement) { JoinFragment joinFragment = join.toJoinFragment( walker.getEnabledFilters(), fromElement.useFromFragment() || fromElement.isDereferencedBySuperclassOrSubclassProperty(), fromElement.getWithClauseFragment(), fromElement.getWithClauseJoinAlias() ); String frag = joinFragment.toFromFragmentString(); String whereFrag = joinFragment.toWhereFragmentString(); // If the from element represents a JOIN_FRAGMENT and it is // a theta-style join, convert its type from JOIN_FRAGMENT // to FROM_FRAGMENT if ( fromElement.getType() == JOIN_FRAGMENT && ( join.isThetaStyle() || StringHelper.isNotEmpty( whereFrag ) ) ) { fromElement.setType( FROM_FRAGMENT ); fromElement.getJoinSequence().setUseThetaStyle( true ); // this is used during SqlGenerator processing } // If there is a FROM fragment and the FROM element is an explicit, then add the from part. if ( fromElement.useFromFragment() /*&& StringHelper.isNotEmpty( frag )*/ ) { String fromFragment = processFromFragment( frag, join ).trim(); if ( log.isDebugEnabled() ) { log.debug( "Using FROM fragment [" + fromFragment + "]" ); } processDynamicFilterParameters( fromFragment, fromElement, walker ); } syntheticAndFactory.addWhereFragment( joinFragment, whereFrag, query, fromElement, walker ); } private String processFromFragment(String frag, JoinSequence join) { String fromFragment = frag.trim(); // The FROM fragment will probably begin with ', '. Remove this if it is present. if ( fromFragment.startsWith( ", " ) ) { fromFragment = fromFragment.substring( 2 ); } return fromFragment; } public static void processDynamicFilterParameters( final String sqlFragment, final ParameterContainer container, final HqlSqlWalker walker) { if ( walker.getEnabledFilters().isEmpty() && ( ! hasDynamicFilterParam( sqlFragment ) ) && ( ! ( hasCollectionFilterParam( sqlFragment ) ) ) ) { return; } Dialect dialect = walker.getSessionFactoryHelper().getFactory().getDialect(); String symbols = new StringBuffer().append( ParserHelper.HQL_SEPARATORS ) .append( dialect.openQuote() ) .append( dialect.closeQuote() ) .toString(); StringTokenizer tokens = new StringTokenizer( sqlFragment, symbols, true ); StringBuffer result = new StringBuffer(); while ( tokens.hasMoreTokens() ) { final String token = tokens.nextToken(); if ( token.startsWith( ParserHelper.HQL_VARIABLE_PREFIX ) ) { final String filterParameterName = token.substring( 1 ); final String[] parts = LoadQueryInfluencers.parseFilterParameterName( filterParameterName ); final FilterImpl filter = ( FilterImpl ) walker.getEnabledFilters().get( parts[0] ); final Object value = filter.getParameter( parts[1] ); final Type type = filter.getFilterDefinition().getParameterType( parts[1] ); final String typeBindFragment = StringHelper.join( ",", ArrayHelper.fillArray( "?", type.getColumnSpan( walker.getSessionFactoryHelper().getFactory() ) ) ); final String bindFragment = ( value != null && Collection.class.isInstance( value ) ) ? StringHelper.join( ",", ArrayHelper.fillArray( typeBindFragment, ( ( Collection ) value ).size() ) ) : typeBindFragment; result.append( bindFragment ); container.addEmbeddedParameter( new DynamicFilterParameterSpecification( parts[0], parts[1], type ) ); } else { result.append( token ); } } container.setText( result.toString() ); } private static boolean hasDynamicFilterParam(String sqlFragment) { return sqlFragment.indexOf( ParserHelper.HQL_VARIABLE_PREFIX ) < 0; } private static boolean hasCollectionFilterParam(String sqlFragment) { return sqlFragment.indexOf( "?" ) < 0; } }
Java
/** * Copyright (c) 2010-2016 by the respective copyright holders. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.openhab.binding.tinkerforge.internal.model.impl; import java.lang.reflect.InvocationTargetException; import java.util.concurrent.atomic.AtomicBoolean; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.impl.MinimalEObjectImpl; import org.eclipse.emf.ecore.util.EcoreUtil; import org.openhab.binding.tinkerforge.internal.LoggerConstants; import org.openhab.binding.tinkerforge.internal.TinkerforgeErrorHandler; import org.openhab.binding.tinkerforge.internal.model.MBaseDevice; import org.openhab.binding.tinkerforge.internal.model.MIndustrialQuadRelay; import org.openhab.binding.tinkerforge.internal.model.MIndustrialQuadRelayBricklet; import org.openhab.binding.tinkerforge.internal.model.MSubDevice; import org.openhab.binding.tinkerforge.internal.model.MSubDeviceHolder; import org.openhab.binding.tinkerforge.internal.model.ModelPackage; import org.openhab.binding.tinkerforge.internal.types.OnOffValue; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.tinkerforge.NotConnectedException; import com.tinkerforge.TimeoutException; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>MIndustrial Quad Relay</b></em>'. * * @author Theo Weiss * @since 1.4.0 * <!-- end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link org.openhab.binding.tinkerforge.internal.model.impl.MIndustrialQuadRelayImpl#getSwitchState * <em>Switch State</em>}</li> * <li>{@link org.openhab.binding.tinkerforge.internal.model.impl.MIndustrialQuadRelayImpl#getLogger * <em>Logger</em>}</li> * <li>{@link org.openhab.binding.tinkerforge.internal.model.impl.MIndustrialQuadRelayImpl#getUid <em>Uid</em>} * </li> * <li>{@link org.openhab.binding.tinkerforge.internal.model.impl.MIndustrialQuadRelayImpl#isPoll <em>Poll</em>} * </li> * <li>{@link org.openhab.binding.tinkerforge.internal.model.impl.MIndustrialQuadRelayImpl#getEnabledA * <em>Enabled A</em>}</li> * <li>{@link org.openhab.binding.tinkerforge.internal.model.impl.MIndustrialQuadRelayImpl#getSubId * <em>Sub Id</em>}</li> * <li>{@link org.openhab.binding.tinkerforge.internal.model.impl.MIndustrialQuadRelayImpl#getMbrick * <em>Mbrick</em>}</li> * <li>{@link org.openhab.binding.tinkerforge.internal.model.impl.MIndustrialQuadRelayImpl#getDeviceType * <em>Device Type</em>}</li> * </ul> * </p> * * @generated */ public class MIndustrialQuadRelayImpl extends MinimalEObjectImpl.Container implements MIndustrialQuadRelay { /** * The default value of the '{@link #getSwitchState() <em>Switch State</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getSwitchState() * @generated * @ordered */ protected static final OnOffValue SWITCH_STATE_EDEFAULT = null; /** * The cached value of the '{@link #getSwitchState() <em>Switch State</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getSwitchState() * @generated * @ordered */ protected OnOffValue switchState = SWITCH_STATE_EDEFAULT; /** * The default value of the '{@link #getLogger() <em>Logger</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getLogger() * @generated * @ordered */ protected static final Logger LOGGER_EDEFAULT = null; /** * The cached value of the '{@link #getLogger() <em>Logger</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getLogger() * @generated * @ordered */ protected Logger logger = LOGGER_EDEFAULT; /** * The default value of the '{@link #getUid() <em>Uid</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getUid() * @generated * @ordered */ protected static final String UID_EDEFAULT = null; /** * The cached value of the '{@link #getUid() <em>Uid</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getUid() * @generated * @ordered */ protected String uid = UID_EDEFAULT; /** * The default value of the '{@link #isPoll() <em>Poll</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #isPoll() * @generated * @ordered */ protected static final boolean POLL_EDEFAULT = true; /** * The cached value of the '{@link #isPoll() <em>Poll</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #isPoll() * @generated * @ordered */ protected boolean poll = POLL_EDEFAULT; /** * The default value of the '{@link #getEnabledA() <em>Enabled A</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getEnabledA() * @generated * @ordered */ protected static final AtomicBoolean ENABLED_A_EDEFAULT = null; /** * The cached value of the '{@link #getEnabledA() <em>Enabled A</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getEnabledA() * @generated * @ordered */ protected AtomicBoolean enabledA = ENABLED_A_EDEFAULT; /** * The default value of the '{@link #getSubId() <em>Sub Id</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getSubId() * @generated * @ordered */ protected static final String SUB_ID_EDEFAULT = null; /** * The cached value of the '{@link #getSubId() <em>Sub Id</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getSubId() * @generated * @ordered */ protected String subId = SUB_ID_EDEFAULT; /** * The default value of the '{@link #getDeviceType() <em>Device Type</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getDeviceType() * @generated * @ordered */ protected static final String DEVICE_TYPE_EDEFAULT = "quad_relay"; /** * The cached value of the '{@link #getDeviceType() <em>Device Type</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getDeviceType() * @generated * @ordered */ protected String deviceType = DEVICE_TYPE_EDEFAULT; private short relayNum; private int mask; private static final byte DEFAULT_SELECTION_MASK = 0000000000000001; private static final byte OFF_BYTE = 0000000000000000; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ protected MIndustrialQuadRelayImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override protected EClass eStaticClass() { return ModelPackage.Literals.MINDUSTRIAL_QUAD_RELAY; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public OnOffValue getSwitchState() { return switchState; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public void setSwitchState(OnOffValue newSwitchState) { OnOffValue oldSwitchState = switchState; switchState = newSwitchState; if (eNotificationRequired()) { eNotify(new ENotificationImpl(this, Notification.SET, ModelPackage.MINDUSTRIAL_QUAD_RELAY__SWITCH_STATE, oldSwitchState, switchState)); } } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated NOT */ @Override public void turnSwitch(OnOffValue state) { logger.debug("turnSwitchState called on: {}", MIndustrialQuadRelayBrickletImpl.class); try { if (state == OnOffValue.OFF) { logger.debug("setSwitchValue off"); getMbrick().getTinkerforgeDevice().setSelectedValues(mask, OFF_BYTE); } else if (state == OnOffValue.ON) { logger.debug("setSwitchState on"); getMbrick().getTinkerforgeDevice().setSelectedValues(mask, mask); } else { logger.error("{} unkown switchstate {}", LoggerConstants.TFMODELUPDATE, state); } setSwitchState(state); } catch (TimeoutException e) { TinkerforgeErrorHandler.handleError(this, TinkerforgeErrorHandler.TF_TIMEOUT_EXCEPTION, e); } catch (NotConnectedException e) { TinkerforgeErrorHandler.handleError(this, TinkerforgeErrorHandler.TF_NOT_CONNECTION_EXCEPTION, e); } } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated NOT */ @Override public void fetchSwitchState() { OnOffValue value = OnOffValue.UNDEF; try { int deviceValue = getMbrick().getTinkerforgeDevice().getValue(); if ((deviceValue & mask) == mask) { value = OnOffValue.ON; } else { value = OnOffValue.OFF; } setSwitchState(value); } catch (TimeoutException e) { TinkerforgeErrorHandler.handleError(this, TinkerforgeErrorHandler.TF_TIMEOUT_EXCEPTION, e); } catch (NotConnectedException e) { TinkerforgeErrorHandler.handleError(this, TinkerforgeErrorHandler.TF_NOT_CONNECTION_EXCEPTION, e); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public Logger getLogger() { return logger; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public void setLogger(Logger newLogger) { Logger oldLogger = logger; logger = newLogger; if (eNotificationRequired()) { eNotify(new ENotificationImpl(this, Notification.SET, ModelPackage.MINDUSTRIAL_QUAD_RELAY__LOGGER, oldLogger, logger)); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public String getUid() { return uid; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public void setUid(String newUid) { String oldUid = uid; uid = newUid; if (eNotificationRequired()) { eNotify(new ENotificationImpl(this, Notification.SET, ModelPackage.MINDUSTRIAL_QUAD_RELAY__UID, oldUid, uid)); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public boolean isPoll() { return poll; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public void setPoll(boolean newPoll) { boolean oldPoll = poll; poll = newPoll; if (eNotificationRequired()) { eNotify(new ENotificationImpl(this, Notification.SET, ModelPackage.MINDUSTRIAL_QUAD_RELAY__POLL, oldPoll, poll)); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public AtomicBoolean getEnabledA() { return enabledA; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public void setEnabledA(AtomicBoolean newEnabledA) { AtomicBoolean oldEnabledA = enabledA; enabledA = newEnabledA; if (eNotificationRequired()) { eNotify(new ENotificationImpl(this, Notification.SET, ModelPackage.MINDUSTRIAL_QUAD_RELAY__ENABLED_A, oldEnabledA, enabledA)); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public String getSubId() { return subId; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public void setSubId(String newSubId) { String oldSubId = subId; subId = newSubId; if (eNotificationRequired()) { eNotify(new ENotificationImpl(this, Notification.SET, ModelPackage.MINDUSTRIAL_QUAD_RELAY__SUB_ID, oldSubId, subId)); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public MIndustrialQuadRelayBricklet getMbrick() { if (eContainerFeatureID() != ModelPackage.MINDUSTRIAL_QUAD_RELAY__MBRICK) { return null; } return (MIndustrialQuadRelayBricklet) eContainer(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ public NotificationChain basicSetMbrick(MIndustrialQuadRelayBricklet newMbrick, NotificationChain msgs) { msgs = eBasicSetContainer((InternalEObject) newMbrick, ModelPackage.MINDUSTRIAL_QUAD_RELAY__MBRICK, msgs); return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public void setMbrick(MIndustrialQuadRelayBricklet newMbrick) { if (newMbrick != eInternalContainer() || (eContainerFeatureID() != ModelPackage.MINDUSTRIAL_QUAD_RELAY__MBRICK && newMbrick != null)) { if (EcoreUtil.isAncestor(this, newMbrick)) { throw new IllegalArgumentException("Recursive containment not allowed for " + toString()); } NotificationChain msgs = null; if (eInternalContainer() != null) { msgs = eBasicRemoveFromContainer(msgs); } if (newMbrick != null) { msgs = ((InternalEObject) newMbrick).eInverseAdd(this, ModelPackage.MSUB_DEVICE_HOLDER__MSUBDEVICES, MSubDeviceHolder.class, msgs); } msgs = basicSetMbrick(newMbrick, msgs); if (msgs != null) { msgs.dispatch(); } } else if (eNotificationRequired()) { eNotify(new ENotificationImpl(this, Notification.SET, ModelPackage.MINDUSTRIAL_QUAD_RELAY__MBRICK, newMbrick, newMbrick)); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public String getDeviceType() { return deviceType; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated NOT */ @Override public void init() { setEnabledA(new AtomicBoolean()); poll = true; // don't use the setter to prevent notification logger = LoggerFactory.getLogger(MIndustrialQuadRelay.class); relayNum = Short.parseShort(String.valueOf(subId.charAt(subId.length() - 1))); mask = DEFAULT_SELECTION_MASK << relayNum; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated NOT */ @Override public void enable() { logger.debug("enable called on MIndustrialQuadRelayImpl"); fetchSwitchState(); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated NOT */ @Override public void disable() { } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case ModelPackage.MINDUSTRIAL_QUAD_RELAY__MBRICK: if (eInternalContainer() != null) { msgs = eBasicRemoveFromContainer(msgs); } return basicSetMbrick((MIndustrialQuadRelayBricklet) otherEnd, msgs); } return super.eInverseAdd(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case ModelPackage.MINDUSTRIAL_QUAD_RELAY__MBRICK: return basicSetMbrick(null, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public NotificationChain eBasicRemoveFromContainerFeature(NotificationChain msgs) { switch (eContainerFeatureID()) { case ModelPackage.MINDUSTRIAL_QUAD_RELAY__MBRICK: return eInternalContainer().eInverseRemove(this, ModelPackage.MSUB_DEVICE_HOLDER__MSUBDEVICES, MSubDeviceHolder.class, msgs); } return super.eBasicRemoveFromContainerFeature(msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case ModelPackage.MINDUSTRIAL_QUAD_RELAY__SWITCH_STATE: return getSwitchState(); case ModelPackage.MINDUSTRIAL_QUAD_RELAY__LOGGER: return getLogger(); case ModelPackage.MINDUSTRIAL_QUAD_RELAY__UID: return getUid(); case ModelPackage.MINDUSTRIAL_QUAD_RELAY__POLL: return isPoll(); case ModelPackage.MINDUSTRIAL_QUAD_RELAY__ENABLED_A: return getEnabledA(); case ModelPackage.MINDUSTRIAL_QUAD_RELAY__SUB_ID: return getSubId(); case ModelPackage.MINDUSTRIAL_QUAD_RELAY__MBRICK: return getMbrick(); case ModelPackage.MINDUSTRIAL_QUAD_RELAY__DEVICE_TYPE: return getDeviceType(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case ModelPackage.MINDUSTRIAL_QUAD_RELAY__SWITCH_STATE: setSwitchState((OnOffValue) newValue); return; case ModelPackage.MINDUSTRIAL_QUAD_RELAY__LOGGER: setLogger((Logger) newValue); return; case ModelPackage.MINDUSTRIAL_QUAD_RELAY__UID: setUid((String) newValue); return; case ModelPackage.MINDUSTRIAL_QUAD_RELAY__POLL: setPoll((Boolean) newValue); return; case ModelPackage.MINDUSTRIAL_QUAD_RELAY__ENABLED_A: setEnabledA((AtomicBoolean) newValue); return; case ModelPackage.MINDUSTRIAL_QUAD_RELAY__SUB_ID: setSubId((String) newValue); return; case ModelPackage.MINDUSTRIAL_QUAD_RELAY__MBRICK: setMbrick((MIndustrialQuadRelayBricklet) newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case ModelPackage.MINDUSTRIAL_QUAD_RELAY__SWITCH_STATE: setSwitchState(SWITCH_STATE_EDEFAULT); return; case ModelPackage.MINDUSTRIAL_QUAD_RELAY__LOGGER: setLogger(LOGGER_EDEFAULT); return; case ModelPackage.MINDUSTRIAL_QUAD_RELAY__UID: setUid(UID_EDEFAULT); return; case ModelPackage.MINDUSTRIAL_QUAD_RELAY__POLL: setPoll(POLL_EDEFAULT); return; case ModelPackage.MINDUSTRIAL_QUAD_RELAY__ENABLED_A: setEnabledA(ENABLED_A_EDEFAULT); return; case ModelPackage.MINDUSTRIAL_QUAD_RELAY__SUB_ID: setSubId(SUB_ID_EDEFAULT); return; case ModelPackage.MINDUSTRIAL_QUAD_RELAY__MBRICK: setMbrick((MIndustrialQuadRelayBricklet) null); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case ModelPackage.MINDUSTRIAL_QUAD_RELAY__SWITCH_STATE: return SWITCH_STATE_EDEFAULT == null ? switchState != null : !SWITCH_STATE_EDEFAULT.equals(switchState); case ModelPackage.MINDUSTRIAL_QUAD_RELAY__LOGGER: return LOGGER_EDEFAULT == null ? logger != null : !LOGGER_EDEFAULT.equals(logger); case ModelPackage.MINDUSTRIAL_QUAD_RELAY__UID: return UID_EDEFAULT == null ? uid != null : !UID_EDEFAULT.equals(uid); case ModelPackage.MINDUSTRIAL_QUAD_RELAY__POLL: return poll != POLL_EDEFAULT; case ModelPackage.MINDUSTRIAL_QUAD_RELAY__ENABLED_A: return ENABLED_A_EDEFAULT == null ? enabledA != null : !ENABLED_A_EDEFAULT.equals(enabledA); case ModelPackage.MINDUSTRIAL_QUAD_RELAY__SUB_ID: return SUB_ID_EDEFAULT == null ? subId != null : !SUB_ID_EDEFAULT.equals(subId); case ModelPackage.MINDUSTRIAL_QUAD_RELAY__MBRICK: return getMbrick() != null; case ModelPackage.MINDUSTRIAL_QUAD_RELAY__DEVICE_TYPE: return DEVICE_TYPE_EDEFAULT == null ? deviceType != null : !DEVICE_TYPE_EDEFAULT.equals(deviceType); } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public int eBaseStructuralFeatureID(int derivedFeatureID, Class<?> baseClass) { if (baseClass == MBaseDevice.class) { switch (derivedFeatureID) { case ModelPackage.MINDUSTRIAL_QUAD_RELAY__LOGGER: return ModelPackage.MBASE_DEVICE__LOGGER; case ModelPackage.MINDUSTRIAL_QUAD_RELAY__UID: return ModelPackage.MBASE_DEVICE__UID; case ModelPackage.MINDUSTRIAL_QUAD_RELAY__POLL: return ModelPackage.MBASE_DEVICE__POLL; case ModelPackage.MINDUSTRIAL_QUAD_RELAY__ENABLED_A: return ModelPackage.MBASE_DEVICE__ENABLED_A; default: return -1; } } if (baseClass == MSubDevice.class) { switch (derivedFeatureID) { case ModelPackage.MINDUSTRIAL_QUAD_RELAY__SUB_ID: return ModelPackage.MSUB_DEVICE__SUB_ID; case ModelPackage.MINDUSTRIAL_QUAD_RELAY__MBRICK: return ModelPackage.MSUB_DEVICE__MBRICK; default: return -1; } } return super.eBaseStructuralFeatureID(derivedFeatureID, baseClass); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public int eDerivedStructuralFeatureID(int baseFeatureID, Class<?> baseClass) { if (baseClass == MBaseDevice.class) { switch (baseFeatureID) { case ModelPackage.MBASE_DEVICE__LOGGER: return ModelPackage.MINDUSTRIAL_QUAD_RELAY__LOGGER; case ModelPackage.MBASE_DEVICE__UID: return ModelPackage.MINDUSTRIAL_QUAD_RELAY__UID; case ModelPackage.MBASE_DEVICE__POLL: return ModelPackage.MINDUSTRIAL_QUAD_RELAY__POLL; case ModelPackage.MBASE_DEVICE__ENABLED_A: return ModelPackage.MINDUSTRIAL_QUAD_RELAY__ENABLED_A; default: return -1; } } if (baseClass == MSubDevice.class) { switch (baseFeatureID) { case ModelPackage.MSUB_DEVICE__SUB_ID: return ModelPackage.MINDUSTRIAL_QUAD_RELAY__SUB_ID; case ModelPackage.MSUB_DEVICE__MBRICK: return ModelPackage.MINDUSTRIAL_QUAD_RELAY__MBRICK; default: return -1; } } return super.eDerivedStructuralFeatureID(baseFeatureID, baseClass); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public int eDerivedOperationID(int baseOperationID, Class<?> baseClass) { if (baseClass == MBaseDevice.class) { switch (baseOperationID) { case ModelPackage.MBASE_DEVICE___INIT: return ModelPackage.MINDUSTRIAL_QUAD_RELAY___INIT; case ModelPackage.MBASE_DEVICE___ENABLE: return ModelPackage.MINDUSTRIAL_QUAD_RELAY___ENABLE; case ModelPackage.MBASE_DEVICE___DISABLE: return ModelPackage.MINDUSTRIAL_QUAD_RELAY___DISABLE; default: return -1; } } if (baseClass == MSubDevice.class) { switch (baseOperationID) { default: return -1; } } return super.eDerivedOperationID(baseOperationID, baseClass); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public Object eInvoke(int operationID, EList<?> arguments) throws InvocationTargetException { switch (operationID) { case ModelPackage.MINDUSTRIAL_QUAD_RELAY___INIT: init(); return null; case ModelPackage.MINDUSTRIAL_QUAD_RELAY___ENABLE: enable(); return null; case ModelPackage.MINDUSTRIAL_QUAD_RELAY___DISABLE: disable(); return null; case ModelPackage.MINDUSTRIAL_QUAD_RELAY___TURN_SWITCH__ONOFFVALUE: turnSwitch((OnOffValue) arguments.get(0)); return null; case ModelPackage.MINDUSTRIAL_QUAD_RELAY___FETCH_SWITCH_STATE: fetchSwitchState(); return null; } return super.eInvoke(operationID, arguments); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public String toString() { if (eIsProxy()) { return super.toString(); } StringBuffer result = new StringBuffer(super.toString()); result.append(" (switchState: "); result.append(switchState); result.append(", logger: "); result.append(logger); result.append(", uid: "); result.append(uid); result.append(", poll: "); result.append(poll); result.append(", enabledA: "); result.append(enabledA); result.append(", subId: "); result.append(subId); result.append(", deviceType: "); result.append(deviceType); result.append(')'); return result.toString(); } } // MIndustrialQuadRelayImpl
Java
#!/bin/bash EXIT_CODE=0 kill_ffmpeg(){ echo "Killing ffmpeg with PID=$ffmpeg_pid" kill -2 "$ffmpeg_pid" wait "$ffmpeg_pid" mkdir -p /tmp/e2e/report/ cp /tmp/ffmpeg_report/* /tmp/e2e/report/ } set -x # Validate selenium base URL if [ -z "$TS_SELENIUM_BASE_URL" ]; then echo "The \"TS_SELENIUM_BASE_URL\" is not set!"; echo "Please, set the \"TS_SELENIUM_BASE_URL\" environment variable." exit 1 fi # Set testing suite if [ -z "$TEST_SUITE" ]; then TEST_SUITE=test-happy-path fi # Launch display mode and VNC server export DISPLAY=':20' Xvfb :20 -screen 0 1920x1080x24 > /dev/null 2>&1 & x11vnc -display :20 -N -forever > /dev/null 2>&1 & echo '' echo '#######################' echo '' echo 'For remote debug connect to the VNC server 0.0.0.0:5920' echo '' echo '#######################' echo '' # Launch selenium server /usr/bin/supervisord --configuration /etc/supervisord.conf & \ export TS_SELENIUM_REMOTE_DRIVER_URL=http://localhost:4444/wd/hub # Check selenium server launching expectedStatus=200 currentTry=1 maximumAttempts=5 while [ $(curl -s -o /dev/null -w "%{http_code}" --fail http://localhost:4444/wd/hub/status) != $expectedStatus ]; do if (( currentTry > maximumAttempts )); then status=$(curl -s -o /dev/null -w "%{http_code}" --fail http://localhost:4444/wd/hub/status) echo "Exceeded the maximum number of checking attempts," echo "selenium server status is '$status' and it is different from '$expectedStatus'"; exit 1; fi; echo "Wait selenium server availability ..." curentTry=$((curentTry + 1)) sleep 1 done # Print information about launching tests if mount | grep 'e2e'; then echo "The local code is mounted. Executing local code." cd /tmp/e2e || exit npm install else echo "Executing e2e tests from an image." cd /tmp/e2e || exit fi # Launch tests if [ $TS_LOAD_TESTS ]; then timestamp=$(date +%s) user_folder="$TS_SELENIUM_USERNAME-$timestamp" export TS_SELENIUM_REPORT_FOLDER="./$user_folder/report" export TS_SELENIUM_LOAD_TEST_REPORT_FOLDER="./$user_folder/load-test-folder" CONSOLE_LOGS="./$user_folder/console-log.txt" mkdir $user_folder touch $CONSOLE_LOGS npm run $TEST_SUITE 2>&1 | tee $CONSOLE_LOGS echo "Tarring files and sending them via FTP..." tar -cf $user_folder.tar ./$user_folder ftp -vn load-tests-ftp-service << End_script user user pass1234 binary put $user_folder.tar quit End_script echo "Files sent to load-tests-ftp-service." else SCREEN_RECORDING=${VIDEO_RECORDING:-true} if [ "${SCREEN_RECORDING}" == "true" ]; then echo "Starting ffmpeg recording..." mkdir -p /tmp/ffmpeg_report nohup ffmpeg -y -video_size 1920x1080 -framerate 24 -f x11grab -i :20.0 /tmp/ffmpeg_report/output.mp4 2> /tmp/ffmpeg_report/ffmpeg_err.txt > /tmp/ffmpeg_report/ffmpeg_std.txt & ffmpeg_pid=$! trap kill_ffmpeg 2 15 fi echo "Running TEST_SUITE: $TEST_SUITE with user: $TS_SELENIUM_USERNAME" npm run $TEST_SUITE EXIT_CODE=$? if [ "${SCREEN_RECORDING}" == "true" ]; then kill_ffmpeg fi exit $EXIT_CODE fi
Java
package org.hibernate.envers.tools; import org.hibernate.mapping.Collection; import org.hibernate.mapping.OneToMany; import org.hibernate.mapping.ToOne; import org.hibernate.mapping.Value; /** * @author Adam Warski (adam at warski dot org) */ public class MappingTools { /** * @param componentName Name of the component, that is, name of the property in the entity that references the * component. * @return A prefix for properties in the given component. */ public static String createComponentPrefix(String componentName) { return componentName + "_"; } /** * @param referencePropertyName The name of the property that holds the relation to the entity. * @return A prefix which should be used to prefix an id mapper for the related entity. */ public static String createToOneRelationPrefix(String referencePropertyName) { return referencePropertyName + "_"; } public static String getReferencedEntityName(Value value) { if (value instanceof ToOne) { return ((ToOne) value).getReferencedEntityName(); } else if (value instanceof OneToMany) { return ((OneToMany) value).getReferencedEntityName(); } else if (value instanceof Collection) { return getReferencedEntityName(((Collection) value).getElement()); } return null; } }
Java
/******************************************************************************* * Copyright (c) 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package com.ibm.ws.security.oauth20.web; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; import java.security.Principal; import java.util.Collection; import java.util.Hashtable; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.StringTokenizer; import javax.security.auth.Subject; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.osgi.framework.ServiceReference; import org.osgi.service.component.ComponentContext; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.ConfigurationPolicy; import org.osgi.service.component.annotations.Deactivate; import org.osgi.service.component.annotations.Reference; import org.osgi.service.component.annotations.ReferenceCardinality; import org.osgi.service.component.annotations.ReferencePolicy; import org.osgi.service.component.annotations.ReferencePolicyOption; import com.ibm.ejs.ras.TraceNLS; import com.ibm.oauth.core.api.OAuthResult; import com.ibm.oauth.core.api.attributes.AttributeList; import com.ibm.oauth.core.api.error.OidcServerException; import com.ibm.oauth.core.api.error.oauth20.OAuth20AccessDeniedException; import com.ibm.oauth.core.api.error.oauth20.OAuth20DuplicateParameterException; import com.ibm.oauth.core.api.error.oauth20.OAuth20Exception; import com.ibm.oauth.core.api.oauth20.token.OAuth20Token; import com.ibm.oauth.core.internal.oauth20.OAuth20Constants; import com.ibm.oauth.core.internal.oauth20.OAuth20Util; import com.ibm.oauth.core.internal.oauth20.OAuthResultImpl; import com.ibm.websphere.ras.Tr; import com.ibm.websphere.ras.TraceComponent; import com.ibm.websphere.security.WSSecurityException; import com.ibm.websphere.security.auth.WSSubject; import com.ibm.ws.ffdc.FFDCFilter; import com.ibm.ws.ffdc.annotation.FFDCIgnore; import com.ibm.ws.security.SecurityService; import com.ibm.ws.security.common.claims.UserClaims; import com.ibm.ws.security.oauth20.ProvidersService; import com.ibm.ws.security.oauth20.api.Constants; import com.ibm.ws.security.oauth20.api.OAuth20EnhancedTokenCache; import com.ibm.ws.security.oauth20.api.OAuth20Provider; import com.ibm.ws.security.oauth20.error.impl.OAuth20TokenRequestExceptionHandler; import com.ibm.ws.security.oauth20.exception.OAuth20BadParameterException; import com.ibm.ws.security.oauth20.plugins.OAuth20TokenImpl; import com.ibm.ws.security.oauth20.plugins.OidcBaseClient; import com.ibm.ws.security.oauth20.util.ConfigUtils; import com.ibm.ws.security.oauth20.util.Nonce; import com.ibm.ws.security.oauth20.util.OAuth20ProviderUtils; import com.ibm.ws.security.oauth20.util.OIDCConstants; import com.ibm.ws.security.oauth20.util.OidcOAuth20Util; import com.ibm.ws.security.oauth20.web.OAuth20Request.EndpointType; import com.ibm.ws.webcontainer.security.CookieHelper; import com.ibm.ws.webcontainer.security.ReferrerURLCookieHandler; import com.ibm.ws.webcontainer.security.WebAppSecurityCollaboratorImpl; import com.ibm.wsspi.kernel.service.utils.AtomicServiceReference; import com.ibm.wsspi.kernel.service.utils.ConcurrentServiceReferenceMap; import com.ibm.wsspi.security.oauth20.JwtAccessTokenMediator; import com.ibm.wsspi.security.oauth20.TokenIntrospectProvider; @Component(service = OAuth20EndpointServices.class, name = "com.ibm.ws.security.oauth20.web.OAuth20EndpointServices", immediate = true, configurationPolicy = ConfigurationPolicy.IGNORE, property = "service.vendor=IBM") public class OAuth20EndpointServices { private static TraceComponent tc = Tr.register(OAuth20EndpointServices.class); private static TraceComponent tc2 = Tr.register(OAuth20EndpointServices.class, // use this one when bundle is the usual bundle. TraceConstants.TRACE_GROUP, TraceConstants.MESSAGE_BUNDLE); protected static final String MESSAGE_BUNDLE = "com.ibm.ws.security.oauth20.internal.resources.OAuthMessages"; protected static final String MSG_RESOURCE_BUNDLE = "com.ibm.ws.security.oauth20.resources.ProviderMsgs"; public static final String KEY_SERVICE_PID = "service.pid"; public static final String KEY_SECURITY_SERVICE = "securityService"; protected final AtomicServiceReference<SecurityService> securityServiceRef = new AtomicServiceReference<SecurityService>(KEY_SECURITY_SERVICE); public static final String KEY_TOKEN_INTROSPECT_PROVIDER = "tokenIntrospectProvider"; private final ConcurrentServiceReferenceMap<String, TokenIntrospectProvider> tokenIntrospectProviderRef = new ConcurrentServiceReferenceMap<String, TokenIntrospectProvider>(KEY_TOKEN_INTROSPECT_PROVIDER); public static final String KEY_JWT_MEDIATOR = "jwtAccessTokenMediator"; private final ConcurrentServiceReferenceMap<String, JwtAccessTokenMediator> jwtAccessTokenMediatorRef = new ConcurrentServiceReferenceMap<String, JwtAccessTokenMediator>(KEY_JWT_MEDIATOR); public static final String KEY_OAUTH_CLIENT_METATYPE_SERVICE = "oauth20ClientMetatypeService"; private static final AtomicServiceReference<OAuth20ClientMetatypeService> oauth20ClientMetatypeServiceRef = new AtomicServiceReference<OAuth20ClientMetatypeService>(KEY_OAUTH_CLIENT_METATYPE_SERVICE); private static final String ATTR_NONCE = "consentNonce"; public static final String AUTHENTICATED = "authenticated"; protected volatile ClientAuthentication clientAuthentication = new ClientAuthentication(); protected volatile ClientAuthorization clientAuthorization = new ClientAuthorization(); protected volatile UserAuthentication userAuthentication = new UserAuthentication(); protected volatile CoverageMapEndpointServices coverageMapServices = new CoverageMapEndpointServices(); protected volatile RegistrationEndpointServices registrationEndpointServices = new RegistrationEndpointServices(); protected volatile Consent consent = new Consent(); protected volatile TokenExchange tokenExchange = new TokenExchange(); @Reference(service = SecurityService.class, name = KEY_SECURITY_SERVICE, policy = ReferencePolicy.DYNAMIC, policyOption = ReferencePolicyOption.GREEDY) protected void setSecurityService(ServiceReference<SecurityService> reference) { securityServiceRef.setReference(reference); } protected void unsetSecurityService(ServiceReference<SecurityService> reference) { securityServiceRef.unsetReference(reference); } @Reference(service = TokenIntrospectProvider.class, name = KEY_TOKEN_INTROSPECT_PROVIDER, policy = ReferencePolicy.DYNAMIC, cardinality = ReferenceCardinality.MULTIPLE, policyOption = ReferencePolicyOption.GREEDY) protected void setTokenIntrospectProvider(ServiceReference<TokenIntrospectProvider> ref) { synchronized (tokenIntrospectProviderRef) { tokenIntrospectProviderRef.putReference((String) ref.getProperty(KEY_SERVICE_PID), ref); } } protected void unsetTokenIntrospectProvider(ServiceReference<TokenIntrospectProvider> ref) { synchronized (tokenIntrospectProviderRef) { tokenIntrospectProviderRef.removeReference((String) ref.getProperty(KEY_SERVICE_PID), ref); } } @Reference(service = JwtAccessTokenMediator.class, name = KEY_JWT_MEDIATOR, policy = ReferencePolicy.DYNAMIC, cardinality = ReferenceCardinality.OPTIONAL, policyOption = ReferencePolicyOption.GREEDY) protected void setJwtAccessTokenMediator(ServiceReference<JwtAccessTokenMediator> ref) { synchronized (jwtAccessTokenMediatorRef) { jwtAccessTokenMediatorRef.putReference((String) ref.getProperty(KEY_SERVICE_PID), ref); } } protected void unsetJwtAccessTokenMediator(ServiceReference<JwtAccessTokenMediator> ref) { synchronized (jwtAccessTokenMediatorRef) { jwtAccessTokenMediatorRef.removeReference((String) ref.getProperty(KEY_SERVICE_PID), ref); } } @Reference(service = OAuth20ClientMetatypeService.class, name = KEY_OAUTH_CLIENT_METATYPE_SERVICE, policy = ReferencePolicy.DYNAMIC) protected void setOAuth20ClientMetatypeService(ServiceReference<OAuth20ClientMetatypeService> ref) { oauth20ClientMetatypeServiceRef.setReference(ref); } protected void unsetOAuth20ClientMetatypeService(ServiceReference<OAuth20ClientMetatypeService> ref) { oauth20ClientMetatypeServiceRef.unsetReference(ref); } @Activate protected void activate(ComponentContext cc) { securityServiceRef.activate(cc); tokenIntrospectProviderRef.activate(cc); jwtAccessTokenMediatorRef.activate(cc); oauth20ClientMetatypeServiceRef.activate(cc); ConfigUtils.setJwtAccessTokenMediatorService(jwtAccessTokenMediatorRef); TokenIntrospect.setTokenIntrospect(tokenIntrospectProviderRef); // The TraceComponent object was not initialized with the message bundle containing this message, so we cannot use // Tr.info(tc, "OAUTH_ENDPOINT_SERVICE_ACTIVATED"). Eventually these messages will be merged into one file, making this infoMsg variable unnecessary String infoMsg = TraceNLS.getFormattedMessage(this.getClass(), MESSAGE_BUNDLE, "OAUTH_ENDPOINT_SERVICE_ACTIVATED", null, "CWWKS1410I: The OAuth endpoint service is activated."); Tr.info(tc, infoMsg); } @Deactivate protected void deactivate(ComponentContext cc) { securityServiceRef.deactivate(cc); tokenIntrospectProviderRef.deactivate(cc); jwtAccessTokenMediatorRef.deactivate(cc); oauth20ClientMetatypeServiceRef.deactivate(cc); } protected void handleOAuthRequest(HttpServletRequest request, HttpServletResponse response, ServletContext servletContext) throws ServletException, IOException { if (tc.isDebugEnabled()) { Tr.debug(tc, "Checking if OAuth20 Provider should process the request."); Tr.debug(tc, "Inbound request " + com.ibm.ws.security.common.web.WebUtils.getRequestStringForTrace(request, "client_secret")); } OAuth20Request oauth20Request = getAuth20Request(request, response); OAuth20Provider oauth20Provider = null; if (oauth20Request != null) { EndpointType endpointType = oauth20Request.getType(); oauth20Provider = getProvider(response, oauth20Request); if (oauth20Provider != null) { AttributeList optionalParams = new AttributeList(); if (tc.isDebugEnabled()) { Tr.debug(tc, "OAUTH20 _SSO OP PROCESS IS STARTING."); Tr.debug(tc, "OAUTH20 _SSO OP inbound URL " + com.ibm.ws.security.common.web.WebUtils.getRequestStringForTrace(request, "client_secret")); } handleEndpointRequest(request, response, servletContext, oauth20Provider, endpointType, optionalParams); } } if (tc.isDebugEnabled()) { if (oauth20Provider != null) { Tr.debug(tc, "OAUTH20 _SSO OP PROCESS HAS ENDED."); } else { Tr.debug(tc, "OAUTH20 _SSO OP WILL NOT PROCESS THE REQUEST"); } } } @FFDCIgnore({ OidcServerException.class }) protected void handleEndpointRequest(HttpServletRequest request, HttpServletResponse response, ServletContext servletContext, OAuth20Provider oauth20Provider, EndpointType endpointType, AttributeList oidcOptionalParams) throws ServletException, IOException { checkHttpsRequirement(request, response, oauth20Provider); if (response.isCommitted()) { if (tc.isDebugEnabled()) { Tr.debug(tc, "Response has already been committed, so likely did not pass HTTPS requirement"); } return; } boolean isBrowserWithBasicAuth = false; UIAccessTokenBuilder uitb = null; if (tc.isDebugEnabled()) { Tr.debug(tc, "endpointType[" + endpointType + "]"); } try { switch (endpointType) { case authorize: OAuthResult result = processAuthorizationRequest(oauth20Provider, request, response, servletContext, oidcOptionalParams); if (result != null) { if (result.getStatus() == OAuthResult.TAI_CHALLENGE) { // SPNEGO negotiate break; } else if (result.getStatus() != OAuthResult.STATUS_OK) { userAuthentication.renderErrorPage(oauth20Provider, request, response, result); } } break; case token: if (clientAuthentication.verify(oauth20Provider, request, response, endpointType)) { processTokenRequest(oauth20Provider, request, response); } break; case introspect: if (clientAuthentication.verify(oauth20Provider, request, response, endpointType)) { introspect(oauth20Provider, request, response); } break; case revoke: if (clientAuthentication.verify(oauth20Provider, request, response, endpointType)) { revoke(oauth20Provider, request, response); } break; case coverage_map: // non-spec extension coverageMapServices.handleEndpointRequest(oauth20Provider, request, response); break; case registration: secureEndpointServices(oauth20Provider, request, response, servletContext, RegistrationEndpointServices.ROLE_REQUIRED, true); registrationEndpointServices.handleEndpointRequest(oauth20Provider, request, response); break; case logout: // no need to authenticate logout(oauth20Provider, request, response); break; case app_password: tokenExchange.processAppPassword(oauth20Provider, request, response); break; case app_token: tokenExchange.processAppToken(oauth20Provider, request, response); break; // these next 3 are for UI pages case clientManagement: if (!authenticateUI(request, response, servletContext, oauth20Provider, oidcOptionalParams, RegistrationEndpointServices.ROLE_REQUIRED)) { break; } // new MockUiPage(request, response).render(); // TODO: replace with hook to real ui. RequestDispatcher rd = servletContext.getRequestDispatcher("WEB-CONTENT/clientAdmin/index.jsp"); rd.forward(request, response); break; case personalTokenManagement: if (!authenticateUI(request, response, servletContext, oauth20Provider, oidcOptionalParams, null)) { break; } checkUIConfig(oauth20Provider, request); // put auth header and access token and feature enablement state into request attributes for ui to use uitb = new UIAccessTokenBuilder(oauth20Provider, request); uitb.createHeaderValuesForUI(); // new MockUiPage(request, response).render(); // TODO: replace with hook to real ui. RequestDispatcher rd2 = servletContext.getRequestDispatcher("WEB-CONTENT/accountManager/index.jsp"); rd2.forward(request, response); break; case usersTokenManagement: if (!authenticateUI(request, response, servletContext, oauth20Provider, oidcOptionalParams, OAuth20Constants.TOKEN_MANAGER_ROLE)) { break; } checkUIConfig(oauth20Provider, request); // put auth header and access token and feature enablement state into request attributes for ui to use uitb = new UIAccessTokenBuilder(oauth20Provider, request); uitb.createHeaderValuesForUI(); // new MockUiPage(request, response).render(); // TODO: replace with hook to real ui. RequestDispatcher rd3 = servletContext.getRequestDispatcher("WEB-CONTENT/tokenManager/index.jsp"); rd3.forward(request, response); break; case clientMetatype: serveClientMetatypeRequest(request, response); break; default: break; } } catch (OidcServerException e) { if (!isBrowserWithBasicAuth) { // we don't want routine browser auth challenges producing ffdc's. // (but if a login is invalid in that case, we will still get a CWIML4537E from base sec.) // however for non-browsers we want ffdc's like we had before, so generate manually if (!e.getErrorDescription().contains("CWWKS1424E")) { // no ffdc for nonexistent clients com.ibm.ws.ffdc.FFDCFilter.processException(e, "com.ibm.ws.security.oauth20.web.OAuth20EndpointServices", "324", this); } } boolean suppressBasicAuthChallenge = isBrowserWithBasicAuth; // ui must NOT log in using basic auth, so logout function will work. WebUtils.sendErrorJSON(response, e.getHttpStatus(), e.getErrorCode(), e.getErrorDescription(request.getLocales()), suppressBasicAuthChallenge); } } // return true if clear to go, false otherwise. Log message and/or throw exception if unsuccessful private boolean authenticateUI(HttpServletRequest request, HttpServletResponse response, ServletContext servletContext, OAuth20Provider provider, AttributeList options, String requiredRole) throws ServletException, IOException, OidcServerException { OAuthResult result = handleUIUserAuthentication(request, response, servletContext, provider, options); if (!isUIAuthenticationComplete(request, response, provider, result, requiredRole)) { return false; } return true; } private boolean isUIAuthenticationComplete(HttpServletRequest request, HttpServletResponse response, OAuth20Provider provider, OAuthResult result, String requiredRole) throws OidcServerException { if (result == null) { // sent to login page return false; } if (result.getStatus() == OAuthResult.TAI_CHALLENGE) { // SPNEGO negotiate return false; } if (result.getStatus() != OAuthResult.STATUS_OK) { try { userAuthentication.renderErrorPage(provider, request, response, result); } catch (Exception e) { // ffdc } return false; } if (requiredRole != null && !request.isUserInRole(requiredRole)) { throw new OidcServerException("403", OIDCConstants.ERROR_ACCESS_DENIED, HttpServletResponse.SC_FORBIDDEN); } return true; } void serveClientMetatypeRequest(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { OAuth20ClientMetatypeService metatypeService = oauth20ClientMetatypeServiceRef.getService(); if (metatypeService == null) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } metatypeService.sendClientMetatypeData(request, response); } private boolean checkUIConfig(OAuth20Provider provider, HttpServletRequest request) { String uri = request.getRequestURI(); String id = provider.getInternalClientId(); String secret = provider.getInternalClientSecret(); OidcBaseClient client = null; boolean result = false; try { client = provider.getClientProvider().get(id); } catch (OidcServerException e) { // ffdc } if (client != null) { result = secret != null && client.isEnabled() && (client.isAppPasswordAllowed() || client.isAppTokenAllowed()); } if (!result) { Tr.warning(tc2, "OAUTH_UI_ENDPOINT_NOT_ENABLED", uri); } return result; } /** * Perform logout. call base security logout to clear ltpa cookie. * Then redirect to a configured logout page if available, else a default. * * This does NOT implement * OpenID Connect Session Management 1.0 draft 28. as of Nov. 2017 * https://openid.net/specs/openid-connect-session-1_0.html#RedirectionAfterLogout * * Instead it is a simpler approach that just deletes the ltpa (sso) cookie * and sends a simple error page if things go wrong. * * @param provider * @param request * @param response */ public void logout(OAuth20Provider provider, HttpServletRequest request, HttpServletResponse response) { if (tc.isDebugEnabled()) { Tr.debug(tc, "Processing logout"); } try { request.logout(); // ltpa cookie removed if present. No exception if not. } catch (ServletException e) { FFDCFilter.processException(e, this.getClass().getName(), "logout", new Object[] {}); new LogoutPages().sendDefaultErrorPage(request, response); return; } // not part of spec: logout url defined in config, not client-specific String logoutRedirectURL = provider.getLogoutRedirectURL(); try { if (logoutRedirectURL != null) { String encodedURL = URLEncodeParams(logoutRedirectURL); if (tc.isDebugEnabled()) { Tr.debug(tc, "OAUTH20 _SSO OP redirecting to [" + logoutRedirectURL + "], url encoded to [" + encodedURL + "]"); } response.sendRedirect(encodedURL); return; } else { // send default logout page new LogoutPages().sendDefaultLogoutPage(request, response); } } catch (IOException e) { FFDCFilter.processException(e, this.getClass().getName(), "logout", new Object[] {}); new LogoutPages().sendDefaultErrorPage(request, response); } } String URLEncodeParams(String UrlStr) { String sep = "?"; String encodedURL = UrlStr; int index = UrlStr.indexOf(sep); // if encoded url in server.xml, don't encode it again. boolean alreadyEncoded = UrlStr.contains("%"); if (index > -1 && !alreadyEncoded) { index++; // don't encode ? String prefix = UrlStr.substring(0, index); String suffix = UrlStr.substring(index); try { encodedURL = prefix + java.net.URLEncoder.encode(suffix, StandardCharsets.UTF_8.toString()); // shouldn't encode = in queries, so flip those back encodedURL = encodedURL.replace("%3D", "="); } catch (UnsupportedEncodingException e) { // ffdc } } return encodedURL; } public OAuthResult processAuthorizationRequest(OAuth20Provider provider, HttpServletRequest request, HttpServletResponse response, ServletContext servletContext, AttributeList options) throws ServletException, IOException, OidcServerException { OAuthResult oauthResult = checkForError(request); if (oauthResult != null) { return oauthResult; } boolean autoAuthz = clientAuthorization.isClientAutoAuthorized(provider, request); String reqConsentNonce = getReqConsentNonce(request); boolean afterLogin = isAfterLogin(request); // we've been to login.jsp or it's replacement. if (reqConsentNonce == null) { // validate request for initial authorization request only oauthResult = clientAuthorization.validateAuthorization(provider, request, response); if (oauthResult.getStatus() != OAuthResult.STATUS_OK) { if (tc.isDebugEnabled()) { Tr.debug(tc, "Status is OK, returning result"); } return oauthResult; } } oauthResult = handleUserAuthentication(oauthResult, request, response, servletContext, provider, reqConsentNonce, options, autoAuthz, afterLogin); return oauthResult; } /** * Adds the id_token_hint_status, id_token_hint_username, and id_token_hint_clientid attributes from the options list * into attrList, if those attributes exist. * * @param options * @param attrList */ private void setTokenHintAttributes(AttributeList options, AttributeList attrList) { String value = options.getAttributeValueByName(OIDCConstants.OIDC_AUTHZ_PARAM_ID_TOKEN_HINT_STATUS); if (value != null) { attrList.setAttribute(OIDCConstants.OIDC_AUTHZ_PARAM_ID_TOKEN_HINT_STATUS, OAuth20Constants.ATTRTYPE_REQUEST, new String[] { value }); } value = options.getAttributeValueByName(OIDCConstants.OIDC_AUTHZ_PARAM_ID_TOKEN_HINT_USERNAME); if (value != null) { attrList.setAttribute(OIDCConstants.OIDC_AUTHZ_PARAM_ID_TOKEN_HINT_USERNAME, OAuth20Constants.ATTRTYPE_REQUEST, new String[] { value }); } value = options.getAttributeValueByName(OIDCConstants.OIDC_AUTHZ_PARAM_ID_TOKEN_HINT_CLIENTID); if (value != null) { attrList.setAttribute(OIDCConstants.OIDC_AUTHZ_PARAM_ID_TOKEN_HINT_CLIENTID, OAuth20Constants.ATTRTYPE_REQUEST, new String[] { value }); } } /** * @param attrs * @param request * @return OAuthResultImpl if validation failed, null otherwise. */ private OAuthResultImpl validateIdTokenHintIfPresent(AttributeList attrs, HttpServletRequest request) { if (attrs != null) { Principal user = request.getUserPrincipal(); String username = null; if (user != null) { username = user.getName(); } try { userAuthentication.validateIdTokenHint(username, attrs); } catch (OAuth20Exception oe) { return new OAuthResultImpl(OAuthResult.STATUS_FAILED, attrs, oe); } } return null; } /** * Creates a 401 STATUS_FAILED result due to the token limit being reached. * * @param attrs * @param request * @param clientId * @return */ private OAuthResult createTokenLimitResult(AttributeList attrs, HttpServletRequest request, String clientId) { if (attrs == null) { attrs = new AttributeList(); String responseType = request.getParameter(OAuth20Constants.RESPONSE_TYPE); attrs.setAttribute(OAuth20Constants.RESPONSE_TYPE, OAuth20Constants.RESPONSE_TYPE, new String[] { responseType }); attrs.setAttribute(OAuth20Constants.CLIENT_ID, OAuth20Constants.CLIENT_ID, new String[] { clientId }); if (tc.isDebugEnabled()) { Tr.debug(tc, "Attribute responseType:" + responseType + " client_id:" + clientId); } } OAuth20AccessDeniedException e = new OAuth20AccessDeniedException("security.oauth20.token.limit.external.error"); e.setHttpStatusCode(HttpServletResponse.SC_BAD_REQUEST); OAuthResult oauthResultWithExcep = new OAuthResultImpl(OAuthResult.STATUS_FAILED, attrs, e); return oauthResultWithExcep; } private OAuthResult handleUIUserAuthentication(HttpServletRequest request, HttpServletResponse response, ServletContext servletContext, OAuth20Provider provider, AttributeList options) throws IOException, ServletException, OidcServerException { OAuthResult oauthResult = null; Prompt prompt = new Prompt(); if (request.getUserPrincipal() == null) { // authenticate user if not done yet. Send to login page. if (tc.isDebugEnabled()) { Tr.debug(tc, "Authenticate user if not done yet"); } oauthResult = userAuthentication.handleAuthenticationWithOAuthResult(provider, request, response, prompt, securityServiceRef, servletContext, OAuth20EndpointServices.AUTHENTICATED, oauthResult); } if (request.getUserPrincipal() == null) { // must be redirect return oauthResult; } else if (CookieHelper.getCookieValue(request.getCookies(), ReferrerURLCookieHandler.CUSTOM_RELOGIN_URL_COOKIENAME) != null) { ReferrerURLCookieHandler handler = WebAppSecurityCollaboratorImpl.getGlobalWebAppSecurityConfig().createReferrerURLCookieHandler(); // GM 2017.05.31 // ReferrerURLCookieHandler handler = new ReferrerURLCookieHandler(WebAppSecurityCollaboratorImpl.getGlobalWebAppSecurityConfig()); handler.invalidateReferrerURLCookie(request, response, ReferrerURLCookieHandler.CUSTOM_RELOGIN_URL_COOKIENAME); } if (!request.isUserInRole(AUTHENTICATED)) { // must be authorized, we'll check userInRole later. Tr.audit(tc, "security.oauth20.error.authorization", request.getUserPrincipal().getName()); response.sendError(HttpServletResponse.SC_FORBIDDEN); return oauthResult; } return new OAuthResultImpl(OAuthResult.STATUS_OK, new AttributeList()); } @FFDCIgnore({ OAuth20BadParameterException.class }) private OAuthResult handleUserAuthentication(OAuthResult oauthResult, HttpServletRequest request, HttpServletResponse response, ServletContext servletContext, OAuth20Provider provider, String reqConsentNonce, AttributeList options, boolean autoauthz, boolean afterLogin) throws IOException, ServletException, OidcServerException { Prompt prompt = null; String[] scopesAttr = null; AttributeList attrs = null; if (oauthResult != null) { attrs = oauthResult.getAttributeList(); scopesAttr = attrs.getAttributeValuesByName(OAuth20Constants.SCOPE); if (options != null) { setTokenHintAttributes(options, attrs); } String[] validResources = attrs.getAttributeValuesByName(OAuth20Constants.RESOURCE); if (validResources != null) { options.setAttribute(OAuth20Constants.RESOURCE, OAuth20Constants.ATTRTYPE_PARAM_OAUTH, validResources); } } // Per section 4.1.2.1 of the OAuth 2.0 spec (RFC6749), the state parameter must be included in any error response if it was // originally provided in the request. Adding it to the attribute list here will ensure it is propagated to any failure response. String[] stateParams = request.getParameterValues(OAuth20Constants.STATE); if (stateParams != null) { if (attrs == null) { attrs = new AttributeList(); } attrs.setAttribute(OAuth20Constants.STATE, OAuth20Constants.ATTRTYPE_PARAM_QUERY, stateParams); } boolean isOpenId = false; if (scopesAttr != null) { for (String scope : scopesAttr) { if (OIDCConstants.SCOPE_OPENID.equals(scope)) { isOpenId = true; break; } } } if (isOpenId) { // if id_token_hint exists and user is already logged in, compare... OAuthResultImpl result = validateIdTokenHintIfPresent(attrs, request); if (result != null) { return result; } } prompt = new Prompt(request); if (request.getUserPrincipal() == null || (prompt.hasLogin() && !afterLogin)) { // authenticate user if not done yet if (tc.isDebugEnabled()) { Tr.debug(tc, "Authenticate user if not done yet"); } oauthResult = userAuthentication.handleAuthenticationWithOAuthResult(provider, request, response, prompt, securityServiceRef, servletContext, OAuth20EndpointServices.AUTHENTICATED, oauthResult); } if (request.getUserPrincipal() == null) { // must be redirect return oauthResult; } else if (CookieHelper.getCookieValue(request.getCookies(), ReferrerURLCookieHandler.CUSTOM_RELOGIN_URL_COOKIENAME) != null) { ReferrerURLCookieHandler handler = WebAppSecurityCollaboratorImpl.getGlobalWebAppSecurityConfig().createReferrerURLCookieHandler(); // GM 2017.05.31 // ReferrerURLCookieHandler handler = new ReferrerURLCookieHandler(WebAppSecurityCollaboratorImpl.getGlobalWebAppSecurityConfig()); handler.invalidateReferrerURLCookie(request, response, ReferrerURLCookieHandler.CUSTOM_RELOGIN_URL_COOKIENAME); } if (!request.isUserInRole(AUTHENTICATED) && !request.isUserInRole(OAuth20Constants.TOKEN_MANAGER_ROLE)) { // must be authorized Tr.audit(tc, "security.oauth20.error.authorization", request.getUserPrincipal().getName()); response.sendError(HttpServletResponse.SC_FORBIDDEN); return oauthResult; } if (reqConsentNonce != null && !consent.isNonceValid(request, reqConsentNonce)) { // nonce must be valid if has one consent.handleNonceError(request, response); return oauthResult; } String clientId = getClientId(request); String[] reducedScopes = null; try { reducedScopes = clientAuthorization.getReducedScopes(provider, request, clientId, true); } catch (Exception e1) { if (tc.isDebugEnabled()) { Tr.debug(tc, "Caught exception, so setting reduced scopes to null. Exception was: " + e1); } reducedScopes = null; } boolean preAuthzed = false; if (reqConsentNonce == null) { try { preAuthzed = clientAuthorization.isPreAuthorizedScope(provider, clientId, reducedScopes); } catch (Exception e) { preAuthzed = false; } } // Handle consent if (!autoauthz && !preAuthzed && reqConsentNonce == null && !consent.isCachedAndValid(oauthResult, provider, request, response)) { if (prompt.hasNone()) { // Prompt includes "none," however authorization has not been obtained or cached; return error oauthResult = prompt.errorConsentRequired(attrs); } else { // ask user for approval if not auto authorized, or not approved Nonce nonce = consent.setNonce(request); if (tc.isDebugEnabled()) { Tr.debug(tc, "_SSO OP redirecting for consent"); } consent.renderConsentForm(request, response, provider, clientId, nonce, oauthResult.getAttributeList(), servletContext); } return oauthResult; } if (reachedTokenLimit(provider, request)) { return createTokenLimitResult(attrs, request, clientId); } if (request.getAttribute(OAuth20Constants.OIDC_REQUEST_OBJECT_ATTR_NAME) != null) { // Ensure that the reduced scopes list is not empty oauthResult = clientAuthorization.checkForEmptyScopeSetAfterConsent(reducedScopes, oauthResult, request, provider, clientId); if (oauthResult != null && oauthResult.getStatus() != OAuthResult.STATUS_OK) { response.setStatus(HttpServletResponse.SC_FOUND); return oauthResult; } } // getBack the resource. better double check it OidcBaseClient client; try { client = OAuth20ProviderUtils.getOidcOAuth20Client(provider, clientId); OAuth20ProviderUtils.validateResource(request, options, client); } catch (OAuth20BadParameterException e) { // some exceptions need to handled separately WebUtils.throwOidcServerException(request, e); } catch (OAuth20Exception e) { WebUtils.throwOidcServerException(request, e); } if (options != null) { options.setAttribute(OAuth20Constants.SCOPE, OAuth20Constants.ATTRTYPE_RESPONSE_ATTRIBUTE, reducedScopes); } if (provider.isTrackOAuthClients()) { OAuthClientTracker clientTracker = new OAuthClientTracker(request, response, provider); clientTracker.trackOAuthClient(clientId); } consent.handleConsent(provider, request, prompt, clientId); getExternalClaimsFromWSSubject(request, options); oauthResult = provider.processAuthorization(request, response, options); return oauthResult; } /** * Secure registration services with BASIC Auth and validating against the required role. * * @param provider * @param request * @param response * @param servletContext * @param requiredRole - user must be in this role. * @param fallbacktoBasicAuth - if false, if there is no cookie on the request, then no basic auth challenge will be sent back to browser. * @throws OidcServerException */ @FFDCIgnore({ OidcServerException.class }) private void secureEndpointServices(OAuth20Provider provider, HttpServletRequest request, HttpServletResponse response, ServletContext servletContext, String requiredRole, boolean fallbackToBasicAuth) throws OidcServerException { try { userAuthentication.handleBasicAuthenticationWithRequiredRole(provider, request, response, securityServiceRef, servletContext, requiredRole, fallbackToBasicAuth); } catch (OidcServerException e) { if (fallbackToBasicAuth) { if (e.getHttpStatus() == HttpServletResponse.SC_UNAUTHORIZED) { response.setHeader(RegistrationEndpointServices.HDR_WWW_AUTHENTICATE, RegistrationEndpointServices.UNAUTHORIZED_HEADER_VALUE); } } throw e; } } @FFDCIgnore({ OAuth20BadParameterException.class }) public void processTokenRequest(OAuth20Provider provider, HttpServletRequest request, HttpServletResponse response) throws ServletException, OidcServerException { String clientId = (String) request.getAttribute("authenticatedClient"); try { // checking resource OidcBaseClient client = OAuth20ProviderUtils.getOidcOAuth20Client(provider, clientId); if (client == null || !client.isEnabled()) { throw new OidcServerException("security.oauth20.error.invalid.client", OIDCConstants.ERROR_INVALID_CLIENT_METADATA, HttpServletResponse.SC_BAD_REQUEST); } OAuth20ProviderUtils.validateResource(request, null, client); } catch (OAuth20BadParameterException e) { // some exceptions need to handled separately WebUtils.throwOidcServerException(request, e); } catch (OAuth20Exception e) { WebUtils.throwOidcServerException(request, e); } OAuthResult result = clientAuthorization.validateAndHandle2LegsScope(provider, request, response, clientId); if (result.getStatus() == OAuthResult.STATUS_OK) { result = provider.processTokenRequest(clientId, request, response); } if (result.getStatus() != OAuthResult.STATUS_OK) { OAuth20TokenRequestExceptionHandler handler = new OAuth20TokenRequestExceptionHandler(); handler.handleResultException(request, response, result); } } /** * Get the access token from the request's token parameter and look it up in * the token cache. * * If the access token is found in the cache return status 200 and a JSON object. * * If the token is not found or the request had errors return status 400. * * @param provider * @param request * @param response * @throws OidcServerException * @throws IOException */ public void introspect(OAuth20Provider provider, HttpServletRequest request, HttpServletResponse response) throws OidcServerException, IOException { TokenIntrospect tokenIntrospect = new TokenIntrospect(); tokenIntrospect.introspect(provider, request, response); } /** * Revoke the provided token by removing it from the cache * * If the access token is found in the cache remove it from the cache * and return status 200. * * @param provider * @param request * @param response */ public void revoke(OAuth20Provider provider, HttpServletRequest request, HttpServletResponse response) { try { String tokenString = request.getParameter(com.ibm.ws.security.oauth20.util.UtilConstants.TOKEN); if (tokenString == null) { // send 400 per OAuth Token revocation spec WebUtils.sendErrorJSON(response, HttpServletResponse.SC_BAD_REQUEST, Constants.ERROR_CODE_INVALID_REQUEST, null); // invalid_request return; } String tokenLookupStr = tokenString; OAuth20Token token = null; boolean isAppPasswordOrToken = false; if (OidcOAuth20Util.isJwtToken(tokenString)) { tokenLookupStr = com.ibm.ws.security.oauth20.util.HashUtils.digest(tokenString); } else if (tokenString.length() == (provider.getAccessTokenLength() + 2)) { // app-token String encode = provider.getAccessTokenEncoding(); if (OAuth20Constants.PLAIN_ENCODING.equals(encode)) { // must be app-password or app-token tokenLookupStr = EndpointUtils.computeTokenHash(tokenString); } else { tokenLookupStr = EndpointUtils.computeTokenHash(tokenString, encode); } isAppPasswordOrToken = true; } if (isAppPasswordOrToken) { token = provider.getTokenCache().getByHash(tokenLookupStr); } else { token = provider.getTokenCache().get(tokenLookupStr); } boolean isAppPassword = false; if (token != null && OAuth20Constants.APP_PASSWORD.equals(token.getGrantType())) { isAppPassword = true; Tr.error(tc, "security.oauth20.apppwtok.revoke.disallowed", new Object[] {}); } if (token == null) { // send 200 per OAuth Token revocation spec response.setStatus(HttpServletResponse.SC_OK); if (tc.isDebugEnabled()) { Tr.debug(tc, "token " + tokenString + " not in cache or wrong token type, return"); } return; } if (tc.isDebugEnabled()) { Tr.debug(tc, "token type: " + token.getType()); } ClientAuthnData clientAuthData = new ClientAuthnData(request, response); if (clientAuthData.hasAuthnData() && clientAuthData.getUserName().equals(token.getClientId()) == true) { if (!isAppPassword && ((token.getType().equals(OAuth20Constants.TOKENTYPE_AUTHORIZATION_GRANT) && token.getSubType().equals(OAuth20Constants.SUBTYPE_REFRESH_TOKEN)) || token.getType().equals(OAuth20Constants.TOKENTYPE_ACCESS_TOKEN))) { // Revoke the token by removing it from the cache if (tc.isDebugEnabled()) { OAuth20Token theToken = provider.getTokenCache().get(tokenLookupStr); String buf = (theToken != null) ? "is in the cache" : "is not in the cache"; Tr.debug(tc, "token " + tokenLookupStr + " " + buf + ", calling remove"); } if (isAppPasswordOrToken) { provider.getTokenCache().removeByHash(tokenLookupStr); } else { provider.getTokenCache().remove(tokenLookupStr); } if (token.getSubType().equals(OAuth20Constants.SUBTYPE_REFRESH_TOKEN)) { removeAssociatedAccessTokens(request, provider, token); } response.setStatus(HttpServletResponse.SC_OK); } else { // Unsupported token type, send 400 per RFC7009 OAuth Token revocation spec WebUtils.sendErrorJSON(response, HttpServletResponse.SC_BAD_REQUEST, Constants.ERROR_CODE_UNSUPPORTED_TOKEN_TYPE, null); } } else { // client is not authorized. send 400 per RFC6749 5.2 OAuth Token revocation spec String defaultMsg = "CWWKS1406E: The revoke request had an invalid client credential. The request URI was {" + request.getRequestURI() + "}."; String errorMsg = TraceNLS.getFormattedMessage(this.getClass(), MESSAGE_BUNDLE, "OAUTH_INVALID_CLIENT", new Object[] { "revoke", request.getRequestURI() }, defaultMsg); WebUtils.sendErrorJSON(response, HttpServletResponse.SC_BAD_REQUEST, Constants.ERROR_CODE_INVALID_CLIENT, errorMsg); } } catch (OAuth20DuplicateParameterException e) { // Duplicate parameter found in request WebUtils.sendErrorJSON(response, HttpServletResponse.SC_BAD_REQUEST, Constants.ERROR_CODE_INVALID_REQUEST, e.getMessage()); } catch (Exception e) { if (tc.isDebugEnabled()) { Tr.debug(tc, "Internal error processing token revoke request", e); } try { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } catch (IOException ioe) { if (tc.isDebugEnabled()) { Tr.debug(tc, "Internal error process token introspect revoke error", ioe); } } } } /** * For OpenidConnect, when a refresh token is revoked, also delete all access tokens that have become associated with it. * (Each time a refresh token is submitted for a new one, the prior access tokens become associated with the new refresh token) * @param request * @param provider * @param refreshToken * @throws Exception */ private void removeAssociatedAccessTokens(HttpServletRequest request, OAuth20Provider provider, OAuth20Token refreshToken) throws Exception { String contextPath = request.getContextPath(); if (contextPath != null && !contextPath.equals("/oidc")) { // if this is for oauth, return. Oauth's persistence code doesn't support this token association. // and we only wanted revocation for oidc, we wanted to leave oauth alone. if (tc.isDebugEnabled()) { Tr.debug(tc, "not oidc, returning"); } return; } if (!provider.getRevokeAccessTokensWithRefreshTokens()) { if (tc.isDebugEnabled()) { Tr.debug(tc, "provider prop revokeAccessTokensWithRefreshTokens is false, returning"); } return; } String username = refreshToken.getUsername(); String clientId = refreshToken.getClientId(); String refreshTokenId = refreshToken.getId(); OAuth20EnhancedTokenCache cache = provider.getTokenCache(); Collection<OAuth20Token> ctokens = cache.getAllUserTokens(username); for (OAuth20Token ctoken : ctokens) { boolean nullGuard = (cache != null && ctoken.getType() != null && clientId != null && ctoken.getClientId() != null && ctoken.getId() != null); if (nullGuard && OAuth20Constants.TOKENTYPE_ACCESS_TOKEN.equals(ctoken.getType()) && clientId.equals(ctoken.getClientId()) && refreshTokenId.equals(((OAuth20TokenImpl) ctoken).getRefreshTokenKey())) { if (tc.isDebugEnabled()) { Tr.debug(tc, "removing token: " + ctoken.getId()); } cache.remove(ctoken.getId()); } } } protected void checkHttpsRequirement(HttpServletRequest request, HttpServletResponse response, OAuth20Provider provider) throws IOException { String url = request.getRequestURL().toString(); if (provider.isHttpsRequired()) { if (tc.isDebugEnabled()) { Tr.debug(tc, "Checking if URL starts with https: " + url); } if (url != null && !url.startsWith("https")) { Tr.error(tc, "security.oauth20.error.wrong.http.scheme", new Object[] { url }); response.sendError(HttpServletResponse.SC_NOT_FOUND, Tr.formatMessage(tc, "security.oauth20.error.wrong.http.scheme", new Object[] { url })); } } } /** * Determines if this user hit the token limit for the user / client combination * * @param provider * @param request * @return */ protected boolean reachedTokenLimit(OAuth20Provider provider, HttpServletRequest request) { String userName = getUserName(request); String clientId = getClientId(request); long limit = provider.getClientTokenCacheSize(); if (limit > 0) { long numtokens = provider.getTokenCache().getNumTokens(userName, clientId); if (numtokens >= limit) { Tr.error(tc, "security.oauth20.token.limit.error", new Object[] { userName, clientId, limit }); return true; } } return false; } private OAuth20Request getAuth20Request(HttpServletRequest request, HttpServletResponse response) throws IOException { OAuth20Request oauth20Request = (OAuth20Request) request.getAttribute(OAuth20Constants.OAUTH_REQUEST_OBJECT_ATTR_NAME); if (oauth20Request == null) { String errorMsg = TraceNLS.getFormattedMessage(this.getClass(), MESSAGE_BUNDLE, "OAUTH_REQUEST_ATTRIBUTE_MISSING", new Object[] { request.getRequestURI(), OAuth20Constants.OAUTH_REQUEST_OBJECT_ATTR_NAME }, "CWWKS1412E: The request endpoint {0} does not have attribute {1}."); Tr.error(tc, errorMsg); response.sendError(HttpServletResponse.SC_NOT_FOUND); } return oauth20Request; } private OAuth20Provider getProvider(HttpServletResponse response, OAuth20Request oauth20Request) throws IOException { OAuth20Provider provider = ProvidersService.getOAuth20Provider(oauth20Request.getProviderName()); if (provider == null) { String errorMsg = TraceNLS.getFormattedMessage(this.getClass(), MESSAGE_BUNDLE, "OAUTH_PROVIDER_OBJECT_NULL", new Object[] { oauth20Request.getProviderName(), OAuth20Constants.OAUTH_REQUEST_OBJECT_ATTR_NAME }, "CWWKS1413E: The OAuth20Provider object is null for OAuth provider {0}."); Tr.error(tc, errorMsg); response.sendError(HttpServletResponse.SC_NOT_FOUND); } return provider; } private String getReqConsentNonce(HttpServletRequest request) { return request.getParameter(ATTR_NONCE); } private String getUserName(HttpServletRequest request) { return request.getUserPrincipal().getName(); } private String getClientId(HttpServletRequest request) { return request.getParameter(OAuth20Constants.CLIENT_ID); } /* returns whether login form had been presented */ protected boolean isAfterLogin(HttpServletRequest request) { boolean output = false; HttpSession session = request.getSession(false); if (session != null) { if (session.getAttribute(Constants.ATTR_AFTERLOGIN) != null) { session.removeAttribute(Constants.ATTR_AFTERLOGIN); output = true; } } return output; } /** * @return */ @SuppressWarnings("unchecked") public Map<String, String[]> getExternalClaimsFromWSSubject(HttpServletRequest request, AttributeList options) { final String methodName = "getExternalClaimsFromWSSubject"; try { String externalClaimNames = options.getAttributeValueByName(OAuth20Constants.EXTERNAL_CLAIM_NAMES); if (tc.isDebugEnabled()) Tr.debug(tc, methodName + " externalClamiNames:" + externalClaimNames); if (externalClaimNames != null) { Map<String, String[]> map2 = (Map<String, String[]>) getFromWSSubject(OAuth20Constants.EXTERNAL_MEDIATION); if (map2 != null && map2.size() > 0) { Set<Entry<String, String[]>> entries = map2.entrySet(); for (Entry<String, String[]> entry : entries) { options.setAttribute(entry.getKey(), OAuth20Constants.EXTERNAL_MEDIATION, entry.getValue()); } } // get the external claims Map<String, String[]> map = (Map<String, String[]>) getFromWSSubject(OAuth20Constants.EXTERNAL_CLAIMS); if (tc.isDebugEnabled()) Tr.debug(tc, methodName + " externalClaims:" + map); if (map == null) return null; // filter properties by externalClaimNames StringTokenizer strTokenizer = new StringTokenizer(externalClaimNames, ", "); while (strTokenizer.hasMoreTokens()) { String key = strTokenizer.nextToken(); String[] values = map.get(key); if (tc.isDebugEnabled()) Tr.debug(tc, methodName + " key:" + key + " values:'" + OAuth20Util.arrayToSpaceString(values) + "'"); if (values != null && values.length > 0) { options.setAttribute(OAuth20Constants.EXTERNAL_CLAIMS_PREFIX + key, OAuth20Constants.EXTERNAL_CLAIMS, values); } } return map; } } catch (WSSecurityException e) { if (tc.isDebugEnabled()) Tr.debug(tc, methodName + " failed. Nothing changed. WSSecurityException:" + e); } return null; } /** * @param externalClaims * @return */ private Object getFromWSSubject(String externalClaims) throws WSSecurityException { Subject runAsSubject = WSSubject.getRunAsSubject(); Object obj = null; try { Set<Object> publicCreds = runAsSubject.getPublicCredentials(); if (publicCreds != null && publicCreds.size() > 0) { Iterator<Object> publicCredIterator = publicCreds.iterator(); while (publicCredIterator.hasNext()) { Object cred = publicCredIterator.next(); if (cred != null && cred instanceof Hashtable) { @SuppressWarnings("rawtypes") Hashtable userCred = (Hashtable) cred; obj = userCred.get(externalClaims); if (obj != null) { if (tc.isDebugEnabled()) { Tr.debug(tc, "getFromWSSubject found:" + obj); } break; } } } } } catch (Exception e) { if (tc.isDebugEnabled()) { Tr.debug(tc, "Unable to match predefined cache key." + e); } } return obj; } /** * Check if the request contains an "error" parameter. If one is present and equals the OAuth 2.0 error type "access_denied", a message indicating the user likely canceled the request will be * logged and a failure result will be returned. * * @param request * @return A {@code OAuthResult} object initialized with AuthResult.FAILURE and 403 status code if an "error" parameter is present and equals "access_denied." Returns null otherwise. */ private OAuthResult checkForError(HttpServletRequest request) { OAuthResult result = null; String error = request.getParameter("error"); if (error != null && error.length() > 0 && OAuth20Exception.ACCESS_DENIED.equals(error)) { // User likely canceled the request String errorMsg = TraceNLS.getFormattedMessage(this.getClass(), MESSAGE_BUNDLE, "security.oauth20.request.denied", new Object[] {}, "CWOAU0067E: The request has been denied by the user, or another error occurred that resulted in denial of the request."); Tr.error(tc, errorMsg); OAuth20AccessDeniedException e = new OAuth20AccessDeniedException("security.oauth20.request.denied"); e.setHttpStatusCode(HttpServletResponse.SC_FORBIDDEN); AttributeList attrs = new AttributeList(); String value = request.getParameter(OAuth20Constants.RESPONSE_TYPE); if (value != null && value.length() > 0) { attrs.setAttribute(OAuth20Constants.RESPONSE_TYPE, OAuth20Constants.RESPONSE_TYPE, new String[] { value }); } value = getClientId(request); if (value != null && value.length() > 0) { attrs.setAttribute(OAuth20Constants.CLIENT_ID, OAuth20Constants.CLIENT_ID, new String[] { value }); } result = new OAuthResultImpl(OAuthResult.STATUS_FAILED, attrs, e); } return result; } /** * @param provider * @param responseJSON * @param accessToken * @param groupsOnly * @throws IOException */ protected Map<String, Object> getUserClaimsMap(UserClaims userClaims, boolean groupsOnly) throws IOException { // keep this method for OidcEndpointServices return TokenIntrospect.getUserClaimsMap(userClaims, groupsOnly); } protected UserClaims getUserClaimsObj(OAuth20Provider provider, OAuth20Token accessToken) throws IOException { // keep this method for OidcEndpointServices return TokenIntrospect.getUserClaimsObj(provider, accessToken); } }
Java
/******************************************************************************* * Copyright (c) 2005-2010, G. Weirich and Elexis * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * G. Weirich - initial implementation * D. Lutz - adapted for importing data from other databases * *******************************************************************************/ package ch.elexis.core.ui.wizards; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.wizard.WizardPage; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.List; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.forms.widgets.Form; import org.eclipse.ui.forms.widgets.FormToolkit; import org.eclipse.ui.forms.widgets.TableWrapData; import org.eclipse.ui.forms.widgets.TableWrapLayout; import ch.elexis.core.ui.UiDesk; import ch.elexis.core.ui.icons.ImageSize; import ch.elexis.core.ui.icons.Images; import ch.rgw.tools.JdbcLink; import ch.rgw.tools.StringTool; public class DBImportFirstPage extends WizardPage { List dbTypes; Text server, dbName; String defaultUser, defaultPassword; JdbcLink j = null; static final String[] supportedDB = new String[] { "mySQl", "PostgreSQL", "H2", "ODBC" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ }; static final int MYSQL = 0; static final int POSTGRESQL = 1; static final int ODBC = 3; static final int H2 = 2; public DBImportFirstPage(String pageName){ super(Messages.DBImportFirstPage_connection, Messages.DBImportFirstPage_typeOfDB, Images.IMG_LOGO.getImageDescriptor(ImageSize._75x66_TitleDialogIconSize)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ setMessage(Messages.DBImportFirstPage_selectType + Messages.DBImportFirstPage_enterNameODBC); //$NON-NLS-1$ setDescription(Messages.DBImportFirstPage_theDesrciption); //$NON-NLS-1$ } public DBImportFirstPage(String pageName, String title, ImageDescriptor titleImage){ super(pageName, title, titleImage); // TODO Automatisch erstellter Konstruktoren-Stub } public void createControl(Composite parent){ DBImportWizard wiz = (DBImportWizard) getWizard(); FormToolkit tk = UiDesk.getToolkit(); Form form = tk.createForm(parent); form.setText(Messages.DBImportFirstPage_Connection); //$NON-NLS-1$ Composite body = form.getBody(); body.setLayout(new TableWrapLayout()); tk.createLabel(body, Messages.DBImportFirstPage_EnterType); //$NON-NLS-1$ dbTypes = new List(body, SWT.BORDER); dbTypes.setItems(supportedDB); dbTypes.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e){ int it = dbTypes.getSelectionIndex(); switch (it) { case MYSQL: case POSTGRESQL: server.setEnabled(true); dbName.setEnabled(true); defaultUser = ""; //$NON-NLS-1$ defaultPassword = ""; //$NON-NLS-1$ break; case H2: server.setEnabled(false); dbName.setEnabled(true); defaultUser = "sa"; defaultPassword = ""; break; case ODBC: server.setEnabled(false); dbName.setEnabled(true); defaultUser = "sa"; //$NON-NLS-1$ defaultPassword = ""; //$NON-NLS-1$ break; default: break; } DBImportSecondPage sec = (DBImportSecondPage) getNextPage(); sec.name.setText(defaultUser); sec.pwd.setText(defaultPassword); } }); tk.adapt(dbTypes, true, true); tk.createLabel(body, Messages.DBImportFirstPage_serverAddress); //$NON-NLS-1$ server = tk.createText(body, "", SWT.BORDER); //$NON-NLS-1$ TableWrapData twr = new TableWrapData(TableWrapData.FILL_GRAB); server.setLayoutData(twr); tk.createLabel(body, Messages.DBImportFirstPage_databaseName); //$NON-NLS-1$ dbName = tk.createText(body, "", SWT.BORDER); //$NON-NLS-1$ TableWrapData twr2 = new TableWrapData(TableWrapData.FILL_GRAB); dbName.setLayoutData(twr2); if (wiz.preset != null && wiz.preset.length > 1) { int idx = StringTool.getIndex(supportedDB, wiz.preset[0]); if (idx < dbTypes.getItemCount()) { dbTypes.select(idx); } server.setText(wiz.preset[1]); dbName.setText(wiz.preset[2]); } setControl(form); } }
Java
/******************************************************************************* * Copyright (c) 2020 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package com.ibm.ws.install.internal; public class MavenRepository { private String name; private String repositoryUrl; private String userId; private String password; public MavenRepository(String name, String repositoryUrl, String userId, String password) { this.name = name; this.repositoryUrl = repositoryUrl; this.userId = userId; this.password = password; } public String getName(){ return name; } public String getRepositoryUrl() { return repositoryUrl; } public String getUserId() { return userId; } public String getPassword() { return password; } public String toString(){ return this.repositoryUrl; } }
Java
/******************************************************************************* * Copyright (c) 2011, 2016 Eurotech and/or its affiliates and others * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Eurotech - initial API and implementation * *******************************************************************************/ package org.eclipse.kapua.service.datastore.internal.model.query; import java.util.ArrayList; import org.eclipse.kapua.service.datastore.model.Storable; import org.eclipse.kapua.service.datastore.model.StorableListResult; @SuppressWarnings("serial") public class AbstractStorableListResult<E extends Storable> extends ArrayList<E> implements StorableListResult<E> { private Object nextKey; private Integer totalCount; public AbstractStorableListResult() { nextKey = null; totalCount = null; } public AbstractStorableListResult(Object nextKey) { this.nextKey = nextKey; this.totalCount = null; } public AbstractStorableListResult(Object nextKeyOffset, Integer totalCount) { this(nextKeyOffset); this.totalCount = totalCount; } public Object getNextKey() { return nextKey; } public Integer getTotalCount() { return totalCount; } }
Java
/******************************************************************************* * Copyright (c) 2017, 2020 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package com.ibm.ws.transaction.test; import org.junit.ClassRule; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; import com.ibm.ws.transaction.test.tests.EJBNewTxDBRoSTest; import com.ibm.ws.transaction.test.tests.EJBNewTxDBTest; import com.ibm.ws.transaction.test.tests.EJBNewTxRoSTest; import com.ibm.ws.transaction.test.tests.EJBNewTxTest; import componenttest.rules.repeater.FeatureReplacementAction; import componenttest.rules.repeater.JakartaEE9Action; import componenttest.rules.repeater.RepeatTests; @RunWith(Suite.class) @SuiteClasses({ EJBNewTxTest.class, EJBNewTxDBTest.class, EJBNewTxRoSTest.class, EJBNewTxDBRoSTest.class }) public class FATSuite { // Using the RepeatTests @ClassRule will cause all tests to be run twice. // First without any modifications, then again with all features upgraded to their EE8 equivalents. @ClassRule public static RepeatTests r = RepeatTests.withoutModification() .andWith(FeatureReplacementAction.EE8_FEATURES()) .andWith(new JakartaEE9Action()); }
Java
/** * Copyright (c) 2010-2021 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.loxone.internal.controls; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.openhab.core.library.types.StringType; /** * Test class for (@link LxControlTracker} * * @author Pawel Pieczul - initial contribution * */ public class LxControlTrackerTest extends LxControlTest { @BeforeEach public void setup() { setupControl("132aa43b-01d4-56ea-ffff403fb0c34b9e", "0b734138-037d-034e-ffff403fb0c34b9e", "0fe650c2-0004-d446-ffff504f9410790f", "Tracker Control"); } @Test public void testControlCreation() { testControlCreation(LxControlTracker.class, 1, 0, 1, 1, 1); } @Test public void testChannels() { testChannel("String", null, null, null, null, null, true, null); } @Test public void testLoxoneStateChanges() { for (int i = 0; i < 20; i++) { String s = new String(); for (int j = 0; j < i; j++) { for (char c = 'a'; c <= 'a' + j; c++) { s = s + c; } if (j != i - 1) { s = s + '|'; } } changeLoxoneState("entries", s); testChannelState(new StringType(s)); } } }
Java
package moCreatures.items; import net.minecraft.src.EntityPlayer; import net.minecraft.src.Item; import net.minecraft.src.ItemStack; import net.minecraft.src.World; import moCreatures.entities.EntitySharkEgg; // Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) braces deadcode public class ItemSharkEgg extends Item { public ItemSharkEgg(int i) { super(i); maxStackSize = 16; } public ItemStack onItemRightClick(ItemStack itemstack, World world, EntityPlayer entityplayer) { itemstack.stackSize--; if(!world.singleplayerWorld) { EntitySharkEgg entitysharkegg = new EntitySharkEgg(world); entitysharkegg.setPosition(entityplayer.posX, entityplayer.posY, entityplayer.posZ); world.entityJoinedWorld(entitysharkegg); entitysharkegg.motionY += world.rand.nextFloat() * 0.05F; entitysharkegg.motionX += (world.rand.nextFloat() - world.rand.nextFloat()) * 0.3F; entitysharkegg.motionZ += (world.rand.nextFloat() - world.rand.nextFloat()) * 0.3F; } return itemstack; } }
Java
/******************************************************************************* * Copyright (C) 2008, 2009 Robin Rosenberg <robin.rosenberg@dewire.com> * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.eclipse.egit.ui.internal.decorators; import java.io.IOException; import java.util.Map; import java.util.WeakHashMap; import org.eclipse.core.resources.IResource; import org.eclipse.egit.core.GitProvider; import org.eclipse.egit.core.project.RepositoryMapping; import org.eclipse.egit.ui.Activator; import org.eclipse.egit.ui.UIText; import org.eclipse.egit.ui.internal.CompareUtils; import org.eclipse.egit.ui.internal.trace.GitTraceLocation; import org.eclipse.jface.text.Document; import org.eclipse.jgit.events.ListenerHandle; import org.eclipse.jgit.events.RefsChangedEvent; import org.eclipse.jgit.events.RefsChangedListener; import org.eclipse.jgit.lib.AnyObjectId; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.ObjectLoader; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.revwalk.RevTree; import org.eclipse.jgit.revwalk.RevWalk; import org.eclipse.jgit.treewalk.TreeWalk; import org.eclipse.osgi.util.NLS; import org.eclipse.team.core.RepositoryProvider; class GitDocument extends Document implements RefsChangedListener { private final IResource resource; private ObjectId lastCommit; private ObjectId lastTree; private ObjectId lastBlob; private ListenerHandle myRefsChangedHandle; static Map<GitDocument, Repository> doc2repo = new WeakHashMap<GitDocument, Repository>(); static GitDocument create(final IResource resource) throws IOException { if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation.getTrace().trace( GitTraceLocation.QUICKDIFF.getLocation(), "(GitDocument) create: " + resource); //$NON-NLS-1$ GitDocument ret = null; if (RepositoryProvider.getProvider(resource.getProject()) instanceof GitProvider) { ret = new GitDocument(resource); ret.populate(); final Repository repository = ret.getRepository(); if (repository != null) ret.myRefsChangedHandle = repository.getListenerList() .addRefsChangedListener(ret); } return ret; } private GitDocument(IResource resource) { this.resource = resource; GitDocument.doc2repo.put(this, getRepository()); } private void setResolved(final AnyObjectId commit, final AnyObjectId tree, final AnyObjectId blob, final String value) { lastCommit = commit != null ? commit.copy() : null; lastTree = tree != null ? tree.copy() : null; lastBlob = blob != null ? blob.copy() : null; set(value); if (blob != null) if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation .getTrace() .trace( GitTraceLocation.QUICKDIFF.getLocation(), "(GitDocument) resolved " + resource + " to " + lastBlob + " in " + lastCommit + "/" + lastTree); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ else if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation.getTrace().trace( GitTraceLocation.QUICKDIFF.getLocation(), "(GitDocument) unresolved " + resource); //$NON-NLS-1$ } void populate() throws IOException { if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation.getTrace().traceEntry( GitTraceLocation.QUICKDIFF.getLocation(), resource); TreeWalk tw = null; RevWalk rw = null; try { RepositoryMapping mapping = RepositoryMapping.getMapping(resource); if (mapping == null) { setResolved(null, null, null, ""); //$NON-NLS-1$ return; } final String gitPath = mapping.getRepoRelativePath(resource); final Repository repository = mapping.getRepository(); String baseline = GitQuickDiffProvider.baseline.get(repository); if (baseline == null) baseline = Constants.HEAD; ObjectId commitId = repository.resolve(baseline); if (commitId != null) { if (commitId.equals(lastCommit)) { if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation.getTrace().trace( GitTraceLocation.QUICKDIFF.getLocation(), "(GitDocument) already resolved"); //$NON-NLS-1$ return; } } else { String msg = NLS.bind(UIText.GitDocument_errorResolveQuickdiff, new Object[] { baseline, resource, repository }); Activator.logError(msg, new Throwable()); setResolved(null, null, null, ""); //$NON-NLS-1$ return; } rw = new RevWalk(repository); RevCommit baselineCommit; try { baselineCommit = rw.parseCommit(commitId); } catch (IOException err) { String msg = NLS .bind(UIText.GitDocument_errorLoadCommit, new Object[] { commitId, baseline, resource, repository }); Activator.logError(msg, err); setResolved(null, null, null, ""); //$NON-NLS-1$ return; } RevTree treeId = baselineCommit.getTree(); if (treeId.equals(lastTree)) { if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation.getTrace().trace( GitTraceLocation.QUICKDIFF.getLocation(), "(GitDocument) already resolved"); //$NON-NLS-1$ return; } tw = TreeWalk.forPath(repository, gitPath, treeId); if (tw == null) { if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation .getTrace() .trace( GitTraceLocation.QUICKDIFF.getLocation(), "(GitDocument) resource " + resource + " not found in " + treeId + " in " + repository + ", baseline=" + baseline); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ setResolved(null, null, null, ""); //$NON-NLS-1$ return; } ObjectId id = tw.getObjectId(0); if (id.equals(ObjectId.zeroId())) { setResolved(null, null, null, ""); //$NON-NLS-1$ String msg = NLS .bind(UIText.GitDocument_errorLoadTree, new Object[] { treeId.getName(), baseline, resource, repository }); Activator.logError(msg, new Throwable()); setResolved(null, null, null, ""); //$NON-NLS-1$ return; } if (!id.equals(lastBlob)) { if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation.getTrace().trace( GitTraceLocation.QUICKDIFF.getLocation(), "(GitDocument) compareTo: " + baseline); //$NON-NLS-1$ ObjectLoader loader = repository.open(id, Constants.OBJ_BLOB); byte[] bytes = loader.getBytes(); String charset; charset = CompareUtils.getResourceEncoding(resource); // Finally we could consider validating the content with respect // to the content. We don't do that here. String s = new String(bytes, charset); setResolved(commitId, treeId, id, s); if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation .getTrace() .trace(GitTraceLocation.QUICKDIFF.getLocation(), "(GitDocument) has reference doc, size=" + s.length() + " bytes"); //$NON-NLS-1$ //$NON-NLS-2$ } else { if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation.getTrace().trace( GitTraceLocation.QUICKDIFF.getLocation(), "(GitDocument) already resolved"); //$NON-NLS-1$ } } finally { if (tw != null) tw.release(); if (rw != null) rw.release(); if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation.getTrace().traceExit( GitTraceLocation.QUICKDIFF.getLocation()); } } void dispose() { if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation.getTrace().trace( GitTraceLocation.QUICKDIFF.getLocation(), "(GitDocument) dispose: " + resource); //$NON-NLS-1$ doc2repo.remove(this); if (myRefsChangedHandle != null) { myRefsChangedHandle.remove(); myRefsChangedHandle = null; } } public void onRefsChanged(final RefsChangedEvent e) { try { populate(); } catch (IOException e1) { Activator.logError(UIText.GitDocument_errorRefreshQuickdiff, e1); } } private Repository getRepository() { RepositoryMapping mapping = RepositoryMapping.getMapping(resource); return (mapping != null) ? mapping.getRepository() : null; } /** * A change occurred to a repository. Update any GitDocument instances * referring to such repositories. * * @param repository * Repository which changed * @throws IOException */ static void refreshRelevant(final Repository repository) throws IOException { for (Map.Entry<GitDocument, Repository> i : doc2repo.entrySet()) { if (i.getValue() == repository) { i.getKey().populate(); } } } }
Java
/******************************************************************************* * Copyright (c) 2017 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ // Generated from C:\SIB\Code\WASX.SIB\dd\SIB\ws\code\sib.mfp.impl\src\com\ibm\ws\sib\mfp\schema\JsHdrSchema.schema: do not edit directly package com.ibm.ws.sib.mfp.schema; import com.ibm.ws.sib.mfp.jmf.impl.JSchema; public final class JsHdrAccess { public final static JSchema schema = new JsHdrSchema(); public final static int DISCRIMINATOR = 0; public final static int ARRIVALTIMESTAMP = 1; public final static int SYSTEMMESSAGESOURCEUUID = 2; public final static int SYSTEMMESSAGEVALUE = 3; public final static int SECURITYUSERID = 4; public final static int SECURITYSENTBYSYSTEM = 5; public final static int MESSAGETYPE = 6; public final static int SUBTYPE = 7; public final static int HDR2 = 8; public final static int API = 10; public final static int IS_API_EMPTY = 0; public final static int IS_API_DATA = 1; public final static int API_DATA = 9; }
Java
///******************************************************************************* // * Copyright (c) 2015, 2016 EfficiOS Inc., Alexandre Montplaisir // * // * All rights reserved. This program and the accompanying materials are // * made available under the terms of the Eclipse Public License v1.0 which // * accompanies this distribution, and is available at // * http://www.eclipse.org/legal/epl-v10.html // *******************************************************************************/ // //package org.lttng.scope.lami.ui.viewers; // //import org.eclipse.jface.viewers.TableViewer; //import org.eclipse.swt.SWT; //import org.eclipse.swt.widgets.Composite; //import org.lttng.scope.lami.core.module.LamiChartModel; //import org.lttng.scope.lami.ui.views.LamiReportViewTabPage; // ///** // * Common interface for all Lami viewers. // * // * @author Alexandre Montplaisir // */ //public interface ILamiViewer { // // /** // * Dispose the viewer widget. // */ // void dispose(); // // /** // * Factory method to create a new Table viewer. // * // * @param parent // * The parent composite // * @param page // * The {@link LamiReportViewTabPage} parent page // * @return The new viewer // */ // static ILamiViewer createLamiTable(Composite parent, LamiReportViewTabPage page) { // TableViewer tableViewer = new TableViewer(parent, SWT.FULL_SELECTION | SWT.MULTI | SWT.VIRTUAL); // return new LamiTableViewer(tableViewer, page); // } // // /** // * Factory method to create a new chart viewer. The chart type is specified // * by the 'chartModel' parameter. // * // * @param parent // * The parent composite // * @param page // * The {@link LamiReportViewTabPage} parent page // * @param chartModel // * The information about the chart to display // * @return The new viewer // */ // static ILamiViewer createLamiChart(Composite parent, LamiReportViewTabPage page, LamiChartModel chartModel) { // switch (chartModel.getChartType()) { // case BAR_CHART: // return new LamiBarChartViewer(parent, page, chartModel); // case XY_SCATTER: // return new LamiScatterViewer(parent, page, chartModel); // case PIE_CHART: // default: // throw new UnsupportedOperationException("Unsupported chart type: " + chartModel.toString()); //$NON-NLS-1$ // } // } //}
Java
/******************************************************************************* * Copyright (c) 2017, 2021 Red Hat Inc and others * * This program and the accompanying materials are made * available under the terms of the Eclipse Public License 2.0 * which is available at https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * Red Hat Inc - initial API and implementation *******************************************************************************/ package org.eclipse.kapua.kura.simulator.app.deploy; import org.eclipse.kapua.kura.simulator.payload.Metric; import org.eclipse.kapua.kura.simulator.payload.Optional; public class DeploymentUninstallPackageRequest { @Metric("dp.name") private String name; @Metric("dp.version") private String version; @Metric("job.id") private long jobId; @Optional @Metric("dp.reboot") private Boolean reboot; @Optional @Metric("dp.reboot.delay") private Integer rebootDelay; public String getName() { return name; } public void setName(final String name) { this.name = name; } public String getVersion() { return version; } public void setVersion(final String version) { this.version = version; } public long getJobId() { return jobId; } public void setJobId(final long jobId) { this.jobId = jobId; } public Boolean getReboot() { return reboot; } public void setReboot(final Boolean reboot) { this.reboot = reboot; } public Integer getRebootDelay() { return rebootDelay; } public void setRebootDelay(final Integer rebootDelay) { this.rebootDelay = rebootDelay; } }
Java
/** * Copyright (c) 2020 Bosch.IO GmbH and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.eclipse.hawkbit.ui.common.tagdetails; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Optional; import java.util.Set; import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.ui.common.data.proxies.ProxyTag; import org.eclipse.hawkbit.ui.common.tagdetails.TagPanelLayout.TagAssignmentListener; import org.eclipse.hawkbit.ui.utils.UIComponentIdProvider; import org.eclipse.hawkbit.ui.utils.UIMessageIdProvider; import org.eclipse.hawkbit.ui.utils.VaadinMessageSource; import com.google.common.collect.Sets; import com.vaadin.ui.ComboBox; import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.themes.ValoTheme; /** * Combobox that lists all available Tags that can be assigned to a * {@link Target} or {@link DistributionSet}. */ public class TagAssignementComboBox extends HorizontalLayout { private static final long serialVersionUID = 1L; private final Collection<ProxyTag> allAssignableTags; private final transient Set<TagAssignmentListener> listeners = Sets.newConcurrentHashSet(); private final ComboBox<ProxyTag> assignableTagsComboBox; private final boolean readOnlyMode; /** * Constructor. * * @param i18n * the i18n * @param readOnlyMode * if true the combobox will be disabled so no assignment can be * done. */ TagAssignementComboBox(final VaadinMessageSource i18n, final boolean readOnlyMode) { this.readOnlyMode = readOnlyMode; setWidth("100%"); this.assignableTagsComboBox = getAssignableTagsComboBox( i18n.getMessage(UIMessageIdProvider.TOOLTIP_SELECT_TAG)); this.allAssignableTags = new HashSet<>(); this.assignableTagsComboBox.setItems(allAssignableTags); addComponent(assignableTagsComboBox); } private ComboBox<ProxyTag> getAssignableTagsComboBox(final String description) { final ComboBox<ProxyTag> tagsComboBox = new ComboBox<>(); tagsComboBox.setId(UIComponentIdProvider.TAG_SELECTION_ID); tagsComboBox.setDescription(description); tagsComboBox.addStyleName(ValoTheme.COMBOBOX_TINY); tagsComboBox.setEnabled(!readOnlyMode); tagsComboBox.setWidth("100%"); tagsComboBox.setEmptySelectionAllowed(true); tagsComboBox.setItemCaptionGenerator(ProxyTag::getName); tagsComboBox.addValueChangeListener(event -> assignTag(event.getValue())); return tagsComboBox; } private void assignTag(final ProxyTag tagData) { if (tagData == null || readOnlyMode) { return; } allAssignableTags.remove(tagData); assignableTagsComboBox.clear(); assignableTagsComboBox.getDataProvider().refreshAll(); notifyListenersTagAssigned(tagData); } /** * Initializes the Combobox with all assignable tags. * * @param assignableTags * assignable tags */ void initializeAssignableTags(final List<ProxyTag> assignableTags) { allAssignableTags.addAll(assignableTags); assignableTagsComboBox.getDataProvider().refreshAll(); } /** * Removes all Tags from Combobox. */ void removeAllTags() { allAssignableTags.clear(); assignableTagsComboBox.clear(); assignableTagsComboBox.getDataProvider().refreshAll(); } /** * Adds an assignable Tag to the combobox. * * @param tagData * the data of the Tag */ void addAssignableTag(final ProxyTag tagData) { if (tagData == null) { return; } allAssignableTags.add(tagData); assignableTagsComboBox.getDataProvider().refreshAll(); } /** * Updates an assignable Tag in the combobox. * * @param tagData * the data of the Tag */ void updateAssignableTag(final ProxyTag tagData) { if (tagData == null) { return; } findAssignableTagById(tagData.getId()).ifPresent(tagToUpdate -> updateAssignableTag(tagToUpdate, tagData)); } private Optional<ProxyTag> findAssignableTagById(final Long id) { return allAssignableTags.stream().filter(tag -> tag.getId().equals(id)).findAny(); } private void updateAssignableTag(final ProxyTag oldTag, final ProxyTag newTag) { allAssignableTags.remove(oldTag); allAssignableTags.add(newTag); assignableTagsComboBox.getDataProvider().refreshAll(); } /** * Removes an assignable tag from the combobox. * * @param tagId * the tag Id of the Tag that should be removed. */ void removeAssignableTag(final Long tagId) { findAssignableTagById(tagId).ifPresent(this::removeAssignableTag); } /** * Removes an assignable tag from the combobox. * * @param tagData * the {@link ProxyTag} of the Tag that should be removed. */ void removeAssignableTag(final ProxyTag tagData) { allAssignableTags.remove(tagData); assignableTagsComboBox.getDataProvider().refreshAll(); } /** * Registers an {@link TagAssignmentListener} on the combobox. * * @param listener * the listener to register */ void addTagAssignmentListener(final TagAssignmentListener listener) { listeners.add(listener); } /** * Removes a {@link TagAssignmentListener} from the combobox, * * @param listener * the listener that should be removed. */ void removeTagAssignmentListener(final TagAssignmentListener listener) { listeners.remove(listener); } private void notifyListenersTagAssigned(final ProxyTag tagData) { listeners.forEach(listener -> listener.assignTag(tagData)); } }
Java
/** * Copyright (c) 2010-2021 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.fronius.internal.api; import com.google.gson.annotations.SerializedName; /** * The {@link HeadRequestArguments} is responsible for storing * the "RequestArguments" node from the {@link Head} * * @author Thomas Rokohl - Initial contribution */ public class HeadRequestArguments { @SerializedName("DataCollection") private String dataCollection; @SerializedName("DeviceClass") private String deviceClass; @SerializedName("DeviceId") private String deviceId; @SerializedName("Scope") private String scope; public String getDataCollection() { if (null == dataCollection) { dataCollection = ""; } return dataCollection; } public void setDataCollection(String dataCollection) { this.dataCollection = dataCollection; } public String getDeviceClass() { if (null == deviceClass) { deviceClass = ""; } return deviceClass; } public void setDeviceClass(String deviceClass) { this.deviceClass = deviceClass; } public String getDeviceId() { if (null == deviceId) { deviceId = ""; } return deviceId; } public void setDeviceId(String deviceId) { this.deviceId = deviceId; } public String getScope() { if (null == scope) { scope = ""; } return scope; } public void setScope(String scope) { this.scope = scope; } }
Java
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.vigicrues.internal.dto.vigicrues; import java.util.List; import com.google.gson.annotations.SerializedName; /** * The {@link TerEntVigiCru} is the Java class used to map the JSON * response to an vigicrue api endpoint request. * * @author Gaël L'hopital - Initial contribution */ public class TerEntVigiCru { public class VicTerEntVigiCru { @SerializedName("vic:aNMoinsUn") public List<VicANMoinsUn> vicANMoinsUn; /* * Currently unused, maybe interesting in the future * * @SerializedName("@id") * public String id; * * @SerializedName("vic:CdEntVigiCru") * public String vicCdEntVigiCru; * * @SerializedName("vic:TypEntVigiCru") * public String vicTypEntVigiCru; * * @SerializedName("vic:LbEntVigiCru") * public String vicLbEntVigiCru; * * @SerializedName("vic:DtHrCreatEntVigiCru") * public String vicDtHrCreatEntVigiCru; * * @SerializedName("vic:DtHrMajEntVigiCru") * public String vicDtHrMajEntVigiCru; * * @SerializedName("vic:StEntVigiCru") * public String vicStEntVigiCru; * public int count_aNMoinsUn; * * @SerializedName("LinkInfoCru") * public String linkInfoCru; */ } @SerializedName("vic:TerEntVigiCru") public VicTerEntVigiCru vicTerEntVigiCru; }
Java
/******************************************************************************* * Copyright (c) 2009-04-24 Joacim Jacobsson. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Joacim Jacobsson - first implementation *******************************************************************************/ #ifndef PARSER_COMMON_H_ #define PARSER_COMMON_H_ #include <btree/btree.h> #include "btree_bison.h" struct SParserContext { StringBuffer m_Parsed; StringBuffer m_Original; ParserContextFunctions m_Funcs; Allocator m_Allocator; unsigned int m_LineNo; BehaviorTreeContext m_Tree; void* m_Extra; const char* m_Current; }; #define YY_EXTRA_TYPE ParserContext int yylex( YYSTYPE*, void* ); int yylex_init( void** ); int yylex_init_extra( YY_EXTRA_TYPE, void** ); int yylex_destroy( void* ); void yyset_extra( YY_EXTRA_TYPE, void* ); int yyparse( YY_EXTRA_TYPE, void* ); void yyerror( ParserContext ctx, const char* msg ); void yywarning( ParserContext ctx, const char* msg ); void yyerror( ParserContext ctx, void*, const char* msg ); void yywarning( ParserContext ctx, void*, const char* msg ); #endif /* PARSER_COMMON_H_ */
Java
/******************************************************************************* * Copyright (c) 2016, 2021 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package com.ibm.ws.security.openidconnect.server.fat.jaxrs.config.OAuth; import java.util.ArrayList; import java.util.List; import org.junit.Assume; import org.junit.BeforeClass; import org.junit.runner.RunWith; import com.ibm.websphere.simplicity.log.Log; import com.ibm.ws.security.oauth_oidc.fat.commonTest.Constants; import com.ibm.ws.security.oauth_oidc.fat.commonTest.TestServer; import com.ibm.ws.security.oauth_oidc.fat.commonTest.TestSettings; import com.ibm.ws.security.openidconnect.server.fat.jaxrs.config.CommonTests.MapToUserRegistryWithRegMismatch2ServerTests; import componenttest.custom.junit.runner.FATRunner; import componenttest.custom.junit.runner.Mode; import componenttest.custom.junit.runner.Mode.TestMode; import componenttest.topology.impl.LibertyServerWrapper; import componenttest.topology.utils.LDAPUtils; // See test description in // com.ibm.ws.security.openidconnect.server-1.0_fat.jaxrs.config/fat/src/com/ibm/ws/security/openidconnect/server/fat/jaxrs/config/CommonTests/MapToUserRegistryWithRegMismatch2ServerTests.java @LibertyServerWrapper @Mode(TestMode.FULL) @RunWith(FATRunner.class) public class OAuthMapToUserRegistryWithRegMismatch2ServerTests extends MapToUserRegistryWithRegMismatch2ServerTests { private static final Class<?> thisClass = OAuthMapToUserRegistryWithRegMismatch2ServerTests.class; @BeforeClass public static void setupBeforeTest() throws Exception { /* * These tests have not been configured to run with the local LDAP server. */ Assume.assumeTrue(!LDAPUtils.USE_LOCAL_LDAP_SERVER); msgUtils.printClassName(thisClass.toString()); Log.info(thisClass, "setupBeforeTest", "Prep for test"); // add any additional messages that you want the "start" to wait for // we should wait for any providers that this test requires List<String> extraMsgs = new ArrayList<String>(); extraMsgs.add("CWWKS1631I.*"); List<String> extraApps = new ArrayList<String>(); TestServer.addTestApp(null, extraMsgs, Constants.OP_SAMPLE_APP, Constants.OAUTH_OP); TestServer.addTestApp(extraApps, null, Constants.OP_CLIENT_APP, Constants.OAUTH_OP); TestServer.addTestApp(extraApps, extraMsgs, Constants.OP_TAI_APP, Constants.OAUTH_OP); List<String> extraMsgs2 = new ArrayList<String>(); List<String> extraApps2 = new ArrayList<String>(); extraApps2.add(Constants.HELLOWORLD_SERVLET); testSettings = new TestSettings(); testOPServer = commonSetUp(OPServerName, "server_orig_maptest_ldap.xml", Constants.OAUTH_OP, extraApps, Constants.DO_NOT_USE_DERBY, extraApps); genericTestServer = commonSetUp(RSServerName, "server_orig_maptest_mismatchregistry.xml", Constants.GENERIC_SERVER, extraApps2, Constants.DO_NOT_USE_DERBY, extraMsgs2, null, Constants.OAUTH_OP); targetProvider = Constants.OAUTHCONFIGSAMPLE_APP; flowType = Constants.WEB_CLIENT_FLOW; goodActions = Constants.BASIC_PROTECTED_RESOURCE_RS_PROTECTED_RESOURCE_ACTIONS; // set RS protected resource to point to second server. testSettings.setRSProtectedResource(genericTestServer.getHttpsString() + "/helloworld/rest/helloworld"); // Initial user settings for default user. Individual tests override as needed. testSettings.setAdminUser("oidcu1"); testSettings.setAdminPswd("security"); testSettings.setGroupIds("RSGroup"); } }
Java
/******************************************************************************* * Copyright (c) 2016, 2021 Eurotech and/or its affiliates and others * * This program and the accompanying materials are made * available under the terms of the Eclipse Public License 2.0 * which is available at https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * Eurotech - initial API and implementation *******************************************************************************/ package org.eclipse.kapua; /** * KapuaIllegalNullArgumentException is thrown when <tt>null</tt> is passed to a method for an argument * or as a value for field in an object where <tt>null</tt> is not allowed.<br> * This should always be used instead of <tt>NullPointerException</tt> as the latter is too easily confused with programming bugs. * * @since 1.0 * */ public class KapuaIllegalNullArgumentException extends KapuaIllegalArgumentException { private static final long serialVersionUID = -8762712571192128282L; /** * Constructor * * @param argumentName */ public KapuaIllegalNullArgumentException(String argumentName) { super(KapuaErrorCodes.ILLEGAL_NULL_ARGUMENT, argumentName, null); } }
Java
<!-- This file is part of YunWebUI. YunWebUI 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 St, Fifth Floor, Boston, MA 02110-1301 USA As a special exception, you may use this file as part of a free software library without restriction. Specifically, if other files instantiate templates or use macros or inline functions from this file, or you compile this file and link it with other files to produce an executable, this file does not by itself cause the resulting executable to be covered by the GNU General Public License. This exception does not however invalidate any other reasons why the executable file might be covered by the GNU General Public License. Copyright 2013 Arduino LLC (http://www.arduino.cc/) --> <html> <head> <title>Bridge Key/Value Storage Manager Example</title> <style> body { background-color: #00979c; color: #222; font: 1em "Lucida Grande", Lucida, Verdana, sans-serif; } </style> </head> <body> <div style="visibility: hidden; display: none;"> <table id="template"> <tr> <td>"KEY"</td> <td><input name="KEY" type="hidden" value="VALUE"> <input name="KEY" value="VALUE" type="text"></td> <td><input type="button" name="KEY" value="delete"></td> </tr> </table> </div> <div style="background: none repeat scroll 0 0 #F5F5F5"> <div style="padding: 2em;"> <div id="warning" style="display: none;"> <span style="color: #c37676;">You are using HTTP. We suggest to use HTTPS to protect your Y&uacute;n<br><br></span> </div> Password: <input id="password" type="password" value=""> <br/> <br/> <div id="storage"> Retrieving storage values... </div> <br/> <input id="refresh" type="button" value="Reload storage!"> <br/> <br/> <div> Add a new entry into the storage:<br> <table> <tr> <td>Key:</td> <td><input id="new_storage_key" type="text"></td> </tr> <tr> <td>Value:</td> <td><input id="new_storage_value" type="text"></td> </tr> </table> </div> <input id="update" type="button" value="Update or insert new key/value pair"> </div> </div> <script type="text/javascript" src="zepto.min.js"></script> <script> "use strict"; var please_wait_message = "Retrieving storage values..."; function util_make_basic_auth(user, password) { var tok = user + ':' + (password || "arduino"); var hash = btoa(tok); return "Basic " + hash; } function add_basic_auth_headers_if_password(ajax_call_options, password) { if (password && password !== "") { ajax_call_options.headers = { Authorization: util_make_basic_auth("root", password) } } } function error_handler(error) { if (error && error.status && error.status === 403) { alert("Password is wrong!"); return } if (error && error.status && error.status === 500) { alert("Error accessing the key/value store. Is the Bridge example sketch running?"); } else { alert("Uknown error: check browser console"); } console.log(arguments); } function storage_retrieve_all(callback) { var ajax_call_options = { url: "/data/get", timeout: 10000, success: callback, error: error_handler }; add_basic_auth_headers_if_password(ajax_call_options, $("#password").val()); $.ajax(ajax_call_options) } function storage_delete_by_key(key, callback) { var ajax_call_options = { url: "/data/delete/" + encodeURIComponent(key), timeout: 10000, success: callback, error: error_handler }; add_basic_auth_headers_if_password(ajax_call_options, $("#password").val()); $.ajax(ajax_call_options) } function storage_update_key_value(key, value, callback) { var ajax_call_options = { url: "/data/put/" + encodeURIComponent(key) + "/" + encodeURIComponent(value), timeout: 10000, success: callback, error: error_handler }; add_basic_auth_headers_if_password(ajax_call_options, $("#password").val()); $.ajax(ajax_call_options) } function repaint_storage(storage) { $("#storage").empty(); if (storage.value.length === 0) { $("#storage").html("Storage is empty!"); return; } var template = $("#template tbody").html(); var html = ""; for (var key in storage.value) { html = html + template.replace(/KEY/g, key).replace(/VALUE/g, storage.value[key]); } $("#storage").html("<table><tr><td>Key</td><td>Value</td><td></td></tr>" + html + "</table>"); } function confirm_storage_key_deletion(event) { var key = $(event.target).attr("name"); if (confirm("Are you sure you want to delete key \"" + key + "\" ?")) { storage_delete_by_key(key, function() { $("#storage").html(please_wait_message); storage_retrieve_all(repaint_storage); }); } } function update_storage(callback) { var keys_to_update = []; $("#storage input[type=text]").each(function(idx, item) { var $key_value = $(item); if ($key_value.val() !== $("#storage input[type=hidden][name=" + $key_value.attr("name") + "]").val()) { keys_to_update.push({ key: $key_value.attr("name"), value: $key_value.val() }); } }); var new_storage_key = $("#new_storage_key").val(); var new_storage_value = $("#new_storage_value").val(); if (new_storage_key && new_storage_value) { keys_to_update.push({ key: new_storage_key, value: new_storage_value }); } var done = 0; for (var idx = 0; idx < keys_to_update.length; idx++) { storage_update_key_value(keys_to_update[idx].key, keys_to_update[idx].value, function() { done++; if (done === keys_to_update.length) { callback(); } }); } } $(function() { $("#storage").html(please_wait_message); storage_retrieve_all(repaint_storage); $("#storage").on("click", "input[type=button]", confirm_storage_key_deletion); $("#update").on("click", function() { update_storage(function() { $("#storage").html(please_wait_message); storage_retrieve_all(repaint_storage); }) }); $("#refresh").on("click", function() { $("#storage").html(please_wait_message); storage_retrieve_all(repaint_storage); }); if (window.location.protocol === "http:") { $("#warning").attr("style", ""); } }); </script> </body> </html>
Java
/* * Copyright (c) 2000, 2001, 2002 Fabrice Bellard * Copyright (c) 2007 Mans Rullgard * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <stdarg.h> #include <stdint.h> #include <stdio.h> #include <string.h> #include "config.h" #include "common.h" #include "mem.h" #include "avassert.h" #include "avstring.h" #include "bprint.h" int av_strstart(const char *str, const char *pfx, const char **ptr) { while (*pfx && *pfx == *str) { pfx++; str++; } if (!*pfx && ptr) *ptr = str; return !*pfx; } int av_stristart(const char *str, const char *pfx, const char **ptr) { while (*pfx && av_toupper((unsigned)*pfx) == av_toupper((unsigned)*str)) { pfx++; str++; } if (!*pfx && ptr) *ptr = str; return !*pfx; } char *av_stristr(const char *s1, const char *s2) { if (!*s2) return (char*)(intptr_t)s1; do if (av_stristart(s1, s2, NULL)) return (char*)(intptr_t)s1; while (*s1++); return NULL; } char *av_strnstr(const char *haystack, const char *needle, size_t hay_length) { size_t needle_len = strlen(needle); if (!needle_len) return (char*)haystack; while (hay_length >= needle_len) { hay_length--; if (!memcmp(haystack, needle, needle_len)) return (char*)haystack; haystack++; } return NULL; } size_t av_strlcpy(char *dst, const char *src, size_t size) { size_t len = 0; while (++len < size && *src) *dst++ = *src++; if (len <= size) *dst = 0; return len + strlen(src) - 1; } size_t av_strlcat(char *dst, const char *src, size_t size) { size_t len = strlen(dst); if (size <= len + 1) return len + strlen(src); return len + av_strlcpy(dst + len, src, size - len); } size_t av_strlcatf(char *dst, size_t size, const char *fmt, ...) { size_t len = strlen(dst); va_list vl; va_start(vl, fmt); len += vsnprintf(dst + len, size > len ? size - len : 0, fmt, vl); va_end(vl); return len; } char *av_asprintf(const char *fmt, ...) { char *p = NULL; va_list va; int len; va_start(va, fmt); len = vsnprintf(NULL, 0, fmt, va); va_end(va); if (len < 0) goto end; p = av_malloc(len + 1); if (!p) goto end; va_start(va, fmt); len = vsnprintf(p, len + 1, fmt, va); va_end(va); if (len < 0) av_freep(&p); end: return p; } char *av_d2str(double d) { char *str = av_malloc(16); if (str) snprintf(str, 16, "%f", d); return str; } #define WHITESPACES " \n\t" char *av_get_token(const char **buf, const char *term) { char *out = av_malloc(strlen(*buf) + 1); char *ret = out, *end = out; const char *p = *buf; if (!out) return NULL; p += strspn(p, WHITESPACES); while (*p && !strspn(p, term)) { char c = *p++; if (c == '\\' && *p) { *out++ = *p++; end = out; } else if (c == '\'') { while (*p && *p != '\'') *out++ = *p++; if (*p) { p++; end = out; } } else { *out++ = c; } } do *out-- = 0; while (out >= end && strspn(out, WHITESPACES)); *buf = p; return ret; } char *av_strtok(char *s, const char *delim, char **saveptr) { char *tok; if (!s && !(s = *saveptr)) return NULL; /* skip leading delimiters */ s += strspn(s, delim); /* s now points to the first non delimiter char, or to the end of the string */ if (!*s) { *saveptr = NULL; return NULL; } tok = s++; /* skip non delimiters */ s += strcspn(s, delim); if (*s) { *s = 0; *saveptr = s+1; } else { *saveptr = NULL; } return tok; } int av_strcasecmp(const char *a, const char *b) { uint8_t c1, c2; do { c1 = av_tolower(*a++); c2 = av_tolower(*b++); } while (c1 && c1 == c2); return c1 - c2; } int av_strncasecmp(const char *a, const char *b, size_t n) { const char *end = a + n; uint8_t c1, c2; do { c1 = av_tolower(*a++); c2 = av_tolower(*b++); } while (a < end && c1 && c1 == c2); return c1 - c2; } const char *av_basename(const char *path) { char *p = strrchr(path, '/'); #if HAVE_DOS_PATHS char *q = strrchr(path, '\\'); char *d = strchr(path, ':'); p = FFMAX3(p, q, d); #endif if (!p) return path; return p + 1; } const char *av_dirname(char *path) { char *p = strrchr(path, '/'); #if HAVE_DOS_PATHS char *q = strrchr(path, '\\'); char *d = strchr(path, ':'); d = d ? d + 1 : d; p = FFMAX3(p, q, d); #endif if (!p) return "."; *p = '\0'; return path; } int av_escape(char **dst, const char *src, const char *special_chars, enum AVEscapeMode mode, int flags) { AVBPrint dstbuf; av_bprint_init(&dstbuf, 1, AV_BPRINT_SIZE_UNLIMITED); av_bprint_escape(&dstbuf, src, special_chars, mode, flags); if (!av_bprint_is_complete(&dstbuf)) { av_bprint_finalize(&dstbuf, NULL); return AVERROR(ENOMEM); } else { av_bprint_finalize(&dstbuf, dst); return dstbuf.len; } } int av_isdigit(int c) { return c >= '0' && c <= '9'; } int av_isgraph(int c) { return c > 32 && c < 127; } int av_isspace(int c) { return c == ' ' || c == '\f' || c == '\n' || c == '\r' || c == '\t' || c == '\v'; } int av_isxdigit(int c) { c = av_tolower(c); return av_isdigit(c) || (c >= 'a' && c <= 'f'); } int av_match_name(const char *name, const char *names) { const char *p; int len, namelen; if (!name || !names) return 0; namelen = strlen(name); while ((p = strchr(names, ','))) { len = FFMAX(p - names, namelen); if (!av_strncasecmp(name, names, len)) return 1; names = p + 1; } return !av_strcasecmp(name, names); } int av_utf8_decode(int32_t *codep, const uint8_t **bufp, const uint8_t *buf_end, unsigned int flags) { const uint8_t *p = *bufp; uint32_t top; uint64_t code; int ret = 0, tail_len; uint32_t overlong_encoding_mins[6] = { 0x00000000, 0x00000080, 0x00000800, 0x00010000, 0x00200000, 0x04000000, }; if (p >= buf_end) return 0; code = *p++; /* first sequence byte starts with 10, or is 1111-1110 or 1111-1111, which is not admitted */ if ((code & 0xc0) == 0x80 || code >= 0xFE) { ret = AVERROR(EILSEQ); goto end; } top = (code & 128) >> 1; tail_len = 0; while (code & top) { int tmp; tail_len++; if (p >= buf_end) { (*bufp) ++; return AVERROR(EILSEQ); /* incomplete sequence */ } /* we assume the byte to be in the form 10xx-xxxx */ tmp = *p++ - 128; /* strip leading 1 */ if (tmp>>6) { (*bufp) ++; return AVERROR(EILSEQ); } code = (code<<6) + tmp; top <<= 5; } code &= (top << 1) - 1; /* check for overlong encodings */ av_assert0(tail_len <= 5); if (code < overlong_encoding_mins[tail_len]) { ret = AVERROR(EILSEQ); goto end; } if (code >= 1<<31) { ret = AVERROR(EILSEQ); /* out-of-range value */ goto end; } *codep = code; if (code > 0x10FFFF && !(flags & AV_UTF8_FLAG_ACCEPT_INVALID_BIG_CODES)) ret = AVERROR(EILSEQ); if (code < 0x20 && code != 0x9 && code != 0xA && code != 0xD && flags & AV_UTF8_FLAG_EXCLUDE_XML_INVALID_CONTROL_CODES) ret = AVERROR(EILSEQ); if (code >= 0xD800 && code <= 0xDFFF && !(flags & AV_UTF8_FLAG_ACCEPT_SURROGATES)) ret = AVERROR(EILSEQ); if ((code == 0xFFFE || code == 0xFFFF) && !(flags & AV_UTF8_FLAG_ACCEPT_NON_CHARACTERS)) ret = AVERROR(EILSEQ); end: *bufp = p; return ret; } int av_match_list(const char *name, const char *list, char separator) { const char *p, *q; for (p = name; p && *p; ) { for (q = list; q && *q; ) { int k; for (k = 0; p[k] == q[k] || (p[k]*q[k] == 0 && p[k]+q[k] == separator); k++) if (k && (!p[k] || p[k] == separator)) return 1; q = strchr(q, separator); q += !!q; } p = strchr(p, separator); p += !!p; } return 0; } #ifdef TEST int main(void) { int i; static const char * const strings[] = { "''", "", ":", "\\", "'", " '' :", " '' '' :", "foo '' :", "'foo'", "foo ", " ' foo ' ", "foo\\", "foo': blah:blah", "foo\\: blah:blah", "foo\'", "'foo : ' :blahblah", "\\ :blah", " foo", " foo ", " foo \\ ", "foo ':blah", " foo bar : blahblah", "\\f\\o\\o", "'foo : \\ \\ ' : blahblah", "'\\fo\\o:': blahblah", "\\'fo\\o\\:': foo ' :blahblah" }; printf("Testing av_get_token()\n"); for (i = 0; i < FF_ARRAY_ELEMS(strings); i++) { const char *p = strings[i]; char *q; printf("|%s|", p); q = av_get_token(&p, ":"); printf(" -> |%s|", q); printf(" + |%s|\n", p); av_free(q); } return 0; } #endif /* TEST */
Java
<?php /** * Community Builder (TM) cbconditional Chinese (China) language file Frontend * @version $Id:$ * @copyright (C) 2004-2014 www.joomlapolis.com / Lightning MultiCom SA - and its licensors, all rights reserved * @license http://www.gnu.org/licenses/old-licenses/gpl-2.0.html GNU/GPL version 2 */ /** * WARNING: * Do not make changes to this file as it will be over-written when you upgrade CB. * To localize you need to create your own CB language plugin and make changes there. */ defined('CBLIB') or die(); return array( // 66 language strings from file plug_cbconditional/cbconditional.xml 'TAB_CONDITION_PREFERENCES_21582b' => 'Tab condition preferences', 'SELECT_CONDITIONAL_DISPLAY_FOR_THIS_TAB_244679' => 'Select conditional display for this tab.', 'NORMAL_CB_SETTINGS_a0f77c' => 'Normal CB settings', 'TAB_CONDITIONAL_46ba5c' => 'Tab conditional', 'IF_bfa9de' => 'If...', 'SELECT_FIELD_TO_MATCH_VALUE_AGAINST_IN_DETERMINING_c94841' => 'Select field to match value against in determining this tabs display.', 'FIELD_6f16a5' => 'Field', 'VALUE_689202' => 'Value', 'VIEW_ACCESS_LEVELS_c06927' => 'View Access Levels', 'USERGROUPS_6ad0aa' => 'Usergroups', 'FIELDS_a4ca5e' => 'Fields', 'VALUE_f14e9e' => 'Value...', 'INPUT_SUBSTITUTION_SUPPORTED_VALUE_TO_MATCH_AGAINS_4be26b' => 'Input substitution supported value to match against. In addition to user substitutions you can access $_REQUEST, $_GET, and $_POST substitutions as [request_VARIABLE],[post_VARIABLE], and [get_VARIABLE] (e.g. [get_task]).', 'ENABLE_OR_DISABLE_TRANSLATION_OF_LANGUAGE_STRINGS__8263a9' => 'Enable or disable translation of language strings in value.', 'TRANSLATE_VALUE_22a4e1' => 'Translate Value', 'HAS_7bac0f' => 'Has...', 'SELECT_THE_VIEW_ACCESS_LEVELS_TO_MATCH_AGAINST_THE_1c9be8' => 'Select the view access levels to match against the user. The user only needs to have one of the selected view access levels to match.', 'SELECT_THE_USERGROUPS_TO_MATCH_AGAINST_THE_USER_TH_dc4e06' => 'Select the usergroups to match against the user. The user only needs to have one of the selected usergroups to match.', 'IS_9149c7' => 'Is...', 'SELECT_OPERATOR_TO_COMPARE_FIELD_VALUE_AGAINST_INP_43ce0f' => 'Select operator to compare field value against input value.', 'OPERATOR_e1b3ec' => 'Operator', 'EQUAL_TO_c1d440' => 'Equal To', 'NOT_EQUAL_TO_9ac8c0' => 'Not Equal To', 'GREATER_THAN_728845' => 'Greater Than', 'LESS_THAN_45ed1c' => 'Less Than', 'GREATER_THAN_OR_EQUAL_TO_93301c' => 'Greater Than or Equal To', 'LESS_THAN_OR_EQUAL_TO_3181f2' => 'Less Than or Equal To', 'EMPTY_ce2c8a' => 'Empty', 'NOT_EMPTY_f49248' => 'Not Empty', 'DOES_CONTAIN_396955' => 'Does Contain', 'DOES_NOT_CONTAIN_ef739c' => 'Does Not Contain', 'IS_REGEX_44846d' => 'Is REGEX', 'IS_NOT_REGEX_4bddfd' => 'Is Not REGEX', 'TO_4a384a' => 'To...', 'INPUT_SUBSTITUTION_SUPPORTED_VALUE_TO_MATCH_AGAINS_07c86e' => 'Input substitution supported value to match against field value. In addition to user substitutions you can access $_REQUEST, $_GET, and $_POST substitutions as [request_VARIABLE],[post_VARIABLE], and [get_VARIABLE] (e.g. [get_task]).', 'THEN_c1325f' => 'Then...', 'SELECT_HOW_TO_HANDLE_THIS_TABS_DISPLAY_BASED_ON_FI_ff33e1' => 'Select how to handle this tabs display based on field value match.', 'FOR_0ba2b3' => 'For...', 'ENABLE_OR_DISABLE_CONDITIONAL_USAGE_ON_REGISTRATIO_cb622e' => 'Enable or disable conditional usage on registration.', 'REGISTRATION_0f98b7' => 'Registration', 'ENABLE_OR_DISABLE_CONDITIONAL_USAGE_ON_PROFILE_EDI_5bfd08' => 'Enable or disable conditional usage on profile edit.', 'PROFILE_EDIT_24f0eb' => 'Profile Edit', 'ENABLE_OR_DISABLE_CONDITIONAL_USAGE_ON_PROFILE_VIE_b815a1' => 'Enable or disable conditional usage on profile view.', 'PROFILE_VIEW_307f0e' => 'Profile View', 'FIELD_CONDITION_PREFERENCES_757bb6' => 'Field condition preferences', 'SELECT_CONDITIONAL_DISPLAY_FOR_THIS_FIELD_329dc4' => 'Select conditional display for this field.', 'FIELD_CONDITIONAL_OTHERS_453f6f' => 'Field conditional others', 'FIELD_CONDITIONAL_SELF_281138' => 'Field conditional self', 'SELECT_FIELD_TO_MATCH_VALUE_AGAINST_IN_DETERMINING_7d601b' => 'Select field to match value against in determining this fields display.', 'SELECT_FIELD_24af14' => '--- Select Field ---', 'SELECT_FIELDS_TO_SHOW_IF_VALUE_IS_MATCHED_f63533' => 'Select fields to show if value is matched.', 'SELECT_FIELDS_5be58c' => '--- Select Fields ---', 'SELECT_FIELDS_TO_HIDE_IF_VALUE_IS_MATCHED_e0a204' => 'Select fields to hide if value is matched.', 'FIELD_OPTIONS_9b3c51' => 'Field Options', 'SELECT_FIELD_OPTIONS_TO_SHOW_IF_VALUE_IS_MATCHED_459bc1' => 'Select field options to show if value is matched.', 'SELECT_FIELD_OPTIONS_837903' => '--- Select Field Options ---', 'SELECT_FIELD_OPTIONS_TO_HIDE_IF_VALUE_IS_MATCHED_01f5ab' => 'Select field options to hide if value is matched.', 'SELECT_HOW_TO_HANDLE_THIS_FIELDS_DISPLAY_BASED_ON__32d89f' => 'Select how to handle this fields display based on field value match.', 'ENABLE_OR_DISABLE_CONDITIONAL_USAGE_ON_USERLISTS_S_15983a' => 'Enable or disable conditional usage on userlists searching.', 'USERLISTS_SEARCH_fad6c1' => 'Userlists Search', 'ENABLE_OR_DISABLE_CONDITIONAL_USAGE_ON_USERLISTS_V_a02f8c' => 'Enable or disable conditional usage on userlists view.', 'USERLISTS_VIEW_72449c' => 'Userlists View', 'ENABLE_OR_DISABLE_USAGE_OF_CONDITIONS_IN_BACKEND_0b15b5' => 'Enable or disable usage of conditions in Backend.', 'BACKEND_2e427c' => 'Backend', 'ENABLE_OR_DISABLE_RESET_OF_FIELD_VALUES_TO_BLANK_I_278676' => 'Enable or disable reset of field values to blank if condition is not met.', 'RESET_526d68' => 'Reset', );
Java
/* * Copyright (C) 2014 Michael Joyce <ubermichael@gmail.com> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation version 2. * * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package ca.nines.ise.util; import java.util.ArrayDeque; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.UserDataHandler; import org.w3c.dom.events.Event; import org.w3c.dom.events.EventListener; import org.w3c.dom.events.EventTarget; import org.xml.sax.Attributes; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.helpers.XMLFilterImpl; import org.xml.sax.XMLReader; import org.xml.sax.helpers.LocatorImpl; /** * Annotates a DOM with location data during the construction process. * <p> * http://javacoalface.blogspot.ca/2011/04/line-and-column-numbers-in-xml-dom.html * <p> * @author Michael Joyce <ubermichael@gmail.com> */ public class LocationAnnotator extends XMLFilterImpl { /** * Locator returned by the construction process. */ private Locator locator; /** * The systemID of the XML. */ private final String source; /** * Stack to hold the locators which haven't been completed yet. */ private final ArrayDeque<Locator> locatorStack = new ArrayDeque<>(); /** * Stack holding incomplete elements. */ private final ArrayDeque<Element> elementStack = new ArrayDeque<>(); /** * A data handler to add the location data. */ private final UserDataHandler dataHandler = new LocationDataHandler(); /** * Construct a location annotator for an XMLReader and Document. The systemID * is determined automatically. * * @param xmlReader the reader to use the annotator * @param dom the DOM to annotate */ LocationAnnotator(XMLReader xmlReader, Document dom) { super(xmlReader); source = ""; EventListener modListener = new EventListener() { @Override public void handleEvent(Event e) { EventTarget target = e.getTarget(); elementStack.push((Element) target); } }; ((EventTarget) dom).addEventListener("DOMNodeInserted", modListener, true); } /** * Construct a location annotator for an XMLReader and Document. The systemID * is NOT determined automatically. * * @param source the systemID of the XML * @param xmlReader the reader to use the annotator * @param dom the DOM to annotate */ LocationAnnotator(String source, XMLReader xmlReader, Document dom) { super(xmlReader); this.source = source; EventListener modListener = new EventListener() { @Override public void handleEvent(Event e) { EventTarget target = e.getTarget(); elementStack.push((Element) target); } }; ((EventTarget) dom).addEventListener("DOMNodeInserted", modListener, true); } /** * Add the locator to the document during the parse. * * @param locator the locator to add */ @Override public void setDocumentLocator(Locator locator) { super.setDocumentLocator(locator); this.locator = locator; } /** * Handle the start tag of an element by adding locator data. * * @param uri The systemID of the XML. * @param localName the name of the tag. unused. * @param qName the FQDN of the tag. unused. * @param atts the attributes of the tag. unused. * @throws SAXException */ @Override public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { super.startElement(uri, localName, qName, atts); locatorStack.push(new LocatorImpl(locator)); } /** * Handle the end tag of an element by adding locator data. * * @param uri The systemID of the XML. * @param localName the name of the tag. unused. * @param qName the FQDN of the tag. unused. * @throws SAXException */ @Override public void endElement(String uri, String localName, String qName) throws SAXException { super.endElement(uri, localName, qName); if (locatorStack.size() > 0) { Locator startLocator = locatorStack.pop(); LocationData location = new LocationData( (startLocator.getSystemId() == null ? source : startLocator.getSystemId()), startLocator.getLineNumber(), startLocator.getColumnNumber(), locator.getLineNumber(), locator.getColumnNumber() ); Element e = elementStack.pop(); e.setUserData( LocationData.LOCATION_DATA_KEY, location, dataHandler); } } /** * UserDataHandler to insert location data into the XML DOM. */ private class LocationDataHandler implements UserDataHandler { /** * Handle an even during a parse. An even is a start/end/empty tag or some * data. * * @param operation unused. * @param key unused * @param data unused * @param src the source of the data * @param dst the destination of the data */ @Override public void handle(short operation, String key, Object data, Node src, Node dst) { if (src != null && dst != null) { LocationData locatonData = (LocationData) src.getUserData(LocationData.LOCATION_DATA_KEY); if (locatonData != null) { dst.setUserData(LocationData.LOCATION_DATA_KEY, locatonData, dataHandler); } } } } }
Java
package net.indrix.arara.servlets.pagination; import java.sql.SQLException; import java.util.List; import net.indrix.arara.dao.DatabaseDownException; public class SoundBySpeciePaginationController extends SoundPaginationController { /** * Creates a new PaginationController object, with the given number of elements per page, and * with the flag identification * * @param soundsPerPage The amount of sounds per page * @param identification The flag for identification */ public SoundBySpeciePaginationController(int soundsPerPage, boolean identification) { super(soundsPerPage, identification); } @Override protected List retrieveAllData() throws DatabaseDownException, SQLException { logger.debug("SoundBySpeciePaginationController.retrieveAllData : retrieving all sounds..."); List listOfSounds = null; if (id != -1){ listOfSounds = model.retrieveIDsForSpecie(getId()); } else { listOfSounds = model.retrieveIDsForSpecieName(getText()); } logger.debug("SoundBySpeciePaginationController.retrieveAllData : " + listOfSounds.size() + " sounds retrieved..."); return listOfSounds; } }
Java
/* This file was generated by PyBindGen 0.15.0.809 */ #define PY_SSIZE_T_CLEAN #include <Python.h> #include <stddef.h> #if PY_VERSION_HEX < 0x020400F0 #define PyEval_ThreadsInitialized() 1 #define Py_CLEAR(op) \ do { \ if (op) { \ PyObject *tmp = (PyObject *)(op); \ (op) = NULL; \ Py_DECREF(tmp); \ } \ } while (0) #define Py_VISIT(op) \ do { \ if (op) { \ int vret = visit((PyObject *)(op), arg); \ if (vret) \ return vret; \ } \ } while (0) #endif #if PY_VERSION_HEX < 0x020500F0 typedef int Py_ssize_t; # define PY_SSIZE_T_MAX INT_MAX # define PY_SSIZE_T_MIN INT_MIN typedef inquiry lenfunc; typedef intargfunc ssizeargfunc; typedef intobjargproc ssizeobjargproc; #endif #if __GNUC__ > 2 # define PYBINDGEN_UNUSED(param) param __attribute__((__unused__)) #elif __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ > 4) # define PYBINDGEN_UNUSED(param) __attribute__((__unused__)) param #else # define PYBINDGEN_UNUSED(param) param #endif /* !__GNUC__ */ typedef enum _PyBindGenWrapperFlags { PYBINDGEN_WRAPPER_FLAG_NONE = 0, PYBINDGEN_WRAPPER_FLAG_OBJECT_NOT_OWNED = (1<<0), } PyBindGenWrapperFlags; #include "ns3/uan-module.h" #include <ostream> #include <sstream> #include <typeinfo> #include <map> #include <iostream> /* --- forward declarations --- */ typedef struct { PyObject_HEAD ns3::Address *obj; PyBindGenWrapperFlags flags:8; } PyNs3Address; extern PyTypeObject *_PyNs3Address_Type; #define PyNs3Address_Type (*_PyNs3Address_Type) extern std::map<void*, PyObject*> *_PyNs3Address_wrapper_registry; #define PyNs3Address_wrapper_registry (*_PyNs3Address_wrapper_registry) typedef struct { PyObject_HEAD ns3::AttributeConstructionList *obj; PyBindGenWrapperFlags flags:8; } PyNs3AttributeConstructionList; extern PyTypeObject *_PyNs3AttributeConstructionList_Type; #define PyNs3AttributeConstructionList_Type (*_PyNs3AttributeConstructionList_Type) extern std::map<void*, PyObject*> *_PyNs3AttributeConstructionList_wrapper_registry; #define PyNs3AttributeConstructionList_wrapper_registry (*_PyNs3AttributeConstructionList_wrapper_registry) typedef struct { PyObject_HEAD ns3::AttributeConstructionList::Item *obj; PyBindGenWrapperFlags flags:8; } PyNs3AttributeConstructionListItem; extern PyTypeObject *_PyNs3AttributeConstructionListItem_Type; #define PyNs3AttributeConstructionListItem_Type (*_PyNs3AttributeConstructionListItem_Type) extern std::map<void*, PyObject*> *_PyNs3AttributeConstructionListItem_wrapper_registry; #define PyNs3AttributeConstructionListItem_wrapper_registry (*_PyNs3AttributeConstructionListItem_wrapper_registry) typedef struct { PyObject_HEAD ns3::Buffer *obj; PyBindGenWrapperFlags flags:8; } PyNs3Buffer; extern PyTypeObject *_PyNs3Buffer_Type; #define PyNs3Buffer_Type (*_PyNs3Buffer_Type) extern std::map<void*, PyObject*> *_PyNs3Buffer_wrapper_registry; #define PyNs3Buffer_wrapper_registry (*_PyNs3Buffer_wrapper_registry) typedef struct { PyObject_HEAD ns3::Buffer::Iterator *obj; PyBindGenWrapperFlags flags:8; } PyNs3BufferIterator; extern PyTypeObject *_PyNs3BufferIterator_Type; #define PyNs3BufferIterator_Type (*_PyNs3BufferIterator_Type) extern std::map<void*, PyObject*> *_PyNs3BufferIterator_wrapper_registry; #define PyNs3BufferIterator_wrapper_registry (*_PyNs3BufferIterator_wrapper_registry) typedef struct { PyObject_HEAD ns3::ByteTagIterator *obj; PyBindGenWrapperFlags flags:8; } PyNs3ByteTagIterator; extern PyTypeObject *_PyNs3ByteTagIterator_Type; #define PyNs3ByteTagIterator_Type (*_PyNs3ByteTagIterator_Type) extern std::map<void*, PyObject*> *_PyNs3ByteTagIterator_wrapper_registry; #define PyNs3ByteTagIterator_wrapper_registry (*_PyNs3ByteTagIterator_wrapper_registry) typedef struct { PyObject_HEAD ns3::ByteTagIterator::Item *obj; PyBindGenWrapperFlags flags:8; } PyNs3ByteTagIteratorItem; extern PyTypeObject *_PyNs3ByteTagIteratorItem_Type; #define PyNs3ByteTagIteratorItem_Type (*_PyNs3ByteTagIteratorItem_Type) extern std::map<void*, PyObject*> *_PyNs3ByteTagIteratorItem_wrapper_registry; #define PyNs3ByteTagIteratorItem_wrapper_registry (*_PyNs3ByteTagIteratorItem_wrapper_registry) typedef struct { PyObject_HEAD ns3::ByteTagList *obj; PyBindGenWrapperFlags flags:8; } PyNs3ByteTagList; extern PyTypeObject *_PyNs3ByteTagList_Type; #define PyNs3ByteTagList_Type (*_PyNs3ByteTagList_Type) extern std::map<void*, PyObject*> *_PyNs3ByteTagList_wrapper_registry; #define PyNs3ByteTagList_wrapper_registry (*_PyNs3ByteTagList_wrapper_registry) typedef struct { PyObject_HEAD ns3::ByteTagList::Iterator *obj; PyBindGenWrapperFlags flags:8; } PyNs3ByteTagListIterator; extern PyTypeObject *_PyNs3ByteTagListIterator_Type; #define PyNs3ByteTagListIterator_Type (*_PyNs3ByteTagListIterator_Type) extern std::map<void*, PyObject*> *_PyNs3ByteTagListIterator_wrapper_registry; #define PyNs3ByteTagListIterator_wrapper_registry (*_PyNs3ByteTagListIterator_wrapper_registry) typedef struct { PyObject_HEAD ns3::ByteTagList::Iterator::Item *obj; PyBindGenWrapperFlags flags:8; } PyNs3ByteTagListIteratorItem; extern PyTypeObject *_PyNs3ByteTagListIteratorItem_Type; #define PyNs3ByteTagListIteratorItem_Type (*_PyNs3ByteTagListIteratorItem_Type) extern std::map<void*, PyObject*> *_PyNs3ByteTagListIteratorItem_wrapper_registry; #define PyNs3ByteTagListIteratorItem_wrapper_registry (*_PyNs3ByteTagListIteratorItem_wrapper_registry) typedef struct { PyObject_HEAD ns3::CallbackBase *obj; PyBindGenWrapperFlags flags:8; } PyNs3CallbackBase; extern PyTypeObject *_PyNs3CallbackBase_Type; #define PyNs3CallbackBase_Type (*_PyNs3CallbackBase_Type) extern std::map<void*, PyObject*> *_PyNs3CallbackBase_wrapper_registry; #define PyNs3CallbackBase_wrapper_registry (*_PyNs3CallbackBase_wrapper_registry) typedef struct { PyObject_HEAD ns3::DeviceEnergyModelContainer *obj; PyBindGenWrapperFlags flags:8; } PyNs3DeviceEnergyModelContainer; extern PyTypeObject *_PyNs3DeviceEnergyModelContainer_Type; #define PyNs3DeviceEnergyModelContainer_Type (*_PyNs3DeviceEnergyModelContainer_Type) extern std::map<void*, PyObject*> *_PyNs3DeviceEnergyModelContainer_wrapper_registry; #define PyNs3DeviceEnergyModelContainer_wrapper_registry (*_PyNs3DeviceEnergyModelContainer_wrapper_registry) typedef struct { PyObject_HEAD ns3::DeviceEnergyModelHelper *obj; PyObject *inst_dict; PyBindGenWrapperFlags flags:8; } PyNs3DeviceEnergyModelHelper; extern PyTypeObject *_PyNs3DeviceEnergyModelHelper_Type; #define PyNs3DeviceEnergyModelHelper_Type (*_PyNs3DeviceEnergyModelHelper_Type) class PyNs3DeviceEnergyModelHelper__PythonHelper : public ns3::DeviceEnergyModelHelper { public: PyObject *m_pyself; void set_pyobj(PyObject *pyobj) { Py_XDECREF(m_pyself); Py_INCREF(pyobj); m_pyself = pyobj; } virtual ~PyNs3DeviceEnergyModelHelper__PythonHelper() { Py_CLEAR(m_pyself); } }; extern std::map<void*, PyObject*> *_PyNs3DeviceEnergyModelHelper_wrapper_registry; #define PyNs3DeviceEnergyModelHelper_wrapper_registry (*_PyNs3DeviceEnergyModelHelper_wrapper_registry) typedef struct { PyObject_HEAD ns3::EnergySourceHelper *obj; PyObject *inst_dict; PyBindGenWrapperFlags flags:8; } PyNs3EnergySourceHelper; extern PyTypeObject *_PyNs3EnergySourceHelper_Type; #define PyNs3EnergySourceHelper_Type (*_PyNs3EnergySourceHelper_Type) class PyNs3EnergySourceHelper__PythonHelper : public ns3::EnergySourceHelper { public: PyObject *m_pyself; void set_pyobj(PyObject *pyobj) { Py_XDECREF(m_pyself); Py_INCREF(pyobj); m_pyself = pyobj; } virtual ~PyNs3EnergySourceHelper__PythonHelper() { Py_CLEAR(m_pyself); } }; extern std::map<void*, PyObject*> *_PyNs3EnergySourceHelper_wrapper_registry; #define PyNs3EnergySourceHelper_wrapper_registry (*_PyNs3EnergySourceHelper_wrapper_registry) typedef struct { PyObject_HEAD ns3::EventId *obj; PyBindGenWrapperFlags flags:8; } PyNs3EventId; extern PyTypeObject *_PyNs3EventId_Type; #define PyNs3EventId_Type (*_PyNs3EventId_Type) extern std::map<void*, PyObject*> *_PyNs3EventId_wrapper_registry; #define PyNs3EventId_wrapper_registry (*_PyNs3EventId_wrapper_registry) typedef struct { PyObject_HEAD ns3::Ipv4Address *obj; PyBindGenWrapperFlags flags:8; } PyNs3Ipv4Address; extern PyTypeObject *_PyNs3Ipv4Address_Type; #define PyNs3Ipv4Address_Type (*_PyNs3Ipv4Address_Type) extern std::map<void*, PyObject*> *_PyNs3Ipv4Address_wrapper_registry; #define PyNs3Ipv4Address_wrapper_registry (*_PyNs3Ipv4Address_wrapper_registry) typedef struct { PyObject_HEAD ns3::Ipv4Mask *obj; PyBindGenWrapperFlags flags:8; } PyNs3Ipv4Mask; extern PyTypeObject *_PyNs3Ipv4Mask_Type; #define PyNs3Ipv4Mask_Type (*_PyNs3Ipv4Mask_Type) extern std::map<void*, PyObject*> *_PyNs3Ipv4Mask_wrapper_registry; #define PyNs3Ipv4Mask_wrapper_registry (*_PyNs3Ipv4Mask_wrapper_registry) typedef struct { PyObject_HEAD ns3::Ipv6Address *obj; PyBindGenWrapperFlags flags:8; } PyNs3Ipv6Address; extern PyTypeObject *_PyNs3Ipv6Address_Type; #define PyNs3Ipv6Address_Type (*_PyNs3Ipv6Address_Type) extern std::map<void*, PyObject*> *_PyNs3Ipv6Address_wrapper_registry; #define PyNs3Ipv6Address_wrapper_registry (*_PyNs3Ipv6Address_wrapper_registry) typedef struct { PyObject_HEAD ns3::Ipv6Prefix *obj; PyBindGenWrapperFlags flags:8; } PyNs3Ipv6Prefix; extern PyTypeObject *_PyNs3Ipv6Prefix_Type; #define PyNs3Ipv6Prefix_Type (*_PyNs3Ipv6Prefix_Type) extern std::map<void*, PyObject*> *_PyNs3Ipv6Prefix_wrapper_registry; #define PyNs3Ipv6Prefix_wrapper_registry (*_PyNs3Ipv6Prefix_wrapper_registry) typedef struct { PyObject_HEAD ns3::NetDeviceContainer *obj; PyBindGenWrapperFlags flags:8; } PyNs3NetDeviceContainer; extern PyTypeObject *_PyNs3NetDeviceContainer_Type; #define PyNs3NetDeviceContainer_Type (*_PyNs3NetDeviceContainer_Type) extern std::map<void*, PyObject*> *_PyNs3NetDeviceContainer_wrapper_registry; #define PyNs3NetDeviceContainer_wrapper_registry (*_PyNs3NetDeviceContainer_wrapper_registry) typedef struct { PyObject_HEAD ns3::NodeContainer *obj; PyBindGenWrapperFlags flags:8; } PyNs3NodeContainer; extern PyTypeObject *_PyNs3NodeContainer_Type; #define PyNs3NodeContainer_Type (*_PyNs3NodeContainer_Type) extern std::map<void*, PyObject*> *_PyNs3NodeContainer_wrapper_registry; #define PyNs3NodeContainer_wrapper_registry (*_PyNs3NodeContainer_wrapper_registry) typedef struct { PyObject_HEAD ns3::ObjectBase *obj; PyObject *inst_dict; PyBindGenWrapperFlags flags:8; } PyNs3ObjectBase; extern PyTypeObject *_PyNs3ObjectBase_Type; #define PyNs3ObjectBase_Type (*_PyNs3ObjectBase_Type) class PyNs3ObjectBase__PythonHelper : public ns3::ObjectBase { public: PyObject *m_pyself; void set_pyobj(PyObject *pyobj) { Py_XDECREF(m_pyself); Py_INCREF(pyobj); m_pyself = pyobj; } virtual ~PyNs3ObjectBase__PythonHelper() { Py_CLEAR(m_pyself); } }; extern std::map<void*, PyObject*> *_PyNs3ObjectBase_wrapper_registry; #define PyNs3ObjectBase_wrapper_registry (*_PyNs3ObjectBase_wrapper_registry) typedef struct { PyObject_HEAD ns3::ObjectDeleter *obj; PyBindGenWrapperFlags flags:8; } PyNs3ObjectDeleter; extern PyTypeObject *_PyNs3ObjectDeleter_Type; #define PyNs3ObjectDeleter_Type (*_PyNs3ObjectDeleter_Type) extern std::map<void*, PyObject*> *_PyNs3ObjectDeleter_wrapper_registry; #define PyNs3ObjectDeleter_wrapper_registry (*_PyNs3ObjectDeleter_wrapper_registry) typedef struct { PyObject_HEAD ns3::ObjectFactory *obj; PyBindGenWrapperFlags flags:8; } PyNs3ObjectFactory; extern PyTypeObject *_PyNs3ObjectFactory_Type; #define PyNs3ObjectFactory_Type (*_PyNs3ObjectFactory_Type) extern std::map<void*, PyObject*> *_PyNs3ObjectFactory_wrapper_registry; #define PyNs3ObjectFactory_wrapper_registry (*_PyNs3ObjectFactory_wrapper_registry) typedef struct { PyObject_HEAD ns3::PacketMetadata *obj; PyBindGenWrapperFlags flags:8; } PyNs3PacketMetadata; extern PyTypeObject *_PyNs3PacketMetadata_Type; #define PyNs3PacketMetadata_Type (*_PyNs3PacketMetadata_Type) extern std::map<void*, PyObject*> *_PyNs3PacketMetadata_wrapper_registry; #define PyNs3PacketMetadata_wrapper_registry (*_PyNs3PacketMetadata_wrapper_registry) typedef struct { PyObject_HEAD ns3::PacketMetadata::Item *obj; PyBindGenWrapperFlags flags:8; } PyNs3PacketMetadataItem; extern PyTypeObject *_PyNs3PacketMetadataItem_Type; #define PyNs3PacketMetadataItem_Type (*_PyNs3PacketMetadataItem_Type) extern std::map<void*, PyObject*> *_PyNs3PacketMetadataItem_wrapper_registry; #define PyNs3PacketMetadataItem_wrapper_registry (*_PyNs3PacketMetadataItem_wrapper_registry) typedef struct { PyObject_HEAD ns3::PacketMetadata::ItemIterator *obj; PyBindGenWrapperFlags flags:8; } PyNs3PacketMetadataItemIterator; extern PyTypeObject *_PyNs3PacketMetadataItemIterator_Type; #define PyNs3PacketMetadataItemIterator_Type (*_PyNs3PacketMetadataItemIterator_Type) extern std::map<void*, PyObject*> *_PyNs3PacketMetadataItemIterator_wrapper_registry; #define PyNs3PacketMetadataItemIterator_wrapper_registry (*_PyNs3PacketMetadataItemIterator_wrapper_registry) typedef struct { PyObject_HEAD ns3::PacketTagIterator *obj; PyBindGenWrapperFlags flags:8; } PyNs3PacketTagIterator; extern PyTypeObject *_PyNs3PacketTagIterator_Type; #define PyNs3PacketTagIterator_Type (*_PyNs3PacketTagIterator_Type) extern std::map<void*, PyObject*> *_PyNs3PacketTagIterator_wrapper_registry; #define PyNs3PacketTagIterator_wrapper_registry (*_PyNs3PacketTagIterator_wrapper_registry) typedef struct { PyObject_HEAD ns3::PacketTagIterator::Item *obj; PyBindGenWrapperFlags flags:8; } PyNs3PacketTagIteratorItem; extern PyTypeObject *_PyNs3PacketTagIteratorItem_Type; #define PyNs3PacketTagIteratorItem_Type (*_PyNs3PacketTagIteratorItem_Type) extern std::map<void*, PyObject*> *_PyNs3PacketTagIteratorItem_wrapper_registry; #define PyNs3PacketTagIteratorItem_wrapper_registry (*_PyNs3PacketTagIteratorItem_wrapper_registry) typedef struct { PyObject_HEAD ns3::PacketTagList *obj; PyBindGenWrapperFlags flags:8; } PyNs3PacketTagList; extern PyTypeObject *_PyNs3PacketTagList_Type; #define PyNs3PacketTagList_Type (*_PyNs3PacketTagList_Type) extern std::map<void*, PyObject*> *_PyNs3PacketTagList_wrapper_registry; #define PyNs3PacketTagList_wrapper_registry (*_PyNs3PacketTagList_wrapper_registry) typedef struct { PyObject_HEAD ns3::PacketTagList::TagData *obj; PyBindGenWrapperFlags flags:8; } PyNs3PacketTagListTagData; extern PyTypeObject *_PyNs3PacketTagListTagData_Type; #define PyNs3PacketTagListTagData_Type (*_PyNs3PacketTagListTagData_Type) extern std::map<void*, PyObject*> *_PyNs3PacketTagListTagData_wrapper_registry; #define PyNs3PacketTagListTagData_wrapper_registry (*_PyNs3PacketTagListTagData_wrapper_registry) typedef struct { PyObject_HEAD ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter > *obj; PyObject *inst_dict; PyBindGenWrapperFlags flags:8; } PyNs3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter; extern PyTypeObject *_PyNs3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_Type; #define PyNs3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_Type (*_PyNs3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_Type) #include <map> #include <string> #include <typeinfo> #if defined(__GNUC__) && __GNUC__ >= 3 # include <cxxabi.h> #endif #define PBG_TYPEMAP_DEBUG 0 namespace pybindgen { class TypeMap { std::map<std::string, PyTypeObject *> m_map; public: TypeMap() {} void register_wrapper(const std::type_info &cpp_type_info, PyTypeObject *python_wrapper) { #if PBG_TYPEMAP_DEBUG std::cerr << "register_wrapper(this=" << this << ", type_name=" << cpp_type_info.name() << ", python_wrapper=" << python_wrapper->tp_name << ")" << std::endl; #endif m_map[std::string(cpp_type_info.name())] = python_wrapper; } PyTypeObject * lookup_wrapper(const std::type_info &cpp_type_info, PyTypeObject *fallback_wrapper) { #if PBG_TYPEMAP_DEBUG std::cerr << "lookup_wrapper(this=" << this << ", type_name=" << cpp_type_info.name() << ")" << std::endl; #endif PyTypeObject *python_wrapper = m_map[cpp_type_info.name()]; if (python_wrapper) return python_wrapper; else { #if defined(__GNUC__) && __GNUC__ >= 3 // Get closest (in the single inheritance tree provided by cxxabi.h) // registered python wrapper. const abi::__si_class_type_info *_typeinfo = dynamic_cast<const abi::__si_class_type_info*> (&cpp_type_info); #if PBG_TYPEMAP_DEBUG std::cerr << " -> looking at C++ type " << _typeinfo->name() << std::endl; #endif while (_typeinfo && (python_wrapper = m_map[std::string(_typeinfo->name())]) == 0) { _typeinfo = dynamic_cast<const abi::__si_class_type_info*> (_typeinfo->__base_type); #if PBG_TYPEMAP_DEBUG std::cerr << " -> looking at C++ type " << _typeinfo->name() << std::endl; #endif } #if PBG_TYPEMAP_DEBUG if (python_wrapper) { std::cerr << " -> found match " << std::endl; } else { std::cerr << " -> return fallback wrapper" << std::endl; } #endif return python_wrapper? python_wrapper : fallback_wrapper; #else // non gcc 3+ compilers can only match against explicitly registered classes, not hidden subclasses return fallback_wrapper; #endif } } }; } extern pybindgen::TypeMap *_PyNs3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter__typeid_map; #define PyNs3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter__typeid_map (*_PyNs3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter__typeid_map) typedef struct { PyObject_HEAD ns3::Simulator *obj; PyBindGenWrapperFlags flags:8; } PyNs3Simulator; extern PyTypeObject *_PyNs3Simulator_Type; #define PyNs3Simulator_Type (*_PyNs3Simulator_Type) extern std::map<void*, PyObject*> *_PyNs3Simulator_wrapper_registry; #define PyNs3Simulator_wrapper_registry (*_PyNs3Simulator_wrapper_registry) typedef struct { PyObject_HEAD ns3::Tag *obj; PyObject *inst_dict; PyBindGenWrapperFlags flags:8; } PyNs3Tag; extern PyTypeObject *_PyNs3Tag_Type; #define PyNs3Tag_Type (*_PyNs3Tag_Type) typedef struct { PyObject_HEAD ns3::TagBuffer *obj; PyBindGenWrapperFlags flags:8; } PyNs3TagBuffer; extern PyTypeObject *_PyNs3TagBuffer_Type; #define PyNs3TagBuffer_Type (*_PyNs3TagBuffer_Type) extern std::map<void*, PyObject*> *_PyNs3TagBuffer_wrapper_registry; #define PyNs3TagBuffer_wrapper_registry (*_PyNs3TagBuffer_wrapper_registry) typedef struct { PyObject_HEAD ns3::TracedValue< double > *obj; PyBindGenWrapperFlags flags:8; } PyNs3TracedValue__Double; extern PyTypeObject *_PyNs3TracedValue__Double_Type; #define PyNs3TracedValue__Double_Type (*_PyNs3TracedValue__Double_Type) extern std::map<void*, PyObject*> *_PyNs3TracedValue__Double_wrapper_registry; #define PyNs3TracedValue__Double_wrapper_registry (*_PyNs3TracedValue__Double_wrapper_registry) typedef struct { PyObject_HEAD ns3::TypeId *obj; PyBindGenWrapperFlags flags:8; } PyNs3TypeId; extern PyTypeObject *_PyNs3TypeId_Type; #define PyNs3TypeId_Type (*_PyNs3TypeId_Type) extern std::map<void*, PyObject*> *_PyNs3TypeId_wrapper_registry; #define PyNs3TypeId_wrapper_registry (*_PyNs3TypeId_wrapper_registry) typedef struct { PyObject_HEAD ns3::TypeId::AttributeInformation *obj; PyBindGenWrapperFlags flags:8; } PyNs3TypeIdAttributeInformation; extern PyTypeObject *_PyNs3TypeIdAttributeInformation_Type; #define PyNs3TypeIdAttributeInformation_Type (*_PyNs3TypeIdAttributeInformation_Type) extern std::map<void*, PyObject*> *_PyNs3TypeIdAttributeInformation_wrapper_registry; #define PyNs3TypeIdAttributeInformation_wrapper_registry (*_PyNs3TypeIdAttributeInformation_wrapper_registry) typedef struct { PyObject_HEAD ns3::TypeId::TraceSourceInformation *obj; PyBindGenWrapperFlags flags:8; } PyNs3TypeIdTraceSourceInformation; extern PyTypeObject *_PyNs3TypeIdTraceSourceInformation_Type; #define PyNs3TypeIdTraceSourceInformation_Type (*_PyNs3TypeIdTraceSourceInformation_Type) extern std::map<void*, PyObject*> *_PyNs3TypeIdTraceSourceInformation_wrapper_registry; #define PyNs3TypeIdTraceSourceInformation_wrapper_registry (*_PyNs3TypeIdTraceSourceInformation_wrapper_registry) typedef struct { PyObject_HEAD ns3::Vector2D *obj; PyBindGenWrapperFlags flags:8; } PyNs3Vector2D; extern PyTypeObject *_PyNs3Vector2D_Type; #define PyNs3Vector2D_Type (*_PyNs3Vector2D_Type) extern std::map<void*, PyObject*> *_PyNs3Vector2D_wrapper_registry; #define PyNs3Vector2D_wrapper_registry (*_PyNs3Vector2D_wrapper_registry) typedef struct { PyObject_HEAD ns3::Vector3D *obj; PyBindGenWrapperFlags flags:8; } PyNs3Vector3D; extern PyTypeObject *_PyNs3Vector3D_Type; #define PyNs3Vector3D_Type (*_PyNs3Vector3D_Type) extern std::map<void*, PyObject*> *_PyNs3Vector3D_wrapper_registry; #define PyNs3Vector3D_wrapper_registry (*_PyNs3Vector3D_wrapper_registry) typedef struct { PyObject_HEAD ns3::empty *obj; PyBindGenWrapperFlags flags:8; } PyNs3Empty; extern PyTypeObject *_PyNs3Empty_Type; #define PyNs3Empty_Type (*_PyNs3Empty_Type) extern std::map<void*, PyObject*> *_PyNs3Empty_wrapper_registry; #define PyNs3Empty_wrapper_registry (*_PyNs3Empty_wrapper_registry) typedef struct { PyObject_HEAD ns3::int64x64_t *obj; PyBindGenWrapperFlags flags:8; } PyNs3Int64x64_t; extern PyTypeObject *_PyNs3Int64x64_t_Type; #define PyNs3Int64x64_t_Type (*_PyNs3Int64x64_t_Type) extern std::map<void*, PyObject*> *_PyNs3Int64x64_t_wrapper_registry; #define PyNs3Int64x64_t_wrapper_registry (*_PyNs3Int64x64_t_wrapper_registry) typedef struct { PyObject_HEAD ns3::Chunk *obj; PyObject *inst_dict; PyBindGenWrapperFlags flags:8; } PyNs3Chunk; extern PyTypeObject *_PyNs3Chunk_Type; #define PyNs3Chunk_Type (*_PyNs3Chunk_Type) typedef struct { PyObject_HEAD ns3::Header *obj; PyObject *inst_dict; PyBindGenWrapperFlags flags:8; } PyNs3Header; extern PyTypeObject *_PyNs3Header_Type; #define PyNs3Header_Type (*_PyNs3Header_Type) typedef struct { PyObject_HEAD ns3::Object *obj; PyObject *inst_dict; PyBindGenWrapperFlags flags:8; } PyNs3Object; extern PyTypeObject *_PyNs3Object_Type; #define PyNs3Object_Type (*_PyNs3Object_Type) class PyNs3Object__PythonHelper : public ns3::Object { public: PyObject *m_pyself; void set_pyobj(PyObject *pyobj) { Py_XDECREF(m_pyself); Py_INCREF(pyobj); m_pyself = pyobj; } virtual ~PyNs3Object__PythonHelper() { Py_CLEAR(m_pyself); } }; typedef struct { PyObject_HEAD ns3::Object::AggregateIterator *obj; PyBindGenWrapperFlags flags:8; } PyNs3ObjectAggregateIterator; extern PyTypeObject *_PyNs3ObjectAggregateIterator_Type; #define PyNs3ObjectAggregateIterator_Type (*_PyNs3ObjectAggregateIterator_Type) extern std::map<void*, PyObject*> *_PyNs3ObjectAggregateIterator_wrapper_registry; #define PyNs3ObjectAggregateIterator_wrapper_registry (*_PyNs3ObjectAggregateIterator_wrapper_registry) typedef struct { PyObject_HEAD ns3::RandomVariableStream *obj; PyObject *inst_dict; PyBindGenWrapperFlags flags:8; } PyNs3RandomVariableStream; extern PyTypeObject *_PyNs3RandomVariableStream_Type; #define PyNs3RandomVariableStream_Type (*_PyNs3RandomVariableStream_Type) class PyNs3RandomVariableStream__PythonHelper : public ns3::RandomVariableStream { public: PyObject *m_pyself; void set_pyobj(PyObject *pyobj) { Py_XDECREF(m_pyself); Py_INCREF(pyobj); m_pyself = pyobj; } virtual ~PyNs3RandomVariableStream__PythonHelper() { Py_CLEAR(m_pyself); } }; typedef struct { PyObject_HEAD ns3::SequentialRandomVariable *obj; PyObject *inst_dict; PyBindGenWrapperFlags flags:8; } PyNs3SequentialRandomVariable; extern PyTypeObject *_PyNs3SequentialRandomVariable_Type; #define PyNs3SequentialRandomVariable_Type (*_PyNs3SequentialRandomVariable_Type) class PyNs3SequentialRandomVariable__PythonHelper : public ns3::SequentialRandomVariable { public: PyObject *m_pyself; void set_pyobj(PyObject *pyobj) { Py_XDECREF(m_pyself); Py_INCREF(pyobj); m_pyself = pyobj; } virtual ~PyNs3SequentialRandomVariable__PythonHelper() { Py_CLEAR(m_pyself); } }; typedef struct { PyObject_HEAD ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> > *obj; PyBindGenWrapperFlags flags:8; } PyNs3SimpleRefCount__Ns3AttributeAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeAccessor__gt__; extern PyTypeObject *_PyNs3SimpleRefCount__Ns3AttributeAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeAccessor__gt___Type; #define PyNs3SimpleRefCount__Ns3AttributeAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeAccessor__gt___Type (*_PyNs3SimpleRefCount__Ns3AttributeAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeAccessor__gt___Type) extern pybindgen::TypeMap *_PyNs3SimpleRefCount__Ns3AttributeAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeAccessor__gt____typeid_map; #define PyNs3SimpleRefCount__Ns3AttributeAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeAccessor__gt____typeid_map (*_PyNs3SimpleRefCount__Ns3AttributeAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeAccessor__gt____typeid_map) typedef struct { PyObject_HEAD ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> > *obj; PyBindGenWrapperFlags flags:8; } PyNs3SimpleRefCount__Ns3AttributeChecker_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeChecker__gt__; extern PyTypeObject *_PyNs3SimpleRefCount__Ns3AttributeChecker_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeChecker__gt___Type; #define PyNs3SimpleRefCount__Ns3AttributeChecker_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeChecker__gt___Type (*_PyNs3SimpleRefCount__Ns3AttributeChecker_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeChecker__gt___Type) extern pybindgen::TypeMap *_PyNs3SimpleRefCount__Ns3AttributeChecker_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeChecker__gt____typeid_map; #define PyNs3SimpleRefCount__Ns3AttributeChecker_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeChecker__gt____typeid_map (*_PyNs3SimpleRefCount__Ns3AttributeChecker_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeChecker__gt____typeid_map) typedef struct { PyObject_HEAD ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> > *obj; PyBindGenWrapperFlags flags:8; } PyNs3SimpleRefCount__Ns3AttributeValue_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeValue__gt__; extern PyTypeObject *_PyNs3SimpleRefCount__Ns3AttributeValue_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeValue__gt___Type; #define PyNs3SimpleRefCount__Ns3AttributeValue_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeValue__gt___Type (*_PyNs3SimpleRefCount__Ns3AttributeValue_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeValue__gt___Type) extern pybindgen::TypeMap *_PyNs3SimpleRefCount__Ns3AttributeValue_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeValue__gt____typeid_map; #define PyNs3SimpleRefCount__Ns3AttributeValue_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeValue__gt____typeid_map (*_PyNs3SimpleRefCount__Ns3AttributeValue_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeValue__gt____typeid_map) typedef struct { PyObject_HEAD ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> > *obj; PyBindGenWrapperFlags flags:8; } PyNs3SimpleRefCount__Ns3CallbackImplBase_Ns3Empty_Ns3DefaultDeleter__lt__ns3CallbackImplBase__gt__; extern PyTypeObject *_PyNs3SimpleRefCount__Ns3CallbackImplBase_Ns3Empty_Ns3DefaultDeleter__lt__ns3CallbackImplBase__gt___Type; #define PyNs3SimpleRefCount__Ns3CallbackImplBase_Ns3Empty_Ns3DefaultDeleter__lt__ns3CallbackImplBase__gt___Type (*_PyNs3SimpleRefCount__Ns3CallbackImplBase_Ns3Empty_Ns3DefaultDeleter__lt__ns3CallbackImplBase__gt___Type) extern pybindgen::TypeMap *_PyNs3SimpleRefCount__Ns3CallbackImplBase_Ns3Empty_Ns3DefaultDeleter__lt__ns3CallbackImplBase__gt____typeid_map; #define PyNs3SimpleRefCount__Ns3CallbackImplBase_Ns3Empty_Ns3DefaultDeleter__lt__ns3CallbackImplBase__gt____typeid_map (*_PyNs3SimpleRefCount__Ns3CallbackImplBase_Ns3Empty_Ns3DefaultDeleter__lt__ns3CallbackImplBase__gt____typeid_map) typedef struct { PyObject_HEAD ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> > *obj; PyBindGenWrapperFlags flags:8; } PyNs3SimpleRefCount__Ns3EventImpl_Ns3Empty_Ns3DefaultDeleter__lt__ns3EventImpl__gt__; extern PyTypeObject *_PyNs3SimpleRefCount__Ns3EventImpl_Ns3Empty_Ns3DefaultDeleter__lt__ns3EventImpl__gt___Type; #define PyNs3SimpleRefCount__Ns3EventImpl_Ns3Empty_Ns3DefaultDeleter__lt__ns3EventImpl__gt___Type (*_PyNs3SimpleRefCount__Ns3EventImpl_Ns3Empty_Ns3DefaultDeleter__lt__ns3EventImpl__gt___Type) extern pybindgen::TypeMap *_PyNs3SimpleRefCount__Ns3EventImpl_Ns3Empty_Ns3DefaultDeleter__lt__ns3EventImpl__gt____typeid_map; #define PyNs3SimpleRefCount__Ns3EventImpl_Ns3Empty_Ns3DefaultDeleter__lt__ns3EventImpl__gt____typeid_map (*_PyNs3SimpleRefCount__Ns3EventImpl_Ns3Empty_Ns3DefaultDeleter__lt__ns3EventImpl__gt____typeid_map) typedef struct { PyObject_HEAD ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> > *obj; PyBindGenWrapperFlags flags:8; } PyNs3SimpleRefCount__Ns3NixVector_Ns3Empty_Ns3DefaultDeleter__lt__ns3NixVector__gt__; extern PyTypeObject *_PyNs3SimpleRefCount__Ns3NixVector_Ns3Empty_Ns3DefaultDeleter__lt__ns3NixVector__gt___Type; #define PyNs3SimpleRefCount__Ns3NixVector_Ns3Empty_Ns3DefaultDeleter__lt__ns3NixVector__gt___Type (*_PyNs3SimpleRefCount__Ns3NixVector_Ns3Empty_Ns3DefaultDeleter__lt__ns3NixVector__gt___Type) extern pybindgen::TypeMap *_PyNs3SimpleRefCount__Ns3NixVector_Ns3Empty_Ns3DefaultDeleter__lt__ns3NixVector__gt____typeid_map; #define PyNs3SimpleRefCount__Ns3NixVector_Ns3Empty_Ns3DefaultDeleter__lt__ns3NixVector__gt____typeid_map (*_PyNs3SimpleRefCount__Ns3NixVector_Ns3Empty_Ns3DefaultDeleter__lt__ns3NixVector__gt____typeid_map) typedef struct { PyObject_HEAD ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> > *obj; PyBindGenWrapperFlags flags:8; } PyNs3SimpleRefCount__Ns3Packet_Ns3Empty_Ns3DefaultDeleter__lt__ns3Packet__gt__; extern PyTypeObject *_PyNs3SimpleRefCount__Ns3Packet_Ns3Empty_Ns3DefaultDeleter__lt__ns3Packet__gt___Type; #define PyNs3SimpleRefCount__Ns3Packet_Ns3Empty_Ns3DefaultDeleter__lt__ns3Packet__gt___Type (*_PyNs3SimpleRefCount__Ns3Packet_Ns3Empty_Ns3DefaultDeleter__lt__ns3Packet__gt___Type) extern pybindgen::TypeMap *_PyNs3SimpleRefCount__Ns3Packet_Ns3Empty_Ns3DefaultDeleter__lt__ns3Packet__gt____typeid_map; #define PyNs3SimpleRefCount__Ns3Packet_Ns3Empty_Ns3DefaultDeleter__lt__ns3Packet__gt____typeid_map (*_PyNs3SimpleRefCount__Ns3Packet_Ns3Empty_Ns3DefaultDeleter__lt__ns3Packet__gt____typeid_map) typedef struct { PyObject_HEAD ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> > *obj; PyBindGenWrapperFlags flags:8; } PyNs3SimpleRefCount__Ns3TraceSourceAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3TraceSourceAccessor__gt__; extern PyTypeObject *_PyNs3SimpleRefCount__Ns3TraceSourceAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3TraceSourceAccessor__gt___Type; #define PyNs3SimpleRefCount__Ns3TraceSourceAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3TraceSourceAccessor__gt___Type (*_PyNs3SimpleRefCount__Ns3TraceSourceAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3TraceSourceAccessor__gt___Type) extern pybindgen::TypeMap *_PyNs3SimpleRefCount__Ns3TraceSourceAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3TraceSourceAccessor__gt____typeid_map; #define PyNs3SimpleRefCount__Ns3TraceSourceAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3TraceSourceAccessor__gt____typeid_map (*_PyNs3SimpleRefCount__Ns3TraceSourceAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3TraceSourceAccessor__gt____typeid_map) typedef struct { PyObject_HEAD ns3::Time *obj; PyBindGenWrapperFlags flags:8; } PyNs3Time; extern PyTypeObject *_PyNs3Time_Type; #define PyNs3Time_Type (*_PyNs3Time_Type) extern std::map<void*, PyObject*> *_PyNs3Time_wrapper_registry; #define PyNs3Time_wrapper_registry (*_PyNs3Time_wrapper_registry) typedef struct { PyObject_HEAD ns3::TraceSourceAccessor *obj; PyBindGenWrapperFlags flags:8; } PyNs3TraceSourceAccessor; extern PyTypeObject *_PyNs3TraceSourceAccessor_Type; #define PyNs3TraceSourceAccessor_Type (*_PyNs3TraceSourceAccessor_Type) typedef struct { PyObject_HEAD ns3::Trailer *obj; PyObject *inst_dict; PyBindGenWrapperFlags flags:8; } PyNs3Trailer; extern PyTypeObject *_PyNs3Trailer_Type; #define PyNs3Trailer_Type (*_PyNs3Trailer_Type) typedef struct { PyObject_HEAD ns3::TriangularRandomVariable *obj; PyObject *inst_dict; PyBindGenWrapperFlags flags:8; } PyNs3TriangularRandomVariable; extern PyTypeObject *_PyNs3TriangularRandomVariable_Type; #define PyNs3TriangularRandomVariable_Type (*_PyNs3TriangularRandomVariable_Type) class PyNs3TriangularRandomVariable__PythonHelper : public ns3::TriangularRandomVariable { public: PyObject *m_pyself; void set_pyobj(PyObject *pyobj) { Py_XDECREF(m_pyself); Py_INCREF(pyobj); m_pyself = pyobj; } virtual ~PyNs3TriangularRandomVariable__PythonHelper() { Py_CLEAR(m_pyself); } }; typedef struct { PyObject_HEAD ns3::UniformRandomVariable *obj; PyObject *inst_dict; PyBindGenWrapperFlags flags:8; } PyNs3UniformRandomVariable; extern PyTypeObject *_PyNs3UniformRandomVariable_Type; #define PyNs3UniformRandomVariable_Type (*_PyNs3UniformRandomVariable_Type) class PyNs3UniformRandomVariable__PythonHelper : public ns3::UniformRandomVariable { public: PyObject *m_pyself; void set_pyobj(PyObject *pyobj) { Py_XDECREF(m_pyself); Py_INCREF(pyobj); m_pyself = pyobj; } virtual ~PyNs3UniformRandomVariable__PythonHelper() { Py_CLEAR(m_pyself); } }; typedef struct { PyObject_HEAD ns3::WeibullRandomVariable *obj; PyObject *inst_dict; PyBindGenWrapperFlags flags:8; } PyNs3WeibullRandomVariable; extern PyTypeObject *_PyNs3WeibullRandomVariable_Type; #define PyNs3WeibullRandomVariable_Type (*_PyNs3WeibullRandomVariable_Type) class PyNs3WeibullRandomVariable__PythonHelper : public ns3::WeibullRandomVariable { public: PyObject *m_pyself; void set_pyobj(PyObject *pyobj) { Py_XDECREF(m_pyself); Py_INCREF(pyobj); m_pyself = pyobj; } virtual ~PyNs3WeibullRandomVariable__PythonHelper() { Py_CLEAR(m_pyself); } }; typedef struct { PyObject_HEAD ns3::ZetaRandomVariable *obj; PyObject *inst_dict; PyBindGenWrapperFlags flags:8; } PyNs3ZetaRandomVariable; extern PyTypeObject *_PyNs3ZetaRandomVariable_Type; #define PyNs3ZetaRandomVariable_Type (*_PyNs3ZetaRandomVariable_Type) class PyNs3ZetaRandomVariable__PythonHelper : public ns3::ZetaRandomVariable { public: PyObject *m_pyself; void set_pyobj(PyObject *pyobj) { Py_XDECREF(m_pyself); Py_INCREF(pyobj); m_pyself = pyobj; } virtual ~PyNs3ZetaRandomVariable__PythonHelper() { Py_CLEAR(m_pyself); } }; typedef struct { PyObject_HEAD ns3::ZipfRandomVariable *obj; PyObject *inst_dict; PyBindGenWrapperFlags flags:8; } PyNs3ZipfRandomVariable; extern PyTypeObject *_PyNs3ZipfRandomVariable_Type; #define PyNs3ZipfRandomVariable_Type (*_PyNs3ZipfRandomVariable_Type) class PyNs3ZipfRandomVariable__PythonHelper : public ns3::ZipfRandomVariable { public: PyObject *m_pyself; void set_pyobj(PyObject *pyobj) { Py_XDECREF(m_pyself); Py_INCREF(pyobj); m_pyself = pyobj; } virtual ~PyNs3ZipfRandomVariable__PythonHelper() { Py_CLEAR(m_pyself); } }; typedef struct { PyObject_HEAD ns3::AttributeAccessor *obj; PyBindGenWrapperFlags flags:8; } PyNs3AttributeAccessor; extern PyTypeObject *_PyNs3AttributeAccessor_Type; #define PyNs3AttributeAccessor_Type (*_PyNs3AttributeAccessor_Type) typedef struct { PyObject_HEAD ns3::AttributeChecker *obj; PyBindGenWrapperFlags flags:8; } PyNs3AttributeChecker; extern PyTypeObject *_PyNs3AttributeChecker_Type; #define PyNs3AttributeChecker_Type (*_PyNs3AttributeChecker_Type) typedef struct { PyObject_HEAD ns3::AttributeValue *obj; PyBindGenWrapperFlags flags:8; } PyNs3AttributeValue; extern PyTypeObject *_PyNs3AttributeValue_Type; #define PyNs3AttributeValue_Type (*_PyNs3AttributeValue_Type) typedef struct { PyObject_HEAD ns3::BooleanChecker *obj; PyBindGenWrapperFlags flags:8; } PyNs3BooleanChecker; extern PyTypeObject *_PyNs3BooleanChecker_Type; #define PyNs3BooleanChecker_Type (*_PyNs3BooleanChecker_Type) typedef struct { PyObject_HEAD ns3::BooleanValue *obj; PyBindGenWrapperFlags flags:8; } PyNs3BooleanValue; extern PyTypeObject *_PyNs3BooleanValue_Type; #define PyNs3BooleanValue_Type (*_PyNs3BooleanValue_Type) typedef struct { PyObject_HEAD ns3::CallbackChecker *obj; PyBindGenWrapperFlags flags:8; } PyNs3CallbackChecker; extern PyTypeObject *_PyNs3CallbackChecker_Type; #define PyNs3CallbackChecker_Type (*_PyNs3CallbackChecker_Type) typedef struct { PyObject_HEAD ns3::CallbackImplBase *obj; PyBindGenWrapperFlags flags:8; } PyNs3CallbackImplBase; extern PyTypeObject *_PyNs3CallbackImplBase_Type; #define PyNs3CallbackImplBase_Type (*_PyNs3CallbackImplBase_Type) typedef struct { PyObject_HEAD ns3::CallbackValue *obj; PyBindGenWrapperFlags flags:8; } PyNs3CallbackValue; extern PyTypeObject *_PyNs3CallbackValue_Type; #define PyNs3CallbackValue_Type (*_PyNs3CallbackValue_Type) typedef struct { PyObject_HEAD ns3::Channel *obj; PyObject *inst_dict; PyBindGenWrapperFlags flags:8; } PyNs3Channel; extern PyTypeObject *_PyNs3Channel_Type; #define PyNs3Channel_Type (*_PyNs3Channel_Type) class PyNs3Channel__PythonHelper : public ns3::Channel { public: PyObject *m_pyself; void set_pyobj(PyObject *pyobj) { Py_XDECREF(m_pyself); Py_INCREF(pyobj); m_pyself = pyobj; } virtual ~PyNs3Channel__PythonHelper() { Py_CLEAR(m_pyself); } }; typedef struct { PyObject_HEAD ns3::ConstantRandomVariable *obj; PyObject *inst_dict; PyBindGenWrapperFlags flags:8; } PyNs3ConstantRandomVariable; extern PyTypeObject *_PyNs3ConstantRandomVariable_Type; #define PyNs3ConstantRandomVariable_Type (*_PyNs3ConstantRandomVariable_Type) class PyNs3ConstantRandomVariable__PythonHelper : public ns3::ConstantRandomVariable { public: PyObject *m_pyself; void set_pyobj(PyObject *pyobj) { Py_XDECREF(m_pyself); Py_INCREF(pyobj); m_pyself = pyobj; } virtual ~PyNs3ConstantRandomVariable__PythonHelper() { Py_CLEAR(m_pyself); } }; typedef struct { PyObject_HEAD ns3::DeterministicRandomVariable *obj; PyObject *inst_dict; PyBindGenWrapperFlags flags:8; } PyNs3DeterministicRandomVariable; extern PyTypeObject *_PyNs3DeterministicRandomVariable_Type; #define PyNs3DeterministicRandomVariable_Type (*_PyNs3DeterministicRandomVariable_Type) class PyNs3DeterministicRandomVariable__PythonHelper : public ns3::DeterministicRandomVariable { public: PyObject *m_pyself; void set_pyobj(PyObject *pyobj) { Py_XDECREF(m_pyself); Py_INCREF(pyobj); m_pyself = pyobj; } virtual ~PyNs3DeterministicRandomVariable__PythonHelper() { Py_CLEAR(m_pyself); } }; typedef struct { PyObject_HEAD ns3::DeviceEnergyModel *obj; PyObject *inst_dict; PyBindGenWrapperFlags flags:8; } PyNs3DeviceEnergyModel; extern PyTypeObject *_PyNs3DeviceEnergyModel_Type; #define PyNs3DeviceEnergyModel_Type (*_PyNs3DeviceEnergyModel_Type) class PyNs3DeviceEnergyModel__PythonHelper : public ns3::DeviceEnergyModel { public: PyObject *m_pyself; void set_pyobj(PyObject *pyobj) { Py_XDECREF(m_pyself); Py_INCREF(pyobj); m_pyself = pyobj; } virtual ~PyNs3DeviceEnergyModel__PythonHelper() { Py_CLEAR(m_pyself); } }; typedef struct { PyObject_HEAD ns3::DoubleValue *obj; PyBindGenWrapperFlags flags:8; } PyNs3DoubleValue; extern PyTypeObject *_PyNs3DoubleValue_Type; #define PyNs3DoubleValue_Type (*_PyNs3DoubleValue_Type) typedef struct { PyObject_HEAD ns3::EmpiricalRandomVariable *obj; PyObject *inst_dict; PyBindGenWrapperFlags flags:8; } PyNs3EmpiricalRandomVariable; extern PyTypeObject *_PyNs3EmpiricalRandomVariable_Type; #define PyNs3EmpiricalRandomVariable_Type (*_PyNs3EmpiricalRandomVariable_Type) class PyNs3EmpiricalRandomVariable__PythonHelper : public ns3::EmpiricalRandomVariable { public: PyObject *m_pyself; void set_pyobj(PyObject *pyobj) { Py_XDECREF(m_pyself); Py_INCREF(pyobj); m_pyself = pyobj; } virtual ~PyNs3EmpiricalRandomVariable__PythonHelper() { Py_CLEAR(m_pyself); } }; typedef struct { PyObject_HEAD ns3::EmptyAttributeValue *obj; PyBindGenWrapperFlags flags:8; } PyNs3EmptyAttributeValue; extern PyTypeObject *_PyNs3EmptyAttributeValue_Type; #define PyNs3EmptyAttributeValue_Type (*_PyNs3EmptyAttributeValue_Type) typedef struct { PyObject_HEAD ns3::EnergySource *obj; PyObject *inst_dict; PyBindGenWrapperFlags flags:8; } PyNs3EnergySource; extern PyTypeObject *_PyNs3EnergySource_Type; #define PyNs3EnergySource_Type (*_PyNs3EnergySource_Type) class PyNs3EnergySource__PythonHelper : public ns3::EnergySource { public: PyObject *m_pyself; void set_pyobj(PyObject *pyobj) { Py_XDECREF(m_pyself); Py_INCREF(pyobj); m_pyself = pyobj; } virtual ~PyNs3EnergySource__PythonHelper() { Py_CLEAR(m_pyself); } }; typedef struct { PyObject_HEAD ns3::EnergySourceContainer *obj; PyObject *inst_dict; PyBindGenWrapperFlags flags:8; } PyNs3EnergySourceContainer; extern PyTypeObject *_PyNs3EnergySourceContainer_Type; #define PyNs3EnergySourceContainer_Type (*_PyNs3EnergySourceContainer_Type) class PyNs3EnergySourceContainer__PythonHelper : public ns3::EnergySourceContainer { public: PyObject *m_pyself; void set_pyobj(PyObject *pyobj) { Py_XDECREF(m_pyself); Py_INCREF(pyobj); m_pyself = pyobj; } virtual ~PyNs3EnergySourceContainer__PythonHelper() { Py_CLEAR(m_pyself); } }; typedef struct { PyObject_HEAD ns3::EnumChecker *obj; PyBindGenWrapperFlags flags:8; } PyNs3EnumChecker; extern PyTypeObject *_PyNs3EnumChecker_Type; #define PyNs3EnumChecker_Type (*_PyNs3EnumChecker_Type) typedef struct { PyObject_HEAD ns3::EnumValue *obj; PyBindGenWrapperFlags flags:8; } PyNs3EnumValue; extern PyTypeObject *_PyNs3EnumValue_Type; #define PyNs3EnumValue_Type (*_PyNs3EnumValue_Type) typedef struct { PyObject_HEAD ns3::ErlangRandomVariable *obj; PyObject *inst_dict; PyBindGenWrapperFlags flags:8; } PyNs3ErlangRandomVariable; extern PyTypeObject *_PyNs3ErlangRandomVariable_Type; #define PyNs3ErlangRandomVariable_Type (*_PyNs3ErlangRandomVariable_Type) class PyNs3ErlangRandomVariable__PythonHelper : public ns3::ErlangRandomVariable { public: PyObject *m_pyself; void set_pyobj(PyObject *pyobj) { Py_XDECREF(m_pyself); Py_INCREF(pyobj); m_pyself = pyobj; } virtual ~PyNs3ErlangRandomVariable__PythonHelper() { Py_CLEAR(m_pyself); } }; typedef struct { PyObject_HEAD ns3::EventImpl *obj; PyBindGenWrapperFlags flags:8; } PyNs3EventImpl; extern PyTypeObject *_PyNs3EventImpl_Type; #define PyNs3EventImpl_Type (*_PyNs3EventImpl_Type) typedef struct { PyObject_HEAD ns3::ExponentialRandomVariable *obj; PyObject *inst_dict; PyBindGenWrapperFlags flags:8; } PyNs3ExponentialRandomVariable; extern PyTypeObject *_PyNs3ExponentialRandomVariable_Type; #define PyNs3ExponentialRandomVariable_Type (*_PyNs3ExponentialRandomVariable_Type) class PyNs3ExponentialRandomVariable__PythonHelper : public ns3::ExponentialRandomVariable { public: PyObject *m_pyself; void set_pyobj(PyObject *pyobj) { Py_XDECREF(m_pyself); Py_INCREF(pyobj); m_pyself = pyobj; } virtual ~PyNs3ExponentialRandomVariable__PythonHelper() { Py_CLEAR(m_pyself); } }; typedef struct { PyObject_HEAD ns3::GammaRandomVariable *obj; PyObject *inst_dict; PyBindGenWrapperFlags flags:8; } PyNs3GammaRandomVariable; extern PyTypeObject *_PyNs3GammaRandomVariable_Type; #define PyNs3GammaRandomVariable_Type (*_PyNs3GammaRandomVariable_Type) class PyNs3GammaRandomVariable__PythonHelper : public ns3::GammaRandomVariable { public: PyObject *m_pyself; void set_pyobj(PyObject *pyobj) { Py_XDECREF(m_pyself); Py_INCREF(pyobj); m_pyself = pyobj; } virtual ~PyNs3GammaRandomVariable__PythonHelper() { Py_CLEAR(m_pyself); } }; typedef struct { PyObject_HEAD ns3::IntegerValue *obj; PyBindGenWrapperFlags flags:8; } PyNs3IntegerValue; extern PyTypeObject *_PyNs3IntegerValue_Type; #define PyNs3IntegerValue_Type (*_PyNs3IntegerValue_Type) typedef struct { PyObject_HEAD ns3::Ipv4AddressChecker *obj; PyBindGenWrapperFlags flags:8; } PyNs3Ipv4AddressChecker; extern PyTypeObject *_PyNs3Ipv4AddressChecker_Type; #define PyNs3Ipv4AddressChecker_Type (*_PyNs3Ipv4AddressChecker_Type) typedef struct { PyObject_HEAD ns3::Ipv4AddressValue *obj; PyBindGenWrapperFlags flags:8; } PyNs3Ipv4AddressValue; extern PyTypeObject *_PyNs3Ipv4AddressValue_Type; #define PyNs3Ipv4AddressValue_Type (*_PyNs3Ipv4AddressValue_Type) typedef struct { PyObject_HEAD ns3::Ipv4MaskChecker *obj; PyBindGenWrapperFlags flags:8; } PyNs3Ipv4MaskChecker; extern PyTypeObject *_PyNs3Ipv4MaskChecker_Type; #define PyNs3Ipv4MaskChecker_Type (*_PyNs3Ipv4MaskChecker_Type) typedef struct { PyObject_HEAD ns3::Ipv4MaskValue *obj; PyBindGenWrapperFlags flags:8; } PyNs3Ipv4MaskValue; extern PyTypeObject *_PyNs3Ipv4MaskValue_Type; #define PyNs3Ipv4MaskValue_Type (*_PyNs3Ipv4MaskValue_Type) typedef struct { PyObject_HEAD ns3::Ipv6AddressChecker *obj; PyBindGenWrapperFlags flags:8; } PyNs3Ipv6AddressChecker; extern PyTypeObject *_PyNs3Ipv6AddressChecker_Type; #define PyNs3Ipv6AddressChecker_Type (*_PyNs3Ipv6AddressChecker_Type) typedef struct { PyObject_HEAD ns3::Ipv6AddressValue *obj; PyBindGenWrapperFlags flags:8; } PyNs3Ipv6AddressValue; extern PyTypeObject *_PyNs3Ipv6AddressValue_Type; #define PyNs3Ipv6AddressValue_Type (*_PyNs3Ipv6AddressValue_Type) typedef struct { PyObject_HEAD ns3::Ipv6PrefixChecker *obj; PyBindGenWrapperFlags flags:8; } PyNs3Ipv6PrefixChecker; extern PyTypeObject *_PyNs3Ipv6PrefixChecker_Type; #define PyNs3Ipv6PrefixChecker_Type (*_PyNs3Ipv6PrefixChecker_Type) typedef struct { PyObject_HEAD ns3::Ipv6PrefixValue *obj; PyBindGenWrapperFlags flags:8; } PyNs3Ipv6PrefixValue; extern PyTypeObject *_PyNs3Ipv6PrefixValue_Type; #define PyNs3Ipv6PrefixValue_Type (*_PyNs3Ipv6PrefixValue_Type) typedef struct { PyObject_HEAD ns3::LogNormalRandomVariable *obj; PyObject *inst_dict; PyBindGenWrapperFlags flags:8; } PyNs3LogNormalRandomVariable; extern PyTypeObject *_PyNs3LogNormalRandomVariable_Type; #define PyNs3LogNormalRandomVariable_Type (*_PyNs3LogNormalRandomVariable_Type) class PyNs3LogNormalRandomVariable__PythonHelper : public ns3::LogNormalRandomVariable { public: PyObject *m_pyself; void set_pyobj(PyObject *pyobj) { Py_XDECREF(m_pyself); Py_INCREF(pyobj); m_pyself = pyobj; } virtual ~PyNs3LogNormalRandomVariable__PythonHelper() { Py_CLEAR(m_pyself); } }; typedef struct { PyObject_HEAD ns3::MobilityModel *obj; PyObject *inst_dict; PyBindGenWrapperFlags flags:8; } PyNs3MobilityModel; extern PyTypeObject *_PyNs3MobilityModel_Type; #define PyNs3MobilityModel_Type (*_PyNs3MobilityModel_Type) class PyNs3MobilityModel__PythonHelper : public ns3::MobilityModel { public: PyObject *m_pyself; void set_pyobj(PyObject *pyobj) { Py_XDECREF(m_pyself); Py_INCREF(pyobj); m_pyself = pyobj; } virtual ~PyNs3MobilityModel__PythonHelper() { Py_CLEAR(m_pyself); } }; typedef struct { PyObject_HEAD ns3::NetDevice *obj; PyObject *inst_dict; PyBindGenWrapperFlags flags:8; } PyNs3NetDevice; extern PyTypeObject *_PyNs3NetDevice_Type; #define PyNs3NetDevice_Type (*_PyNs3NetDevice_Type) typedef struct { PyObject_HEAD ns3::NixVector *obj; PyBindGenWrapperFlags flags:8; } PyNs3NixVector; extern PyTypeObject *_PyNs3NixVector_Type; #define PyNs3NixVector_Type (*_PyNs3NixVector_Type) typedef struct { PyObject_HEAD ns3::Node *obj; PyObject *inst_dict; PyBindGenWrapperFlags flags:8; } PyNs3Node; extern PyTypeObject *_PyNs3Node_Type; #define PyNs3Node_Type (*_PyNs3Node_Type) class PyNs3Node__PythonHelper : public ns3::Node { public: PyObject *m_pyself; void set_pyobj(PyObject *pyobj) { Py_XDECREF(m_pyself); Py_INCREF(pyobj); m_pyself = pyobj; } virtual ~PyNs3Node__PythonHelper() { Py_CLEAR(m_pyself); } }; typedef struct { PyObject_HEAD ns3::NormalRandomVariable *obj; PyObject *inst_dict; PyBindGenWrapperFlags flags:8; } PyNs3NormalRandomVariable; extern PyTypeObject *_PyNs3NormalRandomVariable_Type; #define PyNs3NormalRandomVariable_Type (*_PyNs3NormalRandomVariable_Type) class PyNs3NormalRandomVariable__PythonHelper : public ns3::NormalRandomVariable { public: PyObject *m_pyself; void set_pyobj(PyObject *pyobj) { Py_XDECREF(m_pyself); Py_INCREF(pyobj); m_pyself = pyobj; } virtual ~PyNs3NormalRandomVariable__PythonHelper() { Py_CLEAR(m_pyself); } }; typedef struct { PyObject_HEAD ns3::ObjectFactoryChecker *obj; PyBindGenWrapperFlags flags:8; } PyNs3ObjectFactoryChecker; extern PyTypeObject *_PyNs3ObjectFactoryChecker_Type; #define PyNs3ObjectFactoryChecker_Type (*_PyNs3ObjectFactoryChecker_Type) typedef struct { PyObject_HEAD ns3::ObjectFactoryValue *obj; PyBindGenWrapperFlags flags:8; } PyNs3ObjectFactoryValue; extern PyTypeObject *_PyNs3ObjectFactoryValue_Type; #define PyNs3ObjectFactoryValue_Type (*_PyNs3ObjectFactoryValue_Type) typedef struct { PyObject_HEAD ns3::Packet *obj; PyBindGenWrapperFlags flags:8; } PyNs3Packet; extern PyTypeObject *_PyNs3Packet_Type; #define PyNs3Packet_Type (*_PyNs3Packet_Type) typedef struct { PyObject_HEAD ns3::ParetoRandomVariable *obj; PyObject *inst_dict; PyBindGenWrapperFlags flags:8; } PyNs3ParetoRandomVariable; extern PyTypeObject *_PyNs3ParetoRandomVariable_Type; #define PyNs3ParetoRandomVariable_Type (*_PyNs3ParetoRandomVariable_Type) class PyNs3ParetoRandomVariable__PythonHelper : public ns3::ParetoRandomVariable { public: PyObject *m_pyself; void set_pyobj(PyObject *pyobj) { Py_XDECREF(m_pyself); Py_INCREF(pyobj); m_pyself = pyobj; } virtual ~PyNs3ParetoRandomVariable__PythonHelper() { Py_CLEAR(m_pyself); } }; typedef struct { PyObject_HEAD ns3::PointerChecker *obj; PyBindGenWrapperFlags flags:8; } PyNs3PointerChecker; extern PyTypeObject *_PyNs3PointerChecker_Type; #define PyNs3PointerChecker_Type (*_PyNs3PointerChecker_Type) typedef struct { PyObject_HEAD ns3::PointerValue *obj; PyBindGenWrapperFlags flags:8; } PyNs3PointerValue; extern PyTypeObject *_PyNs3PointerValue_Type; #define PyNs3PointerValue_Type (*_PyNs3PointerValue_Type) typedef struct { PyObject_HEAD ns3::TimeChecker *obj; PyBindGenWrapperFlags flags:8; } PyNs3TimeChecker; extern PyTypeObject *_PyNs3TimeChecker_Type; #define PyNs3TimeChecker_Type (*_PyNs3TimeChecker_Type) typedef struct { PyObject_HEAD ns3::TimeValue *obj; PyBindGenWrapperFlags flags:8; } PyNs3TimeValue; extern PyTypeObject *_PyNs3TimeValue_Type; #define PyNs3TimeValue_Type (*_PyNs3TimeValue_Type) typedef struct { PyObject_HEAD ns3::TypeIdChecker *obj; PyBindGenWrapperFlags flags:8; } PyNs3TypeIdChecker; extern PyTypeObject *_PyNs3TypeIdChecker_Type; #define PyNs3TypeIdChecker_Type (*_PyNs3TypeIdChecker_Type) typedef struct { PyObject_HEAD ns3::TypeIdValue *obj; PyBindGenWrapperFlags flags:8; } PyNs3TypeIdValue; extern PyTypeObject *_PyNs3TypeIdValue_Type; #define PyNs3TypeIdValue_Type (*_PyNs3TypeIdValue_Type) typedef struct { PyObject_HEAD ns3::UintegerValue *obj; PyBindGenWrapperFlags flags:8; } PyNs3UintegerValue; extern PyTypeObject *_PyNs3UintegerValue_Type; #define PyNs3UintegerValue_Type (*_PyNs3UintegerValue_Type) typedef struct { PyObject_HEAD ns3::Vector2DChecker *obj; PyBindGenWrapperFlags flags:8; } PyNs3Vector2DChecker; extern PyTypeObject *_PyNs3Vector2DChecker_Type; #define PyNs3Vector2DChecker_Type (*_PyNs3Vector2DChecker_Type) typedef struct { PyObject_HEAD ns3::Vector2DValue *obj; PyBindGenWrapperFlags flags:8; } PyNs3Vector2DValue; extern PyTypeObject *_PyNs3Vector2DValue_Type; #define PyNs3Vector2DValue_Type (*_PyNs3Vector2DValue_Type) typedef struct { PyObject_HEAD ns3::Vector3DChecker *obj; PyBindGenWrapperFlags flags:8; } PyNs3Vector3DChecker; extern PyTypeObject *_PyNs3Vector3DChecker_Type; #define PyNs3Vector3DChecker_Type (*_PyNs3Vector3DChecker_Type) typedef struct { PyObject_HEAD ns3::Vector3DValue *obj; PyBindGenWrapperFlags flags:8; } PyNs3Vector3DValue; extern PyTypeObject *_PyNs3Vector3DValue_Type; #define PyNs3Vector3DValue_Type (*_PyNs3Vector3DValue_Type) typedef struct { PyObject_HEAD ns3::AddressChecker *obj; PyBindGenWrapperFlags flags:8; } PyNs3AddressChecker; extern PyTypeObject *_PyNs3AddressChecker_Type; #define PyNs3AddressChecker_Type (*_PyNs3AddressChecker_Type) typedef struct { PyObject_HEAD ns3::AddressValue *obj; PyBindGenWrapperFlags flags:8; } PyNs3AddressValue; extern PyTypeObject *_PyNs3AddressValue_Type; #define PyNs3AddressValue_Type (*_PyNs3AddressValue_Type) typedef struct { PyObject_HEAD ns3::Reservation *obj; PyBindGenWrapperFlags flags:8; } PyNs3Reservation; extern PyTypeObject PyNs3Reservation_Type; extern std::map<void*, PyObject*> PyNs3Reservation_wrapper_registry; typedef struct { PyObject_HEAD ns3::Tap *obj; PyBindGenWrapperFlags flags:8; } PyNs3Tap; extern PyTypeObject PyNs3Tap_Type; extern std::map<void*, PyObject*> PyNs3Tap_wrapper_registry; typedef struct { PyObject_HEAD ns3::UanAddress *obj; PyBindGenWrapperFlags flags:8; } PyNs3UanAddress; extern PyTypeObject PyNs3UanAddress_Type; extern std::map<void*, PyObject*> PyNs3UanAddress_wrapper_registry; typedef struct { PyObject_HEAD ns3::UanHelper *obj; PyBindGenWrapperFlags flags:8; } PyNs3UanHelper; extern PyTypeObject PyNs3UanHelper_Type; extern std::map<void*, PyObject*> PyNs3UanHelper_wrapper_registry; typedef struct { PyObject_HEAD ns3::UanModesList *obj; PyBindGenWrapperFlags flags:8; } PyNs3UanModesList; extern PyTypeObject PyNs3UanModesList_Type; extern std::map<void*, PyObject*> PyNs3UanModesList_wrapper_registry; typedef struct { PyObject_HEAD ns3::UanPacketArrival *obj; PyBindGenWrapperFlags flags:8; } PyNs3UanPacketArrival; extern PyTypeObject PyNs3UanPacketArrival_Type; extern std::map<void*, PyObject*> PyNs3UanPacketArrival_wrapper_registry; typedef struct { PyObject_HEAD ns3::UanPdp *obj; PyBindGenWrapperFlags flags:8; } PyNs3UanPdp; extern PyTypeObject PyNs3UanPdp_Type; extern std::map<void*, PyObject*> PyNs3UanPdp_wrapper_registry; typedef struct { PyObject_HEAD ns3::UanPhyListener *obj; PyObject *inst_dict; PyBindGenWrapperFlags flags:8; } PyNs3UanPhyListener; extern PyTypeObject PyNs3UanPhyListener_Type; class PyNs3UanPhyListener__PythonHelper : public ns3::UanPhyListener { public: PyObject *m_pyself; PyNs3UanPhyListener__PythonHelper() : ns3::UanPhyListener(), m_pyself(NULL) {} PyNs3UanPhyListener__PythonHelper(ns3::UanPhyListener const & arg0) : ns3::UanPhyListener(arg0), m_pyself(NULL) {} void set_pyobj(PyObject *pyobj) { Py_XDECREF(m_pyself); Py_INCREF(pyobj); m_pyself = pyobj; } virtual ~PyNs3UanPhyListener__PythonHelper() { Py_CLEAR(m_pyself); } virtual void NotifyCcaEnd(); virtual void NotifyCcaStart(); virtual void NotifyRxEndError(); virtual void NotifyRxEndOk(); virtual void NotifyRxStart(); virtual void NotifyTxStart(ns3::Time duration); }; extern std::map<void*, PyObject*> PyNs3UanPhyListener_wrapper_registry; typedef struct { PyObject_HEAD ns3::UanTxMode *obj; PyBindGenWrapperFlags flags:8; } PyNs3UanTxMode; extern PyTypeObject PyNs3UanTxMode_Type; extern std::map<void*, PyObject*> PyNs3UanTxMode_wrapper_registry; typedef struct { PyObject_HEAD ns3::UanTxModeFactory *obj; PyBindGenWrapperFlags flags:8; } PyNs3UanTxModeFactory; extern PyTypeObject PyNs3UanTxModeFactory_Type; extern std::map<void*, PyObject*> PyNs3UanTxModeFactory_wrapper_registry; typedef struct { PyObject_HEAD ns3::AcousticModemEnergyModelHelper *obj; PyObject *inst_dict; PyBindGenWrapperFlags flags:8; } PyNs3AcousticModemEnergyModelHelper; extern PyTypeObject PyNs3AcousticModemEnergyModelHelper_Type; class PyNs3AcousticModemEnergyModelHelper__PythonHelper : public ns3::AcousticModemEnergyModelHelper { public: PyObject *m_pyself; PyNs3AcousticModemEnergyModelHelper__PythonHelper(ns3::AcousticModemEnergyModelHelper const & arg0) : ns3::AcousticModemEnergyModelHelper(arg0), m_pyself(NULL) {} PyNs3AcousticModemEnergyModelHelper__PythonHelper() : ns3::AcousticModemEnergyModelHelper(), m_pyself(NULL) {} void set_pyobj(PyObject *pyobj) { Py_XDECREF(m_pyself); Py_INCREF(pyobj); m_pyself = pyobj; } virtual ~PyNs3AcousticModemEnergyModelHelper__PythonHelper() { Py_CLEAR(m_pyself); } virtual ns3::Ptr< ns3::DeviceEnergyModel > DoInstall(ns3::Ptr< ns3::NetDevice > device, ns3::Ptr< ns3::EnergySource > source) const; }; typedef struct { PyObject_HEAD ns3::UanHeaderCommon *obj; PyObject *inst_dict; PyBindGenWrapperFlags flags:8; } PyNs3UanHeaderCommon; extern PyTypeObject PyNs3UanHeaderCommon_Type; typedef struct { PyObject_HEAD ns3::UanHeaderRcAck *obj; PyObject *inst_dict; PyBindGenWrapperFlags flags:8; } PyNs3UanHeaderRcAck; extern PyTypeObject PyNs3UanHeaderRcAck_Type; typedef struct { PyObject_HEAD ns3::UanHeaderRcCts *obj; PyObject *inst_dict; PyBindGenWrapperFlags flags:8; } PyNs3UanHeaderRcCts; extern PyTypeObject PyNs3UanHeaderRcCts_Type; typedef struct { PyObject_HEAD ns3::UanHeaderRcCtsGlobal *obj; PyObject *inst_dict; PyBindGenWrapperFlags flags:8; } PyNs3UanHeaderRcCtsGlobal; extern PyTypeObject PyNs3UanHeaderRcCtsGlobal_Type; typedef struct { PyObject_HEAD ns3::UanHeaderRcData *obj; PyObject *inst_dict; PyBindGenWrapperFlags flags:8; } PyNs3UanHeaderRcData; extern PyTypeObject PyNs3UanHeaderRcData_Type; typedef struct { PyObject_HEAD ns3::UanHeaderRcRts *obj; PyObject *inst_dict; PyBindGenWrapperFlags flags:8; } PyNs3UanHeaderRcRts; extern PyTypeObject PyNs3UanHeaderRcRts_Type; typedef struct { PyObject_HEAD ns3::UanMac *obj; PyObject *inst_dict; PyBindGenWrapperFlags flags:8; } PyNs3UanMac; extern PyTypeObject PyNs3UanMac_Type; typedef struct { PyObject_HEAD ns3::UanMacAloha *obj; PyObject *inst_dict; PyBindGenWrapperFlags flags:8; } PyNs3UanMacAloha; extern PyTypeObject PyNs3UanMacAloha_Type; class PyNs3UanMacAloha__PythonHelper : public ns3::UanMacAloha { public: PyObject *m_pyself; PyNs3UanMacAloha__PythonHelper(ns3::UanMacAloha const & arg0) : ns3::UanMacAloha(arg0), m_pyself(NULL) {} PyNs3UanMacAloha__PythonHelper() : ns3::UanMacAloha(), m_pyself(NULL) {} void set_pyobj(PyObject *pyobj) { Py_XDECREF(m_pyself); Py_INCREF(pyobj); m_pyself = pyobj; } virtual ~PyNs3UanMacAloha__PythonHelper() { Py_CLEAR(m_pyself); } static PyObject * _wrap_NotifyConstructionCompleted(PyNs3UanMacAloha *self); inline void NotifyConstructionCompleted__parent_caller() { ns3::ObjectBase::NotifyConstructionCompleted(); } static PyObject * _wrap_NotifyNewAggregate(PyNs3UanMacAloha *self); inline void NotifyNewAggregate__parent_caller() { ns3::Object::NotifyNewAggregate(); } static PyObject * _wrap_DoStart(PyNs3UanMacAloha *self); inline void DoStart__parent_caller() { ns3::Object::DoStart(); } static PyObject * _wrap_DoDispose(PyNs3UanMacAloha *self); inline void DoDispose__parent_caller() { ns3::UanMacAloha::DoDispose(); } virtual int64_t AssignStreams(int64_t stream); virtual void AttachPhy(ns3::Ptr< ns3::UanPhy > phy); virtual void Clear(); virtual bool Enqueue(ns3::Ptr< ns3::Packet > pkt, ns3::Address const & dest, uint16_t protocolNumber); virtual ns3::Address GetAddress(); virtual ns3::Address GetBroadcast() const; virtual void SetAddress(ns3::UanAddress addr); virtual void DoDispose(); virtual ns3::TypeId GetInstanceTypeId() const; virtual void DoStart(); virtual void NotifyNewAggregate(); virtual void NotifyConstructionCompleted(); static ns3::TypeId GetTypeId (void) { static ns3::TypeId tid = ns3::TypeId ("PyNs3UanMacAloha__PythonHelper") .SetParent< ns3::UanMacAloha > () ; return tid; } }; NS_OBJECT_ENSURE_REGISTERED (PyNs3UanMacAloha__PythonHelper); typedef struct { PyObject_HEAD ns3::UanMacCw *obj; PyObject *inst_dict; PyBindGenWrapperFlags flags:8; } PyNs3UanMacCw; extern PyTypeObject PyNs3UanMacCw_Type; class PyNs3UanMacCw__PythonHelper : public ns3::UanMacCw { public: PyObject *m_pyself; PyNs3UanMacCw__PythonHelper(ns3::UanMacCw const & arg0) : ns3::UanMacCw(arg0), m_pyself(NULL) {} PyNs3UanMacCw__PythonHelper() : ns3::UanMacCw(), m_pyself(NULL) {} void set_pyobj(PyObject *pyobj) { Py_XDECREF(m_pyself); Py_INCREF(pyobj); m_pyself = pyobj; } virtual ~PyNs3UanMacCw__PythonHelper() { Py_CLEAR(m_pyself); } static PyObject * _wrap_NotifyConstructionCompleted(PyNs3UanMacCw *self); inline void NotifyConstructionCompleted__parent_caller() { ns3::ObjectBase::NotifyConstructionCompleted(); } static PyObject * _wrap_NotifyNewAggregate(PyNs3UanMacCw *self); inline void NotifyNewAggregate__parent_caller() { ns3::Object::NotifyNewAggregate(); } static PyObject * _wrap_DoStart(PyNs3UanMacCw *self); inline void DoStart__parent_caller() { ns3::Object::DoStart(); } static PyObject * _wrap_DoDispose(PyNs3UanMacCw *self); inline void DoDispose__parent_caller() { ns3::UanMacCw::DoDispose(); } virtual int64_t AssignStreams(int64_t stream); virtual void AttachPhy(ns3::Ptr< ns3::UanPhy > phy); virtual void Clear(); virtual bool Enqueue(ns3::Ptr< ns3::Packet > pkt, ns3::Address const & dest, uint16_t protocolNumber); virtual ns3::Address GetAddress(); virtual ns3::Address GetBroadcast() const; virtual uint32_t GetCw(); virtual ns3::Time GetSlotTime(); virtual void NotifyCcaEnd(); virtual void NotifyCcaStart(); virtual void NotifyRxEndError(); virtual void NotifyRxEndOk(); virtual void NotifyRxStart(); virtual void NotifyTxStart(ns3::Time duration); virtual void SetAddress(ns3::UanAddress addr); virtual void SetCw(uint32_t cw); virtual void SetSlotTime(ns3::Time duration); virtual void DoDispose(); virtual ns3::TypeId GetInstanceTypeId() const; virtual void DoStart(); virtual void NotifyNewAggregate(); virtual void NotifyConstructionCompleted(); static ns3::TypeId GetTypeId (void) { static ns3::TypeId tid = ns3::TypeId ("PyNs3UanMacCw__PythonHelper") .SetParent< ns3::UanMacCw > () ; return tid; } }; NS_OBJECT_ENSURE_REGISTERED (PyNs3UanMacCw__PythonHelper); typedef struct { PyObject_HEAD ns3::UanMacRc *obj; PyObject *inst_dict; PyBindGenWrapperFlags flags:8; } PyNs3UanMacRc; extern PyTypeObject PyNs3UanMacRc_Type; class PyNs3UanMacRc__PythonHelper : public ns3::UanMacRc { public: PyObject *m_pyself; PyNs3UanMacRc__PythonHelper(ns3::UanMacRc const & arg0) : ns3::UanMacRc(arg0), m_pyself(NULL) {} PyNs3UanMacRc__PythonHelper() : ns3::UanMacRc(), m_pyself(NULL) {} void set_pyobj(PyObject *pyobj) { Py_XDECREF(m_pyself); Py_INCREF(pyobj); m_pyself = pyobj; } virtual ~PyNs3UanMacRc__PythonHelper() { Py_CLEAR(m_pyself); } static PyObject * _wrap_NotifyConstructionCompleted(PyNs3UanMacRc *self); inline void NotifyConstructionCompleted__parent_caller() { ns3::ObjectBase::NotifyConstructionCompleted(); } static PyObject * _wrap_NotifyNewAggregate(PyNs3UanMacRc *self); inline void NotifyNewAggregate__parent_caller() { ns3::Object::NotifyNewAggregate(); } static PyObject * _wrap_DoStart(PyNs3UanMacRc *self); inline void DoStart__parent_caller() { ns3::Object::DoStart(); } static PyObject * _wrap_DoDispose(PyNs3UanMacRc *self); inline void DoDispose__parent_caller() { ns3::UanMacRc::DoDispose(); } virtual int64_t AssignStreams(int64_t stream); virtual void AttachPhy(ns3::Ptr< ns3::UanPhy > phy); virtual void Clear(); virtual bool Enqueue(ns3::Ptr< ns3::Packet > pkt, ns3::Address const & dest, uint16_t protocolNumber); virtual ns3::Address GetAddress(); virtual ns3::Address GetBroadcast() const; virtual void SetAddress(ns3::UanAddress addr); virtual void DoDispose(); virtual ns3::TypeId GetInstanceTypeId() const; virtual void DoStart(); virtual void NotifyNewAggregate(); virtual void NotifyConstructionCompleted(); static ns3::TypeId GetTypeId (void) { static ns3::TypeId tid = ns3::TypeId ("PyNs3UanMacRc__PythonHelper") .SetParent< ns3::UanMacRc > () ; return tid; } }; NS_OBJECT_ENSURE_REGISTERED (PyNs3UanMacRc__PythonHelper); typedef struct { PyObject_HEAD ns3::UanMacRcGw *obj; PyObject *inst_dict; PyBindGenWrapperFlags flags:8; } PyNs3UanMacRcGw; extern PyTypeObject PyNs3UanMacRcGw_Type; class PyNs3UanMacRcGw__PythonHelper : public ns3::UanMacRcGw { public: PyObject *m_pyself; PyNs3UanMacRcGw__PythonHelper(ns3::UanMacRcGw const & arg0) : ns3::UanMacRcGw(arg0), m_pyself(NULL) {} PyNs3UanMacRcGw__PythonHelper() : ns3::UanMacRcGw(), m_pyself(NULL) {} void set_pyobj(PyObject *pyobj) { Py_XDECREF(m_pyself); Py_INCREF(pyobj); m_pyself = pyobj; } virtual ~PyNs3UanMacRcGw__PythonHelper() { Py_CLEAR(m_pyself); } static PyObject * _wrap_NotifyConstructionCompleted(PyNs3UanMacRcGw *self); inline void NotifyConstructionCompleted__parent_caller() { ns3::ObjectBase::NotifyConstructionCompleted(); } static PyObject * _wrap_NotifyNewAggregate(PyNs3UanMacRcGw *self); inline void NotifyNewAggregate__parent_caller() { ns3::Object::NotifyNewAggregate(); } static PyObject * _wrap_DoStart(PyNs3UanMacRcGw *self); inline void DoStart__parent_caller() { ns3::Object::DoStart(); } static PyObject * _wrap_DoDispose(PyNs3UanMacRcGw *self); inline void DoDispose__parent_caller() { ns3::UanMacRcGw::DoDispose(); } virtual int64_t AssignStreams(int64_t stream); virtual void AttachPhy(ns3::Ptr< ns3::UanPhy > phy); virtual void Clear(); virtual bool Enqueue(ns3::Ptr< ns3::Packet > pkt, ns3::Address const & dest, uint16_t protocolNumber); virtual ns3::Address GetAddress(); virtual ns3::Address GetBroadcast() const; virtual void SetAddress(ns3::UanAddress addr); virtual void DoDispose(); virtual ns3::TypeId GetInstanceTypeId() const; virtual void DoStart(); virtual void NotifyNewAggregate(); virtual void NotifyConstructionCompleted(); static ns3::TypeId GetTypeId (void) { static ns3::TypeId tid = ns3::TypeId ("PyNs3UanMacRcGw__PythonHelper") .SetParent< ns3::UanMacRcGw > () ; return tid; } }; NS_OBJECT_ENSURE_REGISTERED (PyNs3UanMacRcGw__PythonHelper); typedef struct { PyObject_HEAD ns3::UanNoiseModel *obj; PyObject *inst_dict; PyBindGenWrapperFlags flags:8; } PyNs3UanNoiseModel; extern PyTypeObject PyNs3UanNoiseModel_Type; class PyNs3UanNoiseModel__PythonHelper : public ns3::UanNoiseModel { public: PyObject *m_pyself; PyNs3UanNoiseModel__PythonHelper() : ns3::UanNoiseModel(), m_pyself(NULL) {} PyNs3UanNoiseModel__PythonHelper(ns3::UanNoiseModel const & arg0) : ns3::UanNoiseModel(arg0), m_pyself(NULL) {} void set_pyobj(PyObject *pyobj) { Py_XDECREF(m_pyself); Py_INCREF(pyobj); m_pyself = pyobj; } virtual ~PyNs3UanNoiseModel__PythonHelper() { Py_CLEAR(m_pyself); } static PyObject * _wrap_NotifyConstructionCompleted(PyNs3UanNoiseModel *self); inline void NotifyConstructionCompleted__parent_caller() { ns3::ObjectBase::NotifyConstructionCompleted(); } static PyObject * _wrap_NotifyNewAggregate(PyNs3UanNoiseModel *self); inline void NotifyNewAggregate__parent_caller() { ns3::Object::NotifyNewAggregate(); } static PyObject * _wrap_DoStart(PyNs3UanNoiseModel *self); inline void DoStart__parent_caller() { ns3::Object::DoStart(); } virtual void Clear(); virtual void DoDispose(); virtual double GetNoiseDbHz(double fKhz) const; virtual ns3::TypeId GetInstanceTypeId() const; virtual void DoStart(); virtual void NotifyNewAggregate(); virtual void NotifyConstructionCompleted(); static ns3::TypeId GetTypeId (void) { static ns3::TypeId tid = ns3::TypeId ("PyNs3UanNoiseModel__PythonHelper") .SetParent< ns3::UanNoiseModel > () ; return tid; } }; NS_OBJECT_ENSURE_REGISTERED (PyNs3UanNoiseModel__PythonHelper); typedef struct { PyObject_HEAD ns3::UanNoiseModelDefault *obj; PyObject *inst_dict; PyBindGenWrapperFlags flags:8; } PyNs3UanNoiseModelDefault; extern PyTypeObject PyNs3UanNoiseModelDefault_Type; class PyNs3UanNoiseModelDefault__PythonHelper : public ns3::UanNoiseModelDefault { public: PyObject *m_pyself; PyNs3UanNoiseModelDefault__PythonHelper(ns3::UanNoiseModelDefault const & arg0) : ns3::UanNoiseModelDefault(arg0), m_pyself(NULL) {} PyNs3UanNoiseModelDefault__PythonHelper() : ns3::UanNoiseModelDefault(), m_pyself(NULL) {} void set_pyobj(PyObject *pyobj) { Py_XDECREF(m_pyself); Py_INCREF(pyobj); m_pyself = pyobj; } virtual ~PyNs3UanNoiseModelDefault__PythonHelper() { Py_CLEAR(m_pyself); } static PyObject * _wrap_NotifyConstructionCompleted(PyNs3UanNoiseModelDefault *self); inline void NotifyConstructionCompleted__parent_caller() { ns3::ObjectBase::NotifyConstructionCompleted(); } static PyObject * _wrap_NotifyNewAggregate(PyNs3UanNoiseModelDefault *self); inline void NotifyNewAggregate__parent_caller() { ns3::Object::NotifyNewAggregate(); } static PyObject * _wrap_DoStart(PyNs3UanNoiseModelDefault *self); inline void DoStart__parent_caller() { ns3::Object::DoStart(); } virtual double GetNoiseDbHz(double fKhz) const; virtual void Clear(); virtual void DoDispose(); virtual ns3::TypeId GetInstanceTypeId() const; virtual void DoStart(); virtual void NotifyNewAggregate(); virtual void NotifyConstructionCompleted(); static ns3::TypeId GetTypeId (void) { static ns3::TypeId tid = ns3::TypeId ("PyNs3UanNoiseModelDefault__PythonHelper") .SetParent< ns3::UanNoiseModelDefault > () ; return tid; } }; NS_OBJECT_ENSURE_REGISTERED (PyNs3UanNoiseModelDefault__PythonHelper); typedef struct { PyObject_HEAD ns3::UanPhy *obj; PyObject *inst_dict; PyBindGenWrapperFlags flags:8; } PyNs3UanPhy; extern PyTypeObject PyNs3UanPhy_Type; typedef struct { PyObject_HEAD ns3::UanPhyCalcSinr *obj; PyObject *inst_dict; PyBindGenWrapperFlags flags:8; } PyNs3UanPhyCalcSinr; extern PyTypeObject PyNs3UanPhyCalcSinr_Type; class PyNs3UanPhyCalcSinr__PythonHelper : public ns3::UanPhyCalcSinr { public: PyObject *m_pyself; PyNs3UanPhyCalcSinr__PythonHelper() : ns3::UanPhyCalcSinr(), m_pyself(NULL) {} PyNs3UanPhyCalcSinr__PythonHelper(ns3::UanPhyCalcSinr const & arg0) : ns3::UanPhyCalcSinr(arg0), m_pyself(NULL) {} void set_pyobj(PyObject *pyobj) { Py_XDECREF(m_pyself); Py_INCREF(pyobj); m_pyself = pyobj; } virtual ~PyNs3UanPhyCalcSinr__PythonHelper() { Py_CLEAR(m_pyself); } static PyObject * _wrap_NotifyConstructionCompleted(PyNs3UanPhyCalcSinr *self); inline void NotifyConstructionCompleted__parent_caller() { ns3::ObjectBase::NotifyConstructionCompleted(); } static PyObject * _wrap_NotifyNewAggregate(PyNs3UanPhyCalcSinr *self); inline void NotifyNewAggregate__parent_caller() { ns3::Object::NotifyNewAggregate(); } static PyObject * _wrap_DoStart(PyNs3UanPhyCalcSinr *self); inline void DoStart__parent_caller() { ns3::Object::DoStart(); } virtual double CalcSinrDb(ns3::Ptr< ns3::Packet > pkt, ns3::Time arrTime, double rxPowerDb, double ambNoiseDb, ns3::UanTxMode mode, ns3::UanPdp pdp, std::list< ns3::UanPacketArrival > const & arrivalList) const; virtual void Clear(); virtual void DoDispose(); virtual ns3::TypeId GetInstanceTypeId() const; virtual void DoStart(); virtual void NotifyNewAggregate(); virtual void NotifyConstructionCompleted(); static ns3::TypeId GetTypeId (void) { static ns3::TypeId tid = ns3::TypeId ("PyNs3UanPhyCalcSinr__PythonHelper") .SetParent< ns3::UanPhyCalcSinr > () ; return tid; } }; NS_OBJECT_ENSURE_REGISTERED (PyNs3UanPhyCalcSinr__PythonHelper); typedef struct { PyObject_HEAD ns3::UanPhyCalcSinrDefault *obj; PyObject *inst_dict; PyBindGenWrapperFlags flags:8; } PyNs3UanPhyCalcSinrDefault; extern PyTypeObject PyNs3UanPhyCalcSinrDefault_Type; class PyNs3UanPhyCalcSinrDefault__PythonHelper : public ns3::UanPhyCalcSinrDefault { public: PyObject *m_pyself; PyNs3UanPhyCalcSinrDefault__PythonHelper(ns3::UanPhyCalcSinrDefault const & arg0) : ns3::UanPhyCalcSinrDefault(arg0), m_pyself(NULL) {} PyNs3UanPhyCalcSinrDefault__PythonHelper() : ns3::UanPhyCalcSinrDefault(), m_pyself(NULL) {} void set_pyobj(PyObject *pyobj) { Py_XDECREF(m_pyself); Py_INCREF(pyobj); m_pyself = pyobj; } virtual ~PyNs3UanPhyCalcSinrDefault__PythonHelper() { Py_CLEAR(m_pyself); } static PyObject * _wrap_NotifyConstructionCompleted(PyNs3UanPhyCalcSinrDefault *self); inline void NotifyConstructionCompleted__parent_caller() { ns3::ObjectBase::NotifyConstructionCompleted(); } static PyObject * _wrap_NotifyNewAggregate(PyNs3UanPhyCalcSinrDefault *self); inline void NotifyNewAggregate__parent_caller() { ns3::Object::NotifyNewAggregate(); } static PyObject * _wrap_DoStart(PyNs3UanPhyCalcSinrDefault *self); inline void DoStart__parent_caller() { ns3::Object::DoStart(); } virtual double CalcSinrDb(ns3::Ptr< ns3::Packet > pkt, ns3::Time arrTime, double rxPowerDb, double ambNoiseDb, ns3::UanTxMode mode, ns3::UanPdp pdp, std::list< ns3::UanPacketArrival > const & arrivalList) const; virtual void DoDispose(); virtual void Clear(); virtual ns3::TypeId GetInstanceTypeId() const; virtual void DoStart(); virtual void NotifyNewAggregate(); virtual void NotifyConstructionCompleted(); static ns3::TypeId GetTypeId (void) { static ns3::TypeId tid = ns3::TypeId ("PyNs3UanPhyCalcSinrDefault__PythonHelper") .SetParent< ns3::UanPhyCalcSinrDefault > () ; return tid; } }; NS_OBJECT_ENSURE_REGISTERED (PyNs3UanPhyCalcSinrDefault__PythonHelper); typedef struct { PyObject_HEAD ns3::UanPhyCalcSinrDual *obj; PyObject *inst_dict; PyBindGenWrapperFlags flags:8; } PyNs3UanPhyCalcSinrDual; extern PyTypeObject PyNs3UanPhyCalcSinrDual_Type; class PyNs3UanPhyCalcSinrDual__PythonHelper : public ns3::UanPhyCalcSinrDual { public: PyObject *m_pyself; PyNs3UanPhyCalcSinrDual__PythonHelper(ns3::UanPhyCalcSinrDual const & arg0) : ns3::UanPhyCalcSinrDual(arg0), m_pyself(NULL) {} PyNs3UanPhyCalcSinrDual__PythonHelper() : ns3::UanPhyCalcSinrDual(), m_pyself(NULL) {} void set_pyobj(PyObject *pyobj) { Py_XDECREF(m_pyself); Py_INCREF(pyobj); m_pyself = pyobj; } virtual ~PyNs3UanPhyCalcSinrDual__PythonHelper() { Py_CLEAR(m_pyself); } static PyObject * _wrap_NotifyConstructionCompleted(PyNs3UanPhyCalcSinrDual *self); inline void NotifyConstructionCompleted__parent_caller() { ns3::ObjectBase::NotifyConstructionCompleted(); } static PyObject * _wrap_NotifyNewAggregate(PyNs3UanPhyCalcSinrDual *self); inline void NotifyNewAggregate__parent_caller() { ns3::Object::NotifyNewAggregate(); } static PyObject * _wrap_DoStart(PyNs3UanPhyCalcSinrDual *self); inline void DoStart__parent_caller() { ns3::Object::DoStart(); } virtual double CalcSinrDb(ns3::Ptr< ns3::Packet > pkt, ns3::Time arrTime, double rxPowerDb, double ambNoiseDb, ns3::UanTxMode mode, ns3::UanPdp pdp, std::list< ns3::UanPacketArrival > const & arrivalList) const; virtual void DoDispose(); virtual void Clear(); virtual ns3::TypeId GetInstanceTypeId() const; virtual void DoStart(); virtual void NotifyNewAggregate(); virtual void NotifyConstructionCompleted(); static ns3::TypeId GetTypeId (void) { static ns3::TypeId tid = ns3::TypeId ("PyNs3UanPhyCalcSinrDual__PythonHelper") .SetParent< ns3::UanPhyCalcSinrDual > () ; return tid; } }; NS_OBJECT_ENSURE_REGISTERED (PyNs3UanPhyCalcSinrDual__PythonHelper); typedef struct { PyObject_HEAD ns3::UanPhyCalcSinrFhFsk *obj; PyObject *inst_dict; PyBindGenWrapperFlags flags:8; } PyNs3UanPhyCalcSinrFhFsk; extern PyTypeObject PyNs3UanPhyCalcSinrFhFsk_Type; class PyNs3UanPhyCalcSinrFhFsk__PythonHelper : public ns3::UanPhyCalcSinrFhFsk { public: PyObject *m_pyself; PyNs3UanPhyCalcSinrFhFsk__PythonHelper(ns3::UanPhyCalcSinrFhFsk const & arg0) : ns3::UanPhyCalcSinrFhFsk(arg0), m_pyself(NULL) {} PyNs3UanPhyCalcSinrFhFsk__PythonHelper() : ns3::UanPhyCalcSinrFhFsk(), m_pyself(NULL) {} void set_pyobj(PyObject *pyobj) { Py_XDECREF(m_pyself); Py_INCREF(pyobj); m_pyself = pyobj; } virtual ~PyNs3UanPhyCalcSinrFhFsk__PythonHelper() { Py_CLEAR(m_pyself); } static PyObject * _wrap_NotifyConstructionCompleted(PyNs3UanPhyCalcSinrFhFsk *self); inline void NotifyConstructionCompleted__parent_caller() { ns3::ObjectBase::NotifyConstructionCompleted(); } static PyObject * _wrap_NotifyNewAggregate(PyNs3UanPhyCalcSinrFhFsk *self); inline void NotifyNewAggregate__parent_caller() { ns3::Object::NotifyNewAggregate(); } static PyObject * _wrap_DoStart(PyNs3UanPhyCalcSinrFhFsk *self); inline void DoStart__parent_caller() { ns3::Object::DoStart(); } virtual double CalcSinrDb(ns3::Ptr< ns3::Packet > pkt, ns3::Time arrTime, double rxPowerDb, double ambNoiseDb, ns3::UanTxMode mode, ns3::UanPdp pdp, std::list< ns3::UanPacketArrival > const & arrivalList) const; virtual void DoDispose(); virtual void Clear(); virtual ns3::TypeId GetInstanceTypeId() const; virtual void DoStart(); virtual void NotifyNewAggregate(); virtual void NotifyConstructionCompleted(); static ns3::TypeId GetTypeId (void) { static ns3::TypeId tid = ns3::TypeId ("PyNs3UanPhyCalcSinrFhFsk__PythonHelper") .SetParent< ns3::UanPhyCalcSinrFhFsk > () ; return tid; } }; NS_OBJECT_ENSURE_REGISTERED (PyNs3UanPhyCalcSinrFhFsk__PythonHelper); typedef struct { PyObject_HEAD ns3::UanPhyDual *obj; PyObject *inst_dict; PyBindGenWrapperFlags flags:8; } PyNs3UanPhyDual; extern PyTypeObject PyNs3UanPhyDual_Type; typedef struct { PyObject_HEAD ns3::UanPhyGen *obj; PyObject *inst_dict; PyBindGenWrapperFlags flags:8; } PyNs3UanPhyGen; extern PyTypeObject PyNs3UanPhyGen_Type; typedef struct { PyObject_HEAD ns3::UanPhyPer *obj; PyObject *inst_dict; PyBindGenWrapperFlags flags:8; } PyNs3UanPhyPer; extern PyTypeObject PyNs3UanPhyPer_Type; class PyNs3UanPhyPer__PythonHelper : public ns3::UanPhyPer { public: PyObject *m_pyself; PyNs3UanPhyPer__PythonHelper() : ns3::UanPhyPer(), m_pyself(NULL) {} PyNs3UanPhyPer__PythonHelper(ns3::UanPhyPer const & arg0) : ns3::UanPhyPer(arg0), m_pyself(NULL) {} void set_pyobj(PyObject *pyobj) { Py_XDECREF(m_pyself); Py_INCREF(pyobj); m_pyself = pyobj; } virtual ~PyNs3UanPhyPer__PythonHelper() { Py_CLEAR(m_pyself); } static PyObject * _wrap_NotifyConstructionCompleted(PyNs3UanPhyPer *self); inline void NotifyConstructionCompleted__parent_caller() { ns3::ObjectBase::NotifyConstructionCompleted(); } static PyObject * _wrap_NotifyNewAggregate(PyNs3UanPhyPer *self); inline void NotifyNewAggregate__parent_caller() { ns3::Object::NotifyNewAggregate(); } static PyObject * _wrap_DoStart(PyNs3UanPhyPer *self); inline void DoStart__parent_caller() { ns3::Object::DoStart(); } virtual double CalcPer(ns3::Ptr< ns3::Packet > pkt, double sinrDb, ns3::UanTxMode mode); virtual void Clear(); virtual void DoDispose(); virtual ns3::TypeId GetInstanceTypeId() const; virtual void DoStart(); virtual void NotifyNewAggregate(); virtual void NotifyConstructionCompleted(); static ns3::TypeId GetTypeId (void) { static ns3::TypeId tid = ns3::TypeId ("PyNs3UanPhyPer__PythonHelper") .SetParent< ns3::UanPhyPer > () ; return tid; } }; NS_OBJECT_ENSURE_REGISTERED (PyNs3UanPhyPer__PythonHelper); typedef struct { PyObject_HEAD ns3::UanPhyPerGenDefault *obj; PyObject *inst_dict; PyBindGenWrapperFlags flags:8; } PyNs3UanPhyPerGenDefault; extern PyTypeObject PyNs3UanPhyPerGenDefault_Type; class PyNs3UanPhyPerGenDefault__PythonHelper : public ns3::UanPhyPerGenDefault { public: PyObject *m_pyself; PyNs3UanPhyPerGenDefault__PythonHelper(ns3::UanPhyPerGenDefault const & arg0) : ns3::UanPhyPerGenDefault(arg0), m_pyself(NULL) {} PyNs3UanPhyPerGenDefault__PythonHelper() : ns3::UanPhyPerGenDefault(), m_pyself(NULL) {} void set_pyobj(PyObject *pyobj) { Py_XDECREF(m_pyself); Py_INCREF(pyobj); m_pyself = pyobj; } virtual ~PyNs3UanPhyPerGenDefault__PythonHelper() { Py_CLEAR(m_pyself); } static PyObject * _wrap_NotifyConstructionCompleted(PyNs3UanPhyPerGenDefault *self); inline void NotifyConstructionCompleted__parent_caller() { ns3::ObjectBase::NotifyConstructionCompleted(); } static PyObject * _wrap_NotifyNewAggregate(PyNs3UanPhyPerGenDefault *self); inline void NotifyNewAggregate__parent_caller() { ns3::Object::NotifyNewAggregate(); } static PyObject * _wrap_DoStart(PyNs3UanPhyPerGenDefault *self); inline void DoStart__parent_caller() { ns3::Object::DoStart(); } virtual double CalcPer(ns3::Ptr< ns3::Packet > pkt, double sinrDb, ns3::UanTxMode mode); virtual void Clear(); virtual void DoDispose(); virtual ns3::TypeId GetInstanceTypeId() const; virtual void DoStart(); virtual void NotifyNewAggregate(); virtual void NotifyConstructionCompleted(); static ns3::TypeId GetTypeId (void) { static ns3::TypeId tid = ns3::TypeId ("PyNs3UanPhyPerGenDefault__PythonHelper") .SetParent< ns3::UanPhyPerGenDefault > () ; return tid; } }; NS_OBJECT_ENSURE_REGISTERED (PyNs3UanPhyPerGenDefault__PythonHelper); typedef struct { PyObject_HEAD ns3::UanPhyPerUmodem *obj; PyObject *inst_dict; PyBindGenWrapperFlags flags:8; } PyNs3UanPhyPerUmodem; extern PyTypeObject PyNs3UanPhyPerUmodem_Type; class PyNs3UanPhyPerUmodem__PythonHelper : public ns3::UanPhyPerUmodem { public: PyObject *m_pyself; PyNs3UanPhyPerUmodem__PythonHelper(ns3::UanPhyPerUmodem const & arg0) : ns3::UanPhyPerUmodem(arg0), m_pyself(NULL) {} PyNs3UanPhyPerUmodem__PythonHelper() : ns3::UanPhyPerUmodem(), m_pyself(NULL) {} void set_pyobj(PyObject *pyobj) { Py_XDECREF(m_pyself); Py_INCREF(pyobj); m_pyself = pyobj; } virtual ~PyNs3UanPhyPerUmodem__PythonHelper() { Py_CLEAR(m_pyself); } static PyObject * _wrap_NotifyConstructionCompleted(PyNs3UanPhyPerUmodem *self); inline void NotifyConstructionCompleted__parent_caller() { ns3::ObjectBase::NotifyConstructionCompleted(); } static PyObject * _wrap_NotifyNewAggregate(PyNs3UanPhyPerUmodem *self); inline void NotifyNewAggregate__parent_caller() { ns3::Object::NotifyNewAggregate(); } static PyObject * _wrap_DoStart(PyNs3UanPhyPerUmodem *self); inline void DoStart__parent_caller() { ns3::Object::DoStart(); } virtual double CalcPer(ns3::Ptr< ns3::Packet > pkt, double sinrDb, ns3::UanTxMode mode); virtual void Clear(); virtual void DoDispose(); virtual ns3::TypeId GetInstanceTypeId() const; virtual void DoStart(); virtual void NotifyNewAggregate(); virtual void NotifyConstructionCompleted(); static ns3::TypeId GetTypeId (void) { static ns3::TypeId tid = ns3::TypeId ("PyNs3UanPhyPerUmodem__PythonHelper") .SetParent< ns3::UanPhyPerUmodem > () ; return tid; } }; NS_OBJECT_ENSURE_REGISTERED (PyNs3UanPhyPerUmodem__PythonHelper); typedef struct { PyObject_HEAD ns3::UanPropModel *obj; PyObject *inst_dict; PyBindGenWrapperFlags flags:8; } PyNs3UanPropModel; extern PyTypeObject PyNs3UanPropModel_Type; class PyNs3UanPropModel__PythonHelper : public ns3::UanPropModel { public: PyObject *m_pyself; PyNs3UanPropModel__PythonHelper() : ns3::UanPropModel(), m_pyself(NULL) {} PyNs3UanPropModel__PythonHelper(ns3::UanPropModel const & arg0) : ns3::UanPropModel(arg0), m_pyself(NULL) {} void set_pyobj(PyObject *pyobj) { Py_XDECREF(m_pyself); Py_INCREF(pyobj); m_pyself = pyobj; } virtual ~PyNs3UanPropModel__PythonHelper() { Py_CLEAR(m_pyself); } static PyObject * _wrap_NotifyConstructionCompleted(PyNs3UanPropModel *self); inline void NotifyConstructionCompleted__parent_caller() { ns3::ObjectBase::NotifyConstructionCompleted(); } static PyObject * _wrap_NotifyNewAggregate(PyNs3UanPropModel *self); inline void NotifyNewAggregate__parent_caller() { ns3::Object::NotifyNewAggregate(); } static PyObject * _wrap_DoStart(PyNs3UanPropModel *self); inline void DoStart__parent_caller() { ns3::Object::DoStart(); } virtual void Clear(); virtual void DoDispose(); virtual ns3::Time GetDelay(ns3::Ptr< ns3::MobilityModel > a, ns3::Ptr< ns3::MobilityModel > b, ns3::UanTxMode mode); virtual double GetPathLossDb(ns3::Ptr< ns3::MobilityModel > a, ns3::Ptr< ns3::MobilityModel > b, ns3::UanTxMode txMode); virtual ns3::UanPdp GetPdp(ns3::Ptr< ns3::MobilityModel > a, ns3::Ptr< ns3::MobilityModel > b, ns3::UanTxMode mode); virtual ns3::TypeId GetInstanceTypeId() const; virtual void DoStart(); virtual void NotifyNewAggregate(); virtual void NotifyConstructionCompleted(); static ns3::TypeId GetTypeId (void) { static ns3::TypeId tid = ns3::TypeId ("PyNs3UanPropModel__PythonHelper") .SetParent< ns3::UanPropModel > () ; return tid; } }; NS_OBJECT_ENSURE_REGISTERED (PyNs3UanPropModel__PythonHelper); typedef struct { PyObject_HEAD ns3::UanPropModelIdeal *obj; PyObject *inst_dict; PyBindGenWrapperFlags flags:8; } PyNs3UanPropModelIdeal; extern PyTypeObject PyNs3UanPropModelIdeal_Type; class PyNs3UanPropModelIdeal__PythonHelper : public ns3::UanPropModelIdeal { public: PyObject *m_pyself; PyNs3UanPropModelIdeal__PythonHelper(ns3::UanPropModelIdeal const & arg0) : ns3::UanPropModelIdeal(arg0), m_pyself(NULL) {} PyNs3UanPropModelIdeal__PythonHelper() : ns3::UanPropModelIdeal(), m_pyself(NULL) {} void set_pyobj(PyObject *pyobj) { Py_XDECREF(m_pyself); Py_INCREF(pyobj); m_pyself = pyobj; } virtual ~PyNs3UanPropModelIdeal__PythonHelper() { Py_CLEAR(m_pyself); } static PyObject * _wrap_NotifyConstructionCompleted(PyNs3UanPropModelIdeal *self); inline void NotifyConstructionCompleted__parent_caller() { ns3::ObjectBase::NotifyConstructionCompleted(); } static PyObject * _wrap_NotifyNewAggregate(PyNs3UanPropModelIdeal *self); inline void NotifyNewAggregate__parent_caller() { ns3::Object::NotifyNewAggregate(); } static PyObject * _wrap_DoStart(PyNs3UanPropModelIdeal *self); inline void DoStart__parent_caller() { ns3::Object::DoStart(); } virtual ns3::Time GetDelay(ns3::Ptr< ns3::MobilityModel > a, ns3::Ptr< ns3::MobilityModel > b, ns3::UanTxMode mode); virtual double GetPathLossDb(ns3::Ptr< ns3::MobilityModel > a, ns3::Ptr< ns3::MobilityModel > b, ns3::UanTxMode mode); virtual ns3::UanPdp GetPdp(ns3::Ptr< ns3::MobilityModel > a, ns3::Ptr< ns3::MobilityModel > b, ns3::UanTxMode mode); virtual void Clear(); virtual void DoDispose(); virtual ns3::TypeId GetInstanceTypeId() const; virtual void DoStart(); virtual void NotifyNewAggregate(); virtual void NotifyConstructionCompleted(); static ns3::TypeId GetTypeId (void) { static ns3::TypeId tid = ns3::TypeId ("PyNs3UanPropModelIdeal__PythonHelper") .SetParent< ns3::UanPropModelIdeal > () ; return tid; } }; NS_OBJECT_ENSURE_REGISTERED (PyNs3UanPropModelIdeal__PythonHelper); typedef struct { PyObject_HEAD ns3::UanPropModelThorp *obj; PyObject *inst_dict; PyBindGenWrapperFlags flags:8; } PyNs3UanPropModelThorp; extern PyTypeObject PyNs3UanPropModelThorp_Type; class PyNs3UanPropModelThorp__PythonHelper : public ns3::UanPropModelThorp { public: PyObject *m_pyself; PyNs3UanPropModelThorp__PythonHelper(ns3::UanPropModelThorp const & arg0) : ns3::UanPropModelThorp(arg0), m_pyself(NULL) {} PyNs3UanPropModelThorp__PythonHelper() : ns3::UanPropModelThorp(), m_pyself(NULL) {} void set_pyobj(PyObject *pyobj) { Py_XDECREF(m_pyself); Py_INCREF(pyobj); m_pyself = pyobj; } virtual ~PyNs3UanPropModelThorp__PythonHelper() { Py_CLEAR(m_pyself); } static PyObject * _wrap_NotifyConstructionCompleted(PyNs3UanPropModelThorp *self); inline void NotifyConstructionCompleted__parent_caller() { ns3::ObjectBase::NotifyConstructionCompleted(); } static PyObject * _wrap_NotifyNewAggregate(PyNs3UanPropModelThorp *self); inline void NotifyNewAggregate__parent_caller() { ns3::Object::NotifyNewAggregate(); } static PyObject * _wrap_DoStart(PyNs3UanPropModelThorp *self); inline void DoStart__parent_caller() { ns3::Object::DoStart(); } virtual ns3::Time GetDelay(ns3::Ptr< ns3::MobilityModel > a, ns3::Ptr< ns3::MobilityModel > b, ns3::UanTxMode mode); virtual double GetPathLossDb(ns3::Ptr< ns3::MobilityModel > a, ns3::Ptr< ns3::MobilityModel > b, ns3::UanTxMode mode); virtual ns3::UanPdp GetPdp(ns3::Ptr< ns3::MobilityModel > a, ns3::Ptr< ns3::MobilityModel > b, ns3::UanTxMode mode); virtual void Clear(); virtual void DoDispose(); virtual ns3::TypeId GetInstanceTypeId() const; virtual void DoStart(); virtual void NotifyNewAggregate(); virtual void NotifyConstructionCompleted(); static ns3::TypeId GetTypeId (void) { static ns3::TypeId tid = ns3::TypeId ("PyNs3UanPropModelThorp__PythonHelper") .SetParent< ns3::UanPropModelThorp > () ; return tid; } }; NS_OBJECT_ENSURE_REGISTERED (PyNs3UanPropModelThorp__PythonHelper); typedef struct { PyObject_HEAD ns3::UanTransducer *obj; PyObject *inst_dict; PyBindGenWrapperFlags flags:8; } PyNs3UanTransducer; extern PyTypeObject PyNs3UanTransducer_Type; typedef struct { PyObject_HEAD ns3::UanTransducerHd *obj; PyObject *inst_dict; PyBindGenWrapperFlags flags:8; } PyNs3UanTransducerHd; extern PyTypeObject PyNs3UanTransducerHd_Type; typedef struct { PyObject_HEAD ns3::UanChannel *obj; PyObject *inst_dict; PyBindGenWrapperFlags flags:8; } PyNs3UanChannel; extern PyTypeObject PyNs3UanChannel_Type; class PyNs3UanChannel__PythonHelper : public ns3::UanChannel { public: PyObject *m_pyself; PyNs3UanChannel__PythonHelper(ns3::UanChannel const & arg0) : ns3::UanChannel(arg0), m_pyself(NULL) {} PyNs3UanChannel__PythonHelper() : ns3::UanChannel(), m_pyself(NULL) {} void set_pyobj(PyObject *pyobj) { Py_XDECREF(m_pyself); Py_INCREF(pyobj); m_pyself = pyobj; } virtual ~PyNs3UanChannel__PythonHelper() { Py_CLEAR(m_pyself); } static PyObject * _wrap_NotifyConstructionCompleted(PyNs3UanChannel *self); inline void NotifyConstructionCompleted__parent_caller() { ns3::ObjectBase::NotifyConstructionCompleted(); } static PyObject * _wrap_NotifyNewAggregate(PyNs3UanChannel *self); inline void NotifyNewAggregate__parent_caller() { ns3::Object::NotifyNewAggregate(); } static PyObject * _wrap_DoStart(PyNs3UanChannel *self); inline void DoStart__parent_caller() { ns3::Object::DoStart(); } static PyObject * _wrap_DoDispose(PyNs3UanChannel *self); inline void DoDispose__parent_caller() { ns3::UanChannel::DoDispose(); } virtual ns3::Ptr< ns3::NetDevice > GetDevice(uint32_t i) const; virtual uint32_t GetNDevices() const; virtual void DoDispose(); virtual ns3::TypeId GetInstanceTypeId() const; virtual void DoStart(); virtual void NotifyNewAggregate(); virtual void NotifyConstructionCompleted(); static ns3::TypeId GetTypeId (void) { static ns3::TypeId tid = ns3::TypeId ("PyNs3UanChannel__PythonHelper") .SetParent< ns3::UanChannel > () ; return tid; } }; NS_OBJECT_ENSURE_REGISTERED (PyNs3UanChannel__PythonHelper); typedef struct { PyObject_HEAD ns3::UanModesListChecker *obj; PyBindGenWrapperFlags flags:8; } PyNs3UanModesListChecker; extern PyTypeObject PyNs3UanModesListChecker_Type; typedef struct { PyObject_HEAD ns3::UanModesListValue *obj; PyBindGenWrapperFlags flags:8; } PyNs3UanModesListValue; extern PyTypeObject PyNs3UanModesListValue_Type; typedef struct { PyObject_HEAD ns3::UanNetDevice *obj; PyObject *inst_dict; PyBindGenWrapperFlags flags:8; } PyNs3UanNetDevice; extern PyTypeObject PyNs3UanNetDevice_Type; typedef struct { PyObject_HEAD ns3::AcousticModemEnergyModel *obj; PyObject *inst_dict; PyBindGenWrapperFlags flags:8; } PyNs3AcousticModemEnergyModel; extern PyTypeObject PyNs3AcousticModemEnergyModel_Type; class PyNs3AcousticModemEnergyModel__PythonHelper : public ns3::AcousticModemEnergyModel { public: PyObject *m_pyself; PyNs3AcousticModemEnergyModel__PythonHelper(ns3::AcousticModemEnergyModel const & arg0) : ns3::AcousticModemEnergyModel(arg0), m_pyself(NULL) {} PyNs3AcousticModemEnergyModel__PythonHelper() : ns3::AcousticModemEnergyModel(), m_pyself(NULL) {} void set_pyobj(PyObject *pyobj) { Py_XDECREF(m_pyself); Py_INCREF(pyobj); m_pyself = pyobj; } virtual ~PyNs3AcousticModemEnergyModel__PythonHelper() { Py_CLEAR(m_pyself); } static PyObject * _wrap_NotifyConstructionCompleted(PyNs3AcousticModemEnergyModel *self); inline void NotifyConstructionCompleted__parent_caller() { ns3::ObjectBase::NotifyConstructionCompleted(); } static PyObject * _wrap_NotifyNewAggregate(PyNs3AcousticModemEnergyModel *self); inline void NotifyNewAggregate__parent_caller() { ns3::Object::NotifyNewAggregate(); } static PyObject * _wrap_DoStart(PyNs3AcousticModemEnergyModel *self); inline void DoStart__parent_caller() { ns3::Object::DoStart(); } virtual void ChangeState(int newState); virtual ns3::Ptr< ns3::Node > GetNode() const; virtual double GetTotalEnergyConsumption() const; virtual void HandleEnergyDepletion(); virtual void SetEnergySource(ns3::Ptr< ns3::EnergySource > source); virtual void SetNode(ns3::Ptr< ns3::Node > node); virtual void DoDispose(); virtual double DoGetCurrentA() const; virtual ns3::TypeId GetInstanceTypeId() const; virtual void DoStart(); virtual void NotifyNewAggregate(); virtual void NotifyConstructionCompleted(); static ns3::TypeId GetTypeId (void) { static ns3::TypeId tid = ns3::TypeId ("PyNs3AcousticModemEnergyModel__PythonHelper") .SetParent< ns3::AcousticModemEnergyModel > () ; return tid; } }; NS_OBJECT_ENSURE_REGISTERED (PyNs3AcousticModemEnergyModel__PythonHelper); typedef struct { PyObject_HEAD std::vector< ns3::Tap > *obj; } Pystd__vector__lt___ns3__Tap___gt__; typedef struct { PyObject_HEAD Pystd__vector__lt___ns3__Tap___gt__ *container; std::vector< ns3::Tap >::iterator *iterator; } Pystd__vector__lt___ns3__Tap___gt__Iter; extern PyTypeObject Pystd__vector__lt___ns3__Tap___gt___Type; extern PyTypeObject Pystd__vector__lt___ns3__Tap___gt__Iter_Type; int _wrap_convert_py2c__std__vector__lt___ns3__Tap___gt__(PyObject *arg, std::vector< ns3::Tap > *container); typedef struct { PyObject_HEAD std::vector< double > *obj; } Pystd__vector__lt___double___gt__; typedef struct { PyObject_HEAD Pystd__vector__lt___double___gt__ *container; std::vector< double >::iterator *iterator; } Pystd__vector__lt___double___gt__Iter; extern PyTypeObject Pystd__vector__lt___double___gt___Type; extern PyTypeObject Pystd__vector__lt___double___gt__Iter_Type; int _wrap_convert_py2c__std__vector__lt___double___gt__(PyObject *arg, std::vector< double > *container); typedef struct { PyObject_HEAD std::set< unsigned char > *obj; } Pystd__set__lt___unsigned_char___gt__; typedef struct { PyObject_HEAD Pystd__set__lt___unsigned_char___gt__ *container; std::set< unsigned char >::iterator *iterator; } Pystd__set__lt___unsigned_char___gt__Iter; extern PyTypeObject Pystd__set__lt___unsigned_char___gt___Type; extern PyTypeObject Pystd__set__lt___unsigned_char___gt__Iter_Type; int _wrap_convert_py2c__std__set__lt___unsigned_char___gt__(PyObject *arg, std::set< unsigned char > *container); typedef struct { PyObject_HEAD std::list< ns3::UanPacketArrival > *obj; } Pystd__list__lt___ns3__UanPacketArrival___gt__; typedef struct { PyObject_HEAD Pystd__list__lt___ns3__UanPacketArrival___gt__ *container; std::list< ns3::UanPacketArrival >::iterator *iterator; } Pystd__list__lt___ns3__UanPacketArrival___gt__Iter; extern PyTypeObject Pystd__list__lt___ns3__UanPacketArrival___gt___Type; extern PyTypeObject Pystd__list__lt___ns3__UanPacketArrival___gt__Iter_Type; int _wrap_convert_py2c__std__list__lt___ns3__UanPacketArrival___gt__(PyObject *arg, std::list< ns3::UanPacketArrival > *container); typedef struct { PyObject_HEAD std::list< ns3::Ptr< ns3::UanPhy > > *obj; } Pystd__list__lt___ns3__Ptr__lt___ns3__UanPhy___gt_____gt__; typedef struct { PyObject_HEAD Pystd__list__lt___ns3__Ptr__lt___ns3__UanPhy___gt_____gt__ *container; std::list< ns3::Ptr< ns3::UanPhy > >::iterator *iterator; } Pystd__list__lt___ns3__Ptr__lt___ns3__UanPhy___gt_____gt__Iter; extern PyTypeObject Pystd__list__lt___ns3__Ptr__lt___ns3__UanPhy___gt_____gt___Type; extern PyTypeObject Pystd__list__lt___ns3__Ptr__lt___ns3__UanPhy___gt_____gt__Iter_Type; int _wrap_convert_py2c__std__list__lt___ns3__Ptr__lt___ns3__UanPhy___gt_____gt__(PyObject *arg, std::list< ns3::Ptr< ns3::UanPhy > > *container); typedef struct { PyObject_HEAD std::list< ns3::Ptr< ns3::UanTransducer > > *obj; } Pystd__list__lt___ns3__Ptr__lt___ns3__UanTransducer___gt_____gt__; typedef struct { PyObject_HEAD Pystd__list__lt___ns3__Ptr__lt___ns3__UanTransducer___gt_____gt__ *container; std::list< ns3::Ptr< ns3::UanTransducer > >::iterator *iterator; } Pystd__list__lt___ns3__Ptr__lt___ns3__UanTransducer___gt_____gt__Iter; extern PyTypeObject Pystd__list__lt___ns3__Ptr__lt___ns3__UanTransducer___gt_____gt___Type; extern PyTypeObject Pystd__list__lt___ns3__Ptr__lt___ns3__UanTransducer___gt_____gt__Iter_Type; int _wrap_convert_py2c__std__list__lt___ns3__Ptr__lt___ns3__UanTransducer___gt_____gt__(PyObject *arg, std::list< ns3::Ptr< ns3::UanTransducer > > *container); class PythonCallbackImpl0 : public ns3::CallbackImpl<void, int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> { public: PyObject *m_callback; PythonCallbackImpl0(PyObject *callback) { Py_INCREF(callback); m_callback = callback; } virtual ~PythonCallbackImpl0() { Py_DECREF(m_callback); m_callback = NULL; } virtual bool IsEqual(ns3::Ptr<const ns3::CallbackImplBase> other_base) const { const PythonCallbackImpl0 *other = dynamic_cast<const PythonCallbackImpl0*> (ns3::PeekPointer (other_base)); if (other != NULL) return (other->m_callback == m_callback); else return false; } void operator()(int arg1) { PyGILState_STATE __py_gil_state; PyObject *py_retval; PyObject *args; __py_gil_state = (PyEval_ThreadsInitialized() ? PyGILState_Ensure() : (PyGILState_STATE) 0); args = Py_BuildValue((char *) "(i)", arg1); py_retval = PyObject_CallObject(m_callback, args); if (py_retval == NULL) { Py_DECREF(args); if (PyEval_ThreadsInitialized()) PyGILState_Release(__py_gil_state); return; } if (py_retval != Py_None) { PyErr_SetString(PyExc_TypeError, "function/method should return None"); Py_DECREF(py_retval); Py_DECREF(args); if (PyEval_ThreadsInitialized()) PyGILState_Release(__py_gil_state); return; } Py_DECREF(py_retval); Py_DECREF(args); if (PyEval_ThreadsInitialized()) PyGILState_Release(__py_gil_state); return; } }; class PythonCallbackImpl1 : public ns3::CallbackImpl<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> { public: PyObject *m_callback; PythonCallbackImpl1(PyObject *callback) { Py_INCREF(callback); m_callback = callback; } virtual ~PythonCallbackImpl1() { Py_DECREF(m_callback); m_callback = NULL; } virtual bool IsEqual(ns3::Ptr<const ns3::CallbackImplBase> other_base) const { const PythonCallbackImpl1 *other = dynamic_cast<const PythonCallbackImpl1*> (ns3::PeekPointer (other_base)); if (other != NULL) return (other->m_callback == m_callback); else return false; } void operator()() { PyGILState_STATE __py_gil_state; PyObject *py_retval; PyObject *args; __py_gil_state = (PyEval_ThreadsInitialized() ? PyGILState_Ensure() : (PyGILState_STATE) 0); args = Py_BuildValue((char *) "()"); py_retval = PyObject_CallObject(m_callback, args); if (py_retval == NULL) { Py_DECREF(args); if (PyEval_ThreadsInitialized()) PyGILState_Release(__py_gil_state); return; } if (py_retval != Py_None) { PyErr_SetString(PyExc_TypeError, "function/method should return None"); Py_DECREF(py_retval); Py_DECREF(args); if (PyEval_ThreadsInitialized()) PyGILState_Release(__py_gil_state); return; } Py_DECREF(py_retval); Py_DECREF(args); if (PyEval_ThreadsInitialized()) PyGILState_Release(__py_gil_state); return; } }; class PythonCallbackImpl2 : public ns3::CallbackImpl<void, ns3::Ptr<ns3::Packet>, double, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> { public: PyObject *m_callback; PythonCallbackImpl2(PyObject *callback) { Py_INCREF(callback); m_callback = callback; } virtual ~PythonCallbackImpl2() { Py_DECREF(m_callback); m_callback = NULL; } virtual bool IsEqual(ns3::Ptr<const ns3::CallbackImplBase> other_base) const { const PythonCallbackImpl2 *other = dynamic_cast<const PythonCallbackImpl2*> (ns3::PeekPointer (other_base)); if (other != NULL) return (other->m_callback == m_callback); else return false; } void operator()(ns3::Ptr< ns3::Packet > arg1, double arg2) { PyGILState_STATE __py_gil_state; PyObject *py_retval; PyNs3Packet *py_Packet; std::map<void*, PyObject*>::const_iterator wrapper_lookup_iter; PyTypeObject *wrapper_type = 0; PyObject *args; __py_gil_state = (PyEval_ThreadsInitialized() ? PyGILState_Ensure() : (PyGILState_STATE) 0); wrapper_lookup_iter = PyNs3Empty_wrapper_registry.find((void *) const_cast<ns3::Packet *> (ns3::PeekPointer (arg1))); if (wrapper_lookup_iter == PyNs3Empty_wrapper_registry.end()) { py_Packet = NULL; } else { py_Packet = (PyNs3Packet *) wrapper_lookup_iter->second; Py_INCREF(py_Packet); } if (py_Packet == NULL) { wrapper_type = PyNs3SimpleRefCount__Ns3Packet_Ns3Empty_Ns3DefaultDeleter__lt__ns3Packet__gt____typeid_map.lookup_wrapper(typeid(*const_cast<ns3::Packet *> (ns3::PeekPointer (arg1))), &PyNs3Packet_Type); py_Packet = PyObject_New(PyNs3Packet, wrapper_type); py_Packet->flags = PYBINDGEN_WRAPPER_FLAG_NONE; const_cast<ns3::Packet *> (ns3::PeekPointer (arg1))->Ref(); py_Packet->obj = const_cast<ns3::Packet *> (ns3::PeekPointer (arg1)); PyNs3Empty_wrapper_registry[(void *) py_Packet->obj] = (PyObject *) py_Packet; } args = Py_BuildValue((char *) "(Nd)", py_Packet, arg2); py_retval = PyObject_CallObject(m_callback, args); if (py_retval == NULL) { Py_DECREF(args); if (PyEval_ThreadsInitialized()) PyGILState_Release(__py_gil_state); return; } if (py_retval != Py_None) { PyErr_SetString(PyExc_TypeError, "function/method should return None"); Py_DECREF(py_retval); Py_DECREF(args); if (PyEval_ThreadsInitialized()) PyGILState_Release(__py_gil_state); return; } Py_DECREF(py_retval); Py_DECREF(args); if (PyEval_ThreadsInitialized()) PyGILState_Release(__py_gil_state); return; } }; class PythonCallbackImpl3 : public ns3::CallbackImpl<void, ns3::Ptr<ns3::Packet>, double, ns3::UanTxMode, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> { public: PyObject *m_callback; PythonCallbackImpl3(PyObject *callback) { Py_INCREF(callback); m_callback = callback; } virtual ~PythonCallbackImpl3() { Py_DECREF(m_callback); m_callback = NULL; } virtual bool IsEqual(ns3::Ptr<const ns3::CallbackImplBase> other_base) const { const PythonCallbackImpl3 *other = dynamic_cast<const PythonCallbackImpl3*> (ns3::PeekPointer (other_base)); if (other != NULL) return (other->m_callback == m_callback); else return false; } void operator()(ns3::Ptr< ns3::Packet > arg1, double arg2, ns3::UanTxMode arg3) { PyGILState_STATE __py_gil_state; PyObject *py_retval; PyNs3Packet *py_Packet; std::map<void*, PyObject*>::const_iterator wrapper_lookup_iter; PyTypeObject *wrapper_type = 0; PyNs3UanTxMode *py_UanTxMode; PyObject *args; __py_gil_state = (PyEval_ThreadsInitialized() ? PyGILState_Ensure() : (PyGILState_STATE) 0); wrapper_lookup_iter = PyNs3Empty_wrapper_registry.find((void *) const_cast<ns3::Packet *> (ns3::PeekPointer (arg1))); if (wrapper_lookup_iter == PyNs3Empty_wrapper_registry.end()) { py_Packet = NULL; } else { py_Packet = (PyNs3Packet *) wrapper_lookup_iter->second; Py_INCREF(py_Packet); } if (py_Packet == NULL) { wrapper_type = PyNs3SimpleRefCount__Ns3Packet_Ns3Empty_Ns3DefaultDeleter__lt__ns3Packet__gt____typeid_map.lookup_wrapper(typeid(*const_cast<ns3::Packet *> (ns3::PeekPointer (arg1))), &PyNs3Packet_Type); py_Packet = PyObject_New(PyNs3Packet, wrapper_type); py_Packet->flags = PYBINDGEN_WRAPPER_FLAG_NONE; const_cast<ns3::Packet *> (ns3::PeekPointer (arg1))->Ref(); py_Packet->obj = const_cast<ns3::Packet *> (ns3::PeekPointer (arg1)); PyNs3Empty_wrapper_registry[(void *) py_Packet->obj] = (PyObject *) py_Packet; } py_UanTxMode = PyObject_New(PyNs3UanTxMode, &PyNs3UanTxMode_Type); py_UanTxMode->flags = PYBINDGEN_WRAPPER_FLAG_NONE; py_UanTxMode->obj = new ns3::UanTxMode(arg3); PyNs3UanTxMode_wrapper_registry[(void *) py_UanTxMode->obj] = (PyObject *) py_UanTxMode; args = Py_BuildValue((char *) "(NdN)", py_Packet, arg2, py_UanTxMode); py_retval = PyObject_CallObject(m_callback, args); if (py_retval == NULL) { Py_DECREF(args); if (PyEval_ThreadsInitialized()) PyGILState_Release(__py_gil_state); return; } if (py_retval != Py_None) { PyErr_SetString(PyExc_TypeError, "function/method should return None"); Py_DECREF(py_retval); Py_DECREF(args); if (PyEval_ThreadsInitialized()) PyGILState_Release(__py_gil_state); return; } Py_DECREF(py_retval); Py_DECREF(args); if (PyEval_ThreadsInitialized()) PyGILState_Release(__py_gil_state); return; } }; class PythonCallbackImpl4 : public ns3::CallbackImpl<void, ns3::Ptr<ns3::Packet>, ns3::UanAddress const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> { public: PyObject *m_callback; PythonCallbackImpl4(PyObject *callback) { Py_INCREF(callback); m_callback = callback; } virtual ~PythonCallbackImpl4() { Py_DECREF(m_callback); m_callback = NULL; } virtual bool IsEqual(ns3::Ptr<const ns3::CallbackImplBase> other_base) const { const PythonCallbackImpl4 *other = dynamic_cast<const PythonCallbackImpl4*> (ns3::PeekPointer (other_base)); if (other != NULL) return (other->m_callback == m_callback); else return false; } void operator()(ns3::Ptr< ns3::Packet > arg1, ns3::UanAddress const & arg2) { PyGILState_STATE __py_gil_state; PyObject *py_retval; PyNs3Packet *py_Packet; std::map<void*, PyObject*>::const_iterator wrapper_lookup_iter; PyTypeObject *wrapper_type = 0; PyNs3UanAddress *py_UanAddress; PyObject *args; __py_gil_state = (PyEval_ThreadsInitialized() ? PyGILState_Ensure() : (PyGILState_STATE) 0); wrapper_lookup_iter = PyNs3Empty_wrapper_registry.find((void *) const_cast<ns3::Packet *> (ns3::PeekPointer (arg1))); if (wrapper_lookup_iter == PyNs3Empty_wrapper_registry.end()) { py_Packet = NULL; } else { py_Packet = (PyNs3Packet *) wrapper_lookup_iter->second; Py_INCREF(py_Packet); } if (py_Packet == NULL) { wrapper_type = PyNs3SimpleRefCount__Ns3Packet_Ns3Empty_Ns3DefaultDeleter__lt__ns3Packet__gt____typeid_map.lookup_wrapper(typeid(*const_cast<ns3::Packet *> (ns3::PeekPointer (arg1))), &PyNs3Packet_Type); py_Packet = PyObject_New(PyNs3Packet, wrapper_type); py_Packet->flags = PYBINDGEN_WRAPPER_FLAG_NONE; const_cast<ns3::Packet *> (ns3::PeekPointer (arg1))->Ref(); py_Packet->obj = const_cast<ns3::Packet *> (ns3::PeekPointer (arg1)); PyNs3Empty_wrapper_registry[(void *) py_Packet->obj] = (PyObject *) py_Packet; } py_UanAddress = PyObject_New(PyNs3UanAddress, &PyNs3UanAddress_Type); py_UanAddress->flags = PYBINDGEN_WRAPPER_FLAG_NONE; py_UanAddress->obj = new ns3::UanAddress(arg2); PyNs3UanAddress_wrapper_registry[(void *) py_UanAddress->obj] = (PyObject *) py_UanAddress; args = Py_BuildValue((char *) "(NN)", py_Packet, py_UanAddress); py_retval = PyObject_CallObject(m_callback, args); if (py_retval == NULL) { Py_DECREF(args); if (PyEval_ThreadsInitialized()) PyGILState_Release(__py_gil_state); return; } if (py_retval != Py_None) { PyErr_SetString(PyExc_TypeError, "function/method should return None"); Py_DECREF(py_retval); Py_DECREF(args); if (PyEval_ThreadsInitialized()) PyGILState_Release(__py_gil_state); return; } Py_DECREF(py_retval); Py_DECREF(args); if (PyEval_ThreadsInitialized()) PyGILState_Release(__py_gil_state); return; } }; class PythonCallbackImpl5 : public ns3::CallbackImpl<bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> { public: PyObject *m_callback; PythonCallbackImpl5(PyObject *callback) { Py_INCREF(callback); m_callback = callback; } virtual ~PythonCallbackImpl5() { Py_DECREF(m_callback); m_callback = NULL; } virtual bool IsEqual(ns3::Ptr<const ns3::CallbackImplBase> other_base) const { const PythonCallbackImpl5 *other = dynamic_cast<const PythonCallbackImpl5*> (ns3::PeekPointer (other_base)); if (other != NULL) return (other->m_callback == m_callback); else return false; } bool operator()(ns3::Ptr< ns3::NetDevice > arg1, ns3::Ptr< ns3::Packet const > arg2, unsigned short arg3, ns3::Address const & arg4) { PyGILState_STATE __py_gil_state; PyObject *py_retval; bool retval; PyNs3NetDevice *py_NetDevice; std::map<void*, PyObject*>::const_iterator wrapper_lookup_iter; PyTypeObject *wrapper_type = 0; PyNs3Packet *py_Packet; std::map<void*, PyObject*>::const_iterator wrapper_lookup_iter2; PyTypeObject *wrapper_type2 = 0; PyNs3Address *py_Address; PyObject *args; PyObject *py_boolretval; __py_gil_state = (PyEval_ThreadsInitialized() ? PyGILState_Ensure() : (PyGILState_STATE) 0); wrapper_lookup_iter = PyNs3ObjectBase_wrapper_registry.find((void *) const_cast<ns3::NetDevice *> (ns3::PeekPointer (arg1))); if (wrapper_lookup_iter == PyNs3ObjectBase_wrapper_registry.end()) { py_NetDevice = NULL; } else { py_NetDevice = (PyNs3NetDevice *) wrapper_lookup_iter->second; Py_INCREF(py_NetDevice); } if (py_NetDevice == NULL) { wrapper_type = PyNs3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter__typeid_map.lookup_wrapper(typeid(*const_cast<ns3::NetDevice *> (ns3::PeekPointer (arg1))), &PyNs3NetDevice_Type); py_NetDevice = PyObject_GC_New(PyNs3NetDevice, wrapper_type); py_NetDevice->inst_dict = NULL; py_NetDevice->flags = PYBINDGEN_WRAPPER_FLAG_NONE; const_cast<ns3::NetDevice *> (ns3::PeekPointer (arg1))->Ref(); py_NetDevice->obj = const_cast<ns3::NetDevice *> (ns3::PeekPointer (arg1)); PyNs3ObjectBase_wrapper_registry[(void *) py_NetDevice->obj] = (PyObject *) py_NetDevice; } wrapper_lookup_iter2 = PyNs3Empty_wrapper_registry.find((void *) const_cast<ns3::Packet *> (ns3::PeekPointer (arg2))); if (wrapper_lookup_iter2 == PyNs3Empty_wrapper_registry.end()) { py_Packet = NULL; } else { py_Packet = (PyNs3Packet *) wrapper_lookup_iter2->second; Py_INCREF(py_Packet); } if (py_Packet == NULL) { wrapper_type2 = PyNs3SimpleRefCount__Ns3Packet_Ns3Empty_Ns3DefaultDeleter__lt__ns3Packet__gt____typeid_map.lookup_wrapper(typeid(*const_cast<ns3::Packet *> (ns3::PeekPointer (arg2))), &PyNs3Packet_Type); py_Packet = PyObject_New(PyNs3Packet, wrapper_type2); py_Packet->flags = PYBINDGEN_WRAPPER_FLAG_NONE; const_cast<ns3::Packet *> (ns3::PeekPointer (arg2))->Ref(); py_Packet->obj = const_cast<ns3::Packet *> (ns3::PeekPointer (arg2)); PyNs3Empty_wrapper_registry[(void *) py_Packet->obj] = (PyObject *) py_Packet; } py_Address = PyObject_New(PyNs3Address, &PyNs3Address_Type); py_Address->flags = PYBINDGEN_WRAPPER_FLAG_NONE; py_Address->obj = new ns3::Address(arg4); PyNs3Address_wrapper_registry[(void *) py_Address->obj] = (PyObject *) py_Address; args = Py_BuildValue((char *) "(NNiN)", py_NetDevice, py_Packet, (int) arg3, py_Address); py_retval = PyObject_CallObject(m_callback, args); if (py_retval == NULL) { Py_DECREF(args); if (PyEval_ThreadsInitialized()) PyGILState_Release(__py_gil_state); return false; } py_retval = Py_BuildValue((char*) "(N)", py_retval); if (!PyArg_ParseTuple(py_retval, (char *) "O", &py_boolretval)) { PyErr_Print(); Py_DECREF(py_retval); Py_DECREF(args); if (PyEval_ThreadsInitialized()) PyGILState_Release(__py_gil_state); return false; } retval = PyObject_IsTrue(py_boolretval); Py_DECREF(py_retval); Py_DECREF(args); if (PyEval_ThreadsInitialized()) PyGILState_Release(__py_gil_state); return retval; } }; class PythonCallbackImpl6 : public ns3::CallbackImpl<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> { public: PyObject *m_callback; PythonCallbackImpl6(PyObject *callback) { Py_INCREF(callback); m_callback = callback; } virtual ~PythonCallbackImpl6() { Py_DECREF(m_callback); m_callback = NULL; } virtual bool IsEqual(ns3::Ptr<const ns3::CallbackImplBase> other_base) const { const PythonCallbackImpl6 *other = dynamic_cast<const PythonCallbackImpl6*> (ns3::PeekPointer (other_base)); if (other != NULL) return (other->m_callback == m_callback); else return false; } void operator()(ns3::Ptr< ns3::NetDevice > arg1, ns3::Ptr< ns3::Packet const > arg2, unsigned short arg3, ns3::Address const & arg4, ns3::Address const & arg5, ns3::NetDevice::PacketType arg6) { PyGILState_STATE __py_gil_state; PyObject *py_retval; PyNs3NetDevice *py_NetDevice; std::map<void*, PyObject*>::const_iterator wrapper_lookup_iter; PyTypeObject *wrapper_type = 0; PyNs3Packet *py_Packet; std::map<void*, PyObject*>::const_iterator wrapper_lookup_iter2; PyTypeObject *wrapper_type2 = 0; PyNs3Address *py_Address; PyNs3Address *py_Address2; PyObject *args; __py_gil_state = (PyEval_ThreadsInitialized() ? PyGILState_Ensure() : (PyGILState_STATE) 0); wrapper_lookup_iter = PyNs3ObjectBase_wrapper_registry.find((void *) const_cast<ns3::NetDevice *> (ns3::PeekPointer (arg1))); if (wrapper_lookup_iter == PyNs3ObjectBase_wrapper_registry.end()) { py_NetDevice = NULL; } else { py_NetDevice = (PyNs3NetDevice *) wrapper_lookup_iter->second; Py_INCREF(py_NetDevice); } if (py_NetDevice == NULL) { wrapper_type = PyNs3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter__typeid_map.lookup_wrapper(typeid(*const_cast<ns3::NetDevice *> (ns3::PeekPointer (arg1))), &PyNs3NetDevice_Type); py_NetDevice = PyObject_GC_New(PyNs3NetDevice, wrapper_type); py_NetDevice->inst_dict = NULL; py_NetDevice->flags = PYBINDGEN_WRAPPER_FLAG_NONE; const_cast<ns3::NetDevice *> (ns3::PeekPointer (arg1))->Ref(); py_NetDevice->obj = const_cast<ns3::NetDevice *> (ns3::PeekPointer (arg1)); PyNs3ObjectBase_wrapper_registry[(void *) py_NetDevice->obj] = (PyObject *) py_NetDevice; } wrapper_lookup_iter2 = PyNs3Empty_wrapper_registry.find((void *) const_cast<ns3::Packet *> (ns3::PeekPointer (arg2))); if (wrapper_lookup_iter2 == PyNs3Empty_wrapper_registry.end()) { py_Packet = NULL; } else { py_Packet = (PyNs3Packet *) wrapper_lookup_iter2->second; Py_INCREF(py_Packet); } if (py_Packet == NULL) { wrapper_type2 = PyNs3SimpleRefCount__Ns3Packet_Ns3Empty_Ns3DefaultDeleter__lt__ns3Packet__gt____typeid_map.lookup_wrapper(typeid(*const_cast<ns3::Packet *> (ns3::PeekPointer (arg2))), &PyNs3Packet_Type); py_Packet = PyObject_New(PyNs3Packet, wrapper_type2); py_Packet->flags = PYBINDGEN_WRAPPER_FLAG_NONE; const_cast<ns3::Packet *> (ns3::PeekPointer (arg2))->Ref(); py_Packet->obj = const_cast<ns3::Packet *> (ns3::PeekPointer (arg2)); PyNs3Empty_wrapper_registry[(void *) py_Packet->obj] = (PyObject *) py_Packet; } py_Address = PyObject_New(PyNs3Address, &PyNs3Address_Type); py_Address->flags = PYBINDGEN_WRAPPER_FLAG_NONE; py_Address->obj = new ns3::Address(arg4); PyNs3Address_wrapper_registry[(void *) py_Address->obj] = (PyObject *) py_Address; py_Address2 = PyObject_New(PyNs3Address, &PyNs3Address_Type); py_Address2->flags = PYBINDGEN_WRAPPER_FLAG_NONE; py_Address2->obj = new ns3::Address(arg5); PyNs3Address_wrapper_registry[(void *) py_Address2->obj] = (PyObject *) py_Address2; args = Py_BuildValue((char *) "(NNiNNi)", py_NetDevice, py_Packet, (int) arg3, py_Address, py_Address2, arg6); py_retval = PyObject_CallObject(m_callback, args); if (py_retval == NULL) { Py_DECREF(args); if (PyEval_ThreadsInitialized()) PyGILState_Release(__py_gil_state); return; } if (py_retval != Py_None) { PyErr_SetString(PyExc_TypeError, "function/method should return None"); Py_DECREF(py_retval); Py_DECREF(args); if (PyEval_ThreadsInitialized()) PyGILState_Release(__py_gil_state); return; } Py_DECREF(py_retval); Py_DECREF(args); if (PyEval_ThreadsInitialized()) PyGILState_Release(__py_gil_state); return; } }; int _wrap_convert_py2c__ns3__Tap(PyObject *value, ns3::Tap *address); int _wrap_convert_py2c__double(PyObject *value, double *address); int _wrap_convert_py2c__unsigned_char(PyObject *value, unsigned char *address); int _wrap_convert_py2c__ns3__UanPacketArrival(PyObject *value, ns3::UanPacketArrival *address); int _wrap_convert_py2c__ns3__Ptr__lt___ns3__UanPhy___gt__(PyObject *value, ns3::Ptr< ns3::UanPhy > *address); int _wrap_convert_py2c__ns3__Ptr__lt___ns3__UanTransducer___gt__(PyObject *value, ns3::Ptr< ns3::UanTransducer > *address);
Java
package dataservice.businessdataservice; import java.rmi.Remote; import java.rmi.RemoteException; import java.util.ArrayList; import po.BusinessPO; import po.DistributeReceiptPO; import po.DriverPO; import po.EnVehicleReceiptPO; import po.GatheringReceiptPO; import po.OrderAcceptReceiptPO; import po.OrganizationPO; import po.VehiclePO; /** * BusinessData */ public interface BusinessDataService extends Remote { // 根据营业厅ID(找到文件)和营业厅业务员ID(查找文件内容),ID为null就返回第一个 public BusinessPO getBusinessInfo(String organizationID, String ID) throws RemoteException; // 根据营业厅ID和车辆ID查询车辆PO public VehiclePO getVehicleInfo(String organizationID, String vehicleID) throws RemoteException; // 营业厅每日一个,每日早上8点发货一次 public boolean addReceipt(String organizationID, OrderAcceptReceiptPO po) throws RemoteException; // 获得某营业厅的全部车辆信息 public ArrayList<VehiclePO> getVehicleInfos(String organizationID) throws RemoteException; // 添加装车单到今日装车单文件中 public boolean addEnVehicleReceipt(String organizationID, ArrayList<EnVehicleReceiptPO> pos) throws RemoteException; // 增加一个车辆信息VehiclePO到VehiclePOList中 public boolean addVehicle(String organizationID, VehiclePO po) throws RemoteException; // 删除VehiclePOList中的一个车辆信息VehiclePO public boolean deleteVehicle(String organizationID, VehiclePO po) throws RemoteException; // 修改VehiclePOList中的一个车辆信息VehiclePO public boolean modifyVehicle(String organizationID, VehiclePO po) throws RemoteException; // 返回本营业厅司机信息列表 public ArrayList<DriverPO> getDriverInfos(String organizationID) throws RemoteException; // 增加一个GatheringReceipt到本营业厅今日的文件中,一天也就一个 public boolean addGatheringReceipt(String organizationID, GatheringReceiptPO grp) throws RemoteException; // 获得今日本营业厅OrderAcceptReceiptPO的个数 public int getNumOfOrderAcceptReceipt(String organizationID) throws RemoteException; // 返回规定日期的所有GatheringReceipt,time格式 2015-11-23 public ArrayList<GatheringReceiptPO> getGatheringReceipt(String time) throws RemoteException; public ArrayList<GatheringReceiptPO> getGatheringReceiptByHallID(String organization) throws RemoteException; public ArrayList<GatheringReceiptPO> getGatheringReceiptByBoth(String organization, String time) throws RemoteException; // 增加一个DistributeOrder到本营业厅今日的文件中,一天也就一个 public boolean addDistributeReceipt(String organizationID, DistributeReceiptPO po) throws RemoteException; // 查照死机 public DriverPO getDriverInfo(String organizationID, String ID) throws RemoteException; // 增加一个司机到本营业厅 public boolean addDriver(String organizationID, DriverPO po) throws RemoteException; // 删除一个司机到本营业厅 public boolean deleteDriver(String organizationID, DriverPO po) throws RemoteException; // 修改本营业厅该司机信息 public boolean modifyDriver(String organizationID, DriverPO po) throws RemoteException; /** * Lizi 收款单 */ public ArrayList<GatheringReceiptPO> getSubmittedGatheringReceiptInfo() throws RemoteException; /** * Lizi 派件单 */ public ArrayList<DistributeReceiptPO> getSubmittedDistributeReceiptInfo() throws RemoteException; /** * Lizi 装车 */ public ArrayList<EnVehicleReceiptPO> getSubmittedEnVehicleReceiptInfo() throws RemoteException; /** * Lizi 到达单 */ public ArrayList<OrderAcceptReceiptPO> getSubmittedOrderAcceptReceiptInfo() throws RemoteException; public void saveDistributeReceiptInfo(DistributeReceiptPO po) throws RemoteException; public void saveOrderAcceptReceiptInfo(OrderAcceptReceiptPO po) throws RemoteException; public void saveEnVehicleReceiptInfo(EnVehicleReceiptPO po) throws RemoteException; public void saveGatheringReceiptInfo(GatheringReceiptPO po) throws RemoteException; // public boolean addDriverTime(String organizationID, String driverID) throws RemoteException; public ArrayList<OrganizationPO> getOrganizationInfos() throws RemoteException; public int getNumOfVehicles(String organizationID) throws RemoteException; public int getNumOfDrivers(String organizationID) throws RemoteException; public int getNumOfEnVechileReceipt(String organizationID) throws RemoteException; public int getNumOfOrderReceipt(String organizationID) throws RemoteException; public int getNumOfOrderDistributeReceipt(String organizationID) throws RemoteException; // // /** // * 返回待转运的订单的列表 // */ // public ArrayList<OrderPO> getTransferOrders() throws RemoteException; // // /** // * 返回待派送的订单的列表 // */ // public ArrayList<VehiclePO> getFreeVehicles() throws RemoteException; // // /** // * 生成装车单 // */ // public boolean addEnVehicleReceiptPO(EnVehicleReceiptPO po) throws // RemoteException; // // /** // * 获取收款汇总单 // */ // public ArrayList<GatheringReceiptPO> getGatheringReceiptPOs() throws // RemoteException; // // /** // * 增加收货单 // */ // public boolean addReceipt(OrderAcceptReceiptPO po) throws // RemoteException; // // /** // * 增加收款汇总单 // */ // // public boolean addGatheringReceipt(GatheringReceiptPO po); }
Java
# OpenStack ocata installation script on Ubuntu 16.04.2 # by kasidit chanchio # vasabilab, dept of computer science, # Thammasat University, Thailand # # Copyright 2017 Kasidit Chanchio # # run with sudo or as root. # #!/bin/bash -x cd $HOME/OPSInstaller/controller pwd # apt-get -y install keystone # cp files/keystone.conf /etc/keystone/keystone.conf echo "su -s /bin/sh -c \"keystone-manage db_sync\" keystone" su -s /bin/sh -c "keystone-manage db_sync" keystone # #echo keystone-manage fernet_setup --keystone-user keystone --keystone-group keystone keystone-manage fernet_setup --keystone-user keystone --keystone-group keystone keystone-manage credential_setup --keystone-user keystone --keystone-group keystone keystone-manage bootstrap --bootstrap-password adminpassword \ --bootstrap-admin-url http://controller:35357/v3/ \ --bootstrap-internal-url http://controller:5000/v3/ \ --bootstrap-public-url http://controller:5000/v3/ \ --bootstrap-region-id RegionOne # cp files/apache2.conf /etc/apache2/apache2.conf # service apache2 restart rm -f /var/lib/keystone/keystone.db
Java
FusionCharts.ready(function () { var gradientCheckBox = document.getElementById('useGradient'); //Set event listener for radio button if (gradientCheckBox.addEventListener) { gradientCheckBox.addEventListener("click", changeGradient); } function changeGradient(evt, obj) { //Set gradient fill for chart using usePlotGradientColor attribute (gradientCheckBox.checked) ?revenueChart.setChartAttribute('usePlotGradientColor', 1) : revenueChart.setChartAttribute('usePlotGradientColor', 0); }; var revenueChart = new FusionCharts({ type: 'column2d', renderAt: 'chart-container', width: '400', height: '300', dataFormat: 'json', dataSource: { "chart": { "caption": "Quarterly Revenue", "subCaption": "Last year", "xAxisName": "Quarter", "yAxisName": "Amount (In USD)", "theme": "fint", "numberPrefix": "$", //Removing default gradient fill from columns "usePlotGradientColor": "1" }, "data": [{ "label": "Q1", "value": "1950000", "color": "#008ee4" }, { "label": "Q2", "value": "1450000", "color": "#9b59b6" }, { "label": "Q3", "value": "1730000", "color": "#6baa01" }, { "label": "Q4", "value": "2120000", "color": "#e44a00" }] } }).render(); });
Java
/* Copyright (C) 2009 - 2012 by Bartosz Waresiak <dragonking@o2.pl> Part of the Battle for Wesnoth Project http://www.wesnoth.org/ 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. See the COPYING file for more details. */ #ifndef FORMULA_AI_FUNCTION_TABLE_HPP_INCLUDED #define FORMULA_AI_FUNCTION_TABLE_HPP_INCLUDED #include "formula_function.hpp" #include <set> namespace ai { class formula_ai; } namespace game_logic { class ai_function_symbol_table : public function_symbol_table { public: explicit ai_function_symbol_table(ai::formula_ai& ai) : ai_(ai), move_functions() {} expression_ptr create_function(const std::string& fn, const std::vector<expression_ptr>& args) const; private: ai::formula_ai& ai_; std::set<std::string> move_functions; }; } #endif /* FORMULA_AI_FUNCTION_TABLE_HPP_INCLUDED */
Java
/* -*- mode: c -*- */ /* Copyright (C) 2005-2016 Alexander Chernov <cher@ejudge.ru> */ /* * 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. */ #include "ejudge/cpu.h" #include "ejudge/errlog.h" #include <stdlib.h> int cpu_get_bogomips(void) { err("cpu_get_bogomips: not implemented"); return -1; } void cpu_get_performance_info(unsigned char **p_model, unsigned char **p_mhz) { *p_model = NULL; *p_mhz = NULL; }
Java
/* * This file is part of the UCB release of Plan 9. It is subject to the license * terms in the LICENSE file found in the top-level directory of this * distribution and at http://akaros.cs.berkeley.edu/files/Plan9License. No * part of the UCB release of Plan 9, including this file, may be copied, * modified, propagated, or distributed except according to the terms contained * in the LICENSE file. */ #include <u.h> #include <libc.h> #include <bio.h> #include "pci.h" #include "vga.h" /* * ATI Mach64 family. */ enum { HTotalDisp, HSyncStrtWid, VTotalDisp, VSyncStrtWid, VlineCrntVline, OffPitch, IntCntl, CrtcGenCntl, OvrClr, OvrWidLR, OvrWidTB, CurClr0, CurClr1, CurOffset, CurHVposn, CurHVoff, ScratchReg0, ScratchReg1, /* Scratch Register (BIOS info) */ ClockCntl, BusCntl, MemCntl, ExtMemCntl, MemVgaWpSel, MemVgaRpSel, DacRegs, DacCntl, GenTestCntl, ConfigCntl, /* Configuration control */ ConfigChipId, ConfigStat0, /* Configuration status 0 */ ConfigStat1, /* Configuration status 1 */ ConfigStat2, DspConfig, /* Rage */ DspOnOff, /* Rage */ DpBkgdClr, DpChainMsk, DpFrgdClr, DpMix, DpPixWidth, DpSrc, DpWriteMsk, LcdIndex, LcdData, Nreg, TvIndex = 0x1D, TvData = 0x27, LCD_ConfigPanel = 0, LCD_GenCtrl, LCD_DstnCntl, LCD_HfbPitchAddr, LCD_HorzStretch, LCD_VertStretch, LCD_ExtVertStretch, LCD_LtGio, LCD_PowerMngmnt, LCD_ZvgPio, Nlcd, }; static char* iorname[Nreg] = { "HTotalDisp", "HSyncStrtWid", "VTotalDisp", "VSyncStrtWid", "VlineCrntVline", "OffPitch", "IntCntl", "CrtcGenCntl", "OvrClr", "OvrWidLR", "OvrWidTB", "CurClr0", "CurClr1", "CurOffset", "CurHVposn", "CurHVoff", "ScratchReg0", "ScratchReg1", "ClockCntl", "BusCntl", "MemCntl", "ExtMemCntl", "MemVgaWpSel", "MemVgaRpSel", "DacRegs", "DacCntl", "GenTestCntl", "ConfigCntl", "ConfigChipId", "ConfigStat0", "ConfigStat1", "ConfigStat2", "DspConfig", "DspOnOff", "DpBkgdClr", "DpChainMsk", "DpFrgdClr", "DpMix", "DpPixWidth", "DpSrc", "DpWriteMsk", "LcdIndex", "LcdData", }; static char* lcdname[Nlcd] = { "LCD ConfigPanel", "LCD GenCntl", "LCD DstnCntl", "LCD HfbPitchAddr", "LCD HorzStretch", "LCD VertStretch", "LCD ExtVertStretch", "LCD LtGio", "LCD PowerMngmnt", "LCD ZvgPio" }; /* * Crummy hack: all io register offsets * here get IOREG or'ed in, so that we can * tell the difference between an uninitialized * array entry and HTotalDisp. */ enum { IOREG = 0x10000, }; static ushort ioregs[Nreg] = { [HTotalDisp] IOREG|0x0000, [HSyncStrtWid] IOREG|0x0100, [VTotalDisp] IOREG|0x0200, [VSyncStrtWid] IOREG|0x0300, [VlineCrntVline] IOREG|0x0400, [OffPitch] IOREG|0x0500, [IntCntl] IOREG|0x0600, [CrtcGenCntl] IOREG|0x0700, [OvrClr] IOREG|0x0800, [OvrWidLR] IOREG|0x0900, [OvrWidTB] IOREG|0x0A00, [CurClr0] IOREG|0x0B00, [CurClr1] IOREG|0x0C00, [CurOffset] IOREG|0x0D00, [CurHVposn] IOREG|0x0E00, [CurHVoff] IOREG|0x0F00, [ScratchReg0] IOREG|0x1000, [ScratchReg1] IOREG|0x1100, [ClockCntl] IOREG|0x1200, [BusCntl] IOREG|0x1300, [MemCntl] IOREG|0x1400, [MemVgaWpSel] IOREG|0x1500, [MemVgaRpSel] IOREG|0x1600, [DacRegs] IOREG|0x1700, [DacCntl] IOREG|0x1800, [GenTestCntl] IOREG|0x1900, [ConfigCntl] IOREG|0x1A00, [ConfigChipId] IOREG|0x1B00, [ConfigStat0] IOREG|0x1C00, [ConfigStat1] IOREG|0x1D00, /* [GpIo] IOREG|0x1E00, */ /* [HTotalDisp] IOREG|0x1F00, duplicate, says XFree86 */ }; static ushort pciregs[Nreg] = { [HTotalDisp] 0x00, [HSyncStrtWid] 0x01, [VTotalDisp] 0x02, [VSyncStrtWid] 0x03, [VlineCrntVline] 0x04, [OffPitch] 0x05, [IntCntl] 0x06, [CrtcGenCntl] 0x07, [DspConfig] 0x08, [DspOnOff] 0x09, [OvrClr] 0x10, [OvrWidLR] 0x11, [OvrWidTB] 0x12, [CurClr0] 0x18, [CurClr1] 0x19, [CurOffset] 0x1A, [CurHVposn] 0x1B, [CurHVoff] 0x1C, [ScratchReg0] 0x20, [ScratchReg1] 0x21, [ClockCntl] 0x24, [BusCntl] 0x28, [LcdIndex] 0x29, [LcdData] 0x2A, [ExtMemCntl] 0x2B, [MemCntl] 0x2C, [MemVgaWpSel] 0x2D, [MemVgaRpSel] 0x2E, [DacRegs] 0x30, [DacCntl] 0x31, [GenTestCntl] 0x34, [ConfigCntl] 0x37, [ConfigChipId] 0x38, [ConfigStat0] 0x39, [ConfigStat1] 0x25, /* rsc: was 0x3A, but that's not what the LT manual says */ [ConfigStat2] 0x26, [DpBkgdClr] 0xB0, [DpChainMsk] 0xB3, [DpFrgdClr] 0xB1, [DpMix] 0xB5, [DpPixWidth] 0xB4, [DpSrc] 0xB6, [DpWriteMsk] 0xB2, }; enum { PLLm = 0x02, PLLp = 0x06, PLLn0 = 0x07, PLLn1 = 0x08, PLLn2 = 0x09, PLLn3 = 0x0A, PLLx = 0x0B, /* external divisor (Rage) */ Npll = 32, Ntv = 1, /* actually 256, but not used */ }; typedef struct Mach64xx Mach64xx; struct Mach64xx { ulong io; Pcidev* pci; int bigmem; int lcdon; int lcdpanelid; ulong reg[Nreg]; ulong lcd[Nlcd]; ulong tv[Ntv]; uchar pll[Npll]; ulong (*ior32)(Mach64xx*, int); void (*iow32)(Mach64xx*, int, ulong); }; static ulong portior32(Mach64xx* mp, int r) { if((ioregs[r] & IOREG) == 0) return ~0; return inportl(((ioregs[r] & ~IOREG)<<2)+mp->io); } static void portiow32(Mach64xx* mp, int r, ulong l) { if((ioregs[r] & IOREG) == 0) return; outportl(((ioregs[r] & ~IOREG)<<2)+mp->io, l); } static ulong pciior32(Mach64xx* mp, int r) { return inportl((pciregs[r]<<2)+mp->io); } static void pciiow32(Mach64xx* mp, int r, ulong l) { outportl((pciregs[r]<<2)+mp->io, l); } static uchar pllr(Mach64xx* mp, int r) { int io; if(mp->ior32 == portior32) io = ((ioregs[ClockCntl]&~IOREG)<<2)+mp->io; else io = (pciregs[ClockCntl]<<2)+mp->io; outportb(io+1, r<<2); return inportb(io+2); } static void pllw(Mach64xx* mp, int r, uchar b) { int io; if(mp->ior32 == portior32) io = ((ioregs[ClockCntl]&~IOREG)<<2)+mp->io; else io = (pciregs[ClockCntl]<<2)+mp->io; outportb(io+1, (r<<2)|0x02); outportb(io+2, b); } static ulong lcdr32(Mach64xx *mp, ulong r) { ulong or; or = mp->ior32(mp, LcdIndex); mp->iow32(mp, LcdIndex, (or&~0x0F) | (r&0x0F)); return mp->ior32(mp, LcdData); } static void lcdw32(Mach64xx *mp, ulong r, ulong v) { ulong or; or = mp->ior32(mp, LcdIndex); mp->iow32(mp, LcdIndex, (or&~0x0F) | (r&0x0F)); mp->iow32(mp, LcdData, v); } static ulong tvr32(Mach64xx *mp, ulong r) { outportb(mp->io+(TvIndex<<2), r&0x0F); return inportl(mp->io+(TvData<<2)); } static void tvw32(Mach64xx *mp, ulong r, ulong v) { outportb(mp->io+(TvIndex<<2), r&0x0F); outportl(mp->io+(TvData<<2), v); } static int smallmem[] = { 512*1024, 1024*1024, 2*1024*1024, 4*1024*1024, 6*1024*1024, 8*1024*1024, 12*1024*1024, 16*1024*1024, }; static int bigmem[] = { 512*1024, 2*512*1024, 3*512*1024, 4*512*1024, 5*512*1024, 6*512*1024, 7*512*1024, 8*512*1024, 5*1024*1024, 6*1024*1024, 7*1024*1024, 8*1024*1024, 10*1024*1024, 12*1024*1024, 14*1024*1024, 16*1024*1024, }; static void snarf(Vga* vga, Ctlr* ctlr) { Mach64xx *mp; int i; ulong v; if(vga->private == nil){ vga->private = alloc(sizeof(Mach64xx)); mp = vga->private; mp->io = 0x2EC; mp->ior32 = portior32; mp->iow32 = portiow32; mp->pci = pcimatch(0, 0x1002, 0); if (mp->pci) { if(v = mp->pci->mem[1].bar & ~0x3) { mp->io = v; mp->ior32 = pciior32; mp->iow32 = pciiow32; } } } mp = vga->private; for(i = 0; i < Nreg; i++) mp->reg[i] = mp->ior32(mp, i); for(i = 0; i < Npll; i++) mp->pll[i] = pllr(mp, i); switch(mp->reg[ConfigChipId] & 0xFFFF){ default: mp->lcdpanelid = 0; break; case ('L'<<8)|'B': /* 4C42: Rage LTPro AGP */ case ('L'<<8)|'I': /* 4C49: Rage 3D LTPro */ case ('L'<<8)|'M': /* 4C4D: Rage Mobility */ case ('L'<<8)|'P': /* 4C50: Rage 3D LTPro */ for(i = 0; i < Nlcd; i++) mp->lcd[i] = lcdr32(mp, i); if(mp->lcd[LCD_GenCtrl] & 0x02) mp->lcdon = 1; mp->lcdpanelid = ((mp->reg[ConfigStat2]>>14) & 0x1F); break; } /* * Check which memory size map we are using. */ mp->bigmem = 0; switch(mp->reg[ConfigChipId] & 0xFFFF){ case ('G'<<8)|'B': /* 4742: 264GT PRO */ case ('G'<<8)|'D': /* 4744: 264GT PRO */ case ('G'<<8)|'I': /* 4749: 264GT PRO */ case ('G'<<8)|'M': /* 474D: Rage XL */ case ('G'<<8)|'P': /* 4750: 264GT PRO */ case ('G'<<8)|'Q': /* 4751: 264GT PRO */ case ('G'<<8)|'R': /* 4752: */ case ('G'<<8)|'U': /* 4755: 264GT DVD */ case ('G'<<8)|'V': /* 4756: Rage2C */ case ('G'<<8)|'Z': /* 475A: Rage2C */ case ('V'<<8)|'U': /* 5655: 264VT3 */ case ('V'<<8)|'V': /* 5656: 264VT4 */ case ('L'<<8)|'B': /* 4C42: Rage LTPro AGP */ case ('L'<<8)|'I': /* 4C49: Rage 3D LTPro */ case ('L'<<8)|'M': /* 4C4D: Rage Mobility */ case ('L'<<8)|'P': /* 4C50: Rage 3D LTPro */ mp->bigmem = 1; break; case ('G'<<8)|'T': /* 4754: 264GT[B] */ case ('V'<<8)|'T': /* 5654: 264VT/GT/VTB */ /* * Only the VTB and GTB use the new memory encoding, * and they are identified by a nonzero ChipVersion, * apparently. */ if((mp->reg[ConfigChipId] >> 24) & 0x7) mp->bigmem = 1; break; } /* * Memory size and aperture. It's recommended * to use an 8Mb aperture on a 16Mb boundary. */ if(mp->bigmem) vga->vmz = bigmem[mp->reg[MemCntl] & 0x0F]; else vga->vmz = smallmem[mp->reg[MemCntl] & 0x07]; vga->vma = 16*1024*1024; switch(mp->reg[ConfigCntl]&0x3){ case 0: vga->apz = 16*1024*1024; /* empirical -rsc */ break; case 1: vga->apz = 4*1024*1024; break; case 2: vga->apz = 8*1024*1024; break; case 3: vga->apz = 2*1024*1024; /* empirical: mach64GX -rsc */ break; } ctlr->flag |= Fsnarf; } static void options(Vga*, Ctlr* ctlr) { ctlr->flag |= Hlinear|Foptions; } static void clock(Vga* vga, Ctlr* ctlr) { int clk, m, n, p; double f, q; Mach64xx *mp; mp = vga->private; /* * Don't compute clock timings for LCD panels. * Just use what's already there. We can't just use * the frequency in the vgadb for this because * the frequency being programmed into the PLLs * is not the frequency being used to compute the DSP * settings. The DSP-relevant frequency is the one * we keep in /lib/vgadb. */ if(mp->lcdon){ clk = mp->reg[ClockCntl] & 0x03; n = mp->pll[7+clk]; p = (mp->pll[6]>>(clk*2)) & 0x03; p |= (mp->pll[11]>>(2+clk)) & 0x04; switch(p){ case 0: case 1: case 2: case 3: p = 1<<p; break; case 4+0: p = 3; break; case 4+2: p = 6; break; case 4+3: p = 12; break; default: case 4+1: p = -1; break; } m = mp->pll[PLLm]; f = (2.0*RefFreq*n)/(m*p) + 0.5; vga->m[0] = m; vga->p[0] = p; vga->n[0] = n; vga->f[0] = f; return; } if(vga->f[0] == 0) vga->f[0] = vga->mode->frequency; f = vga->f[0]; /* * To generate a specific output frequency, the reference (m), * feedback (n), and post dividers (p) must be loaded with the * appropriate divide-down ratios. In the following r is the * XTALIN frequency (usually RefFreq) and t is the target frequency * (vga->f). * * Use the maximum reference divider left by the BIOS for now, * otherwise MCLK might be a concern. It can be calculated as * follows: * Upper Limit of PLL Lock Range * Minimum PLLREFCLK = ----------------------------- * (2*255) * * XTALIN * m = Floor[-----------------] * Minimum PLLREFCLK * * For an upper limit of 135MHz and XTALIN of 14.318MHz m * would be 54. */ m = mp->pll[PLLm]; vga->m[0] = m; /* * The post divider may be 1, 2, 4 or 8 and is determined by * calculating * t*m * q = ----- * (2*r) * and using the result to look-up p. */ q = (f*m)/(2*RefFreq); if(ctlr->flag&Uenhanced){ if(q > 255 || q < 10.6666666667) error("%s: vclk %lud out of range\n", ctlr->name, vga->f[0]); if(q > 127.5) p = 1; else if(q > 85) p = 2; else if(q > 63.75) p = 3; else if(q > 42.5) p = 4; else if(q > 31.875) p = 6; else if(q > 21.25) p = 8; else p = 12; }else{ if(q > 255 || q < 16) error("%s: vclk %lud out of range\n", ctlr->name, vga->f[0]); if(q >= 127.5) p = 1; else if(q >= 63.5) p = 2; else if(q >= 31.5) p = 4; else p = 8; } vga->p[0] = p; /* * The feedback divider should be kept in the range 0x80 to 0xFF * and is found from * n = q*p * rounded to the nearest whole number. */ vga->n[0] = (q*p)+0.5; } typedef struct Meminfo Meminfo; struct Meminfo { int latency; int latch; int trp; /* filled in from card */ int trcd; /* filled in from card */ int tcrd; /* filled in from card */ int tras; /* filled in from card */ }; enum { Mdram, Medo, Msdram, Mwram, }; /* * The manuals and documentation are silent on which settings * to use for Mwdram, or how to tell which to use. */ static Meminfo meminfo[] = { [Mdram] { 1, 0 }, [Medo] { 1, 2 }, [Msdram] { 3, 1 }, [Mwram] { 1, 3 }, /* non TYPE_A */ }; static ushort looplatencytab[2][2] = { { 8, 6 }, /* DRAM: ≤1M, > 1M */ { 9, 8 }, /* SDRAM: ≤1M, > 1M */ }; static ushort cyclesperqwordtab[2][2] = { { 3, 2 }, /* DRAM: ≤1M, > 1M */ { 2, 1 }, /* SDRAM: ≤1M, > 1M */ }; static int memtype[] = { -1, /* disable memory access */ Mdram, /* basic DRAM */ Medo, /* EDO */ Medo, /* hyper page DRAM or EDO */ Msdram, /* SDRAM */ Msdram, /* SGRAM */ Mwram, Mwram }; /* * Calculate various memory parameters so that the card * fetches the right bytes at the right time. I don't claim to * understand the actual calculations very well. * * This is remarkably useful on laptops, since knowledge of * x lets us find the frequency that the screen is really running * at, which is not necessarily in the VCLKs. */ static void setdsp(Vga* vga, Ctlr*) { Mach64xx *mp; Meminfo *mem; ushort table, memclk, memtyp; int i, prec, xprec, fprec; ulong t; double pw, x, fifosz, fifoon, fifooff; ushort dspon, dspoff; int afifosz, lat, ncycle, pfc, rcc; mp = vga->private; /* * Get video ram configuration from BIOS and chip */ table = *(ushort*)readbios(sizeof table, 0xc0048); trace("rom table offset %uX\n", table); table = *(ushort*)readbios(sizeof table, 0xc0000+table+16); trace("freq table offset %uX\n", table); memclk = *(ushort*)readbios(sizeof memclk, 0xc0000+table+18); trace("memclk %ud\n", memclk); memtyp = memtype[mp->reg[ConfigStat0]&07]; mem = &meminfo[memtyp]; /* * First we need to calculate x, the number of * XCLKs that one QWORD occupies in the display FIFO. * * For some reason, x gets stretched out if LCD stretching * is turned on. */ x = ((double)memclk*640000.0) / ((double)vga->mode->frequency * (double)vga->mode->z); if(mp->lcd[LCD_HorzStretch] & (1<<31)) x *= 4096.0 / (double)(mp->lcd[LCD_HorzStretch] & 0xFFFF); trace("memclk %d... x %f...", memclk, x); /* * We have 14 bits to specify x in. Decide where to * put the decimal (err, binary) point by counting how * many significant bits are in the integer portion of x. */ t = x; for(i=31; i>=0; i--) if(t & (1<<i)) break; xprec = i+1; trace("t %lud... xprec %d...", t, xprec); /* * The maximum FIFO size is the number of XCLKs per QWORD * multiplied by 32, for some reason. We have 11 bits to * specify fifosz. */ fifosz = x * 32.0; trace("fifosz %f...", fifosz); t = fifosz; for(i=31; i>=0; i--) if(t & (1<<i)) break; fprec = i+1; trace("fprec %d...", fprec); /* * Precision is specified as 3 less than the number of bits * in the integer part of x, and 5 less than the number of bits * in the integer part of fifosz. * * It is bounded by zero and seven. */ prec = (xprec-3 > fprec-5) ? xprec-3 : fprec-5; if(prec < 0) prec = 0; if(prec > 7) prec = 7; xprec = prec+3; fprec = prec+5; trace("prec %d...", prec); /* * Actual fifo size */ afifosz = (1<<fprec) / x; if(afifosz > 32) afifosz = 32; fifooff = ceil(x*(afifosz-1)); /* * I am suspicious of this table, lifted from ATI docs, * because it doesn't agree with the Windows drivers. * We always get 0x0A for lat+2 while Windows uses 0x08. */ lat = looplatencytab[memtyp > 1][vga->vmz > 1*1024*1024]; trace("afifosz %d...fifooff %f...", afifosz, fifooff); /* * Page fault clock */ t = mp->reg[MemCntl]; mem->trp = (t>>8)&3; /* RAS precharge time */ mem->trcd = (t>>10)&3; /* RAS to CAS delay */ mem->tcrd = (t>>12)&1; /* CAS to RAS delay */ mem->tras = (t>>16)&7; /* RAS low minimum pulse width */ pfc = mem->trp + 1 + mem->trcd + 1 + mem->tcrd; trace("pfc %d...", pfc); /* * Maximum random access cycle clock. */ ncycle = cyclesperqwordtab[memtyp > 1][vga->vmz > 1*1024*1024]; rcc = mem->trp + 1 + mem->tras + 1; if(rcc < pfc+ncycle) rcc = pfc+ncycle; trace("rcc %d...", rcc); fifoon = (rcc > floor(x)) ? rcc : floor(x); fifoon += (3.0 * rcc) - 1 + pfc + ncycle; trace("fifoon %f...\n", fifoon); /* * Now finally put the bits together. * x is stored in a 14 bit field with xprec bits of integer. */ pw = x * (1<<(14-xprec)); mp->reg[DspConfig] = (ulong)pw | (((lat+2)&0xF)<<16) | ((prec&7)<<20); /* * These are stored in an 11 bit field with fprec bits of integer. */ dspon = (ushort)fifoon << (11-fprec); dspoff = (ushort)fifooff << (11-fprec); mp->reg[DspOnOff] = ((dspon&0x7ff) << 16) | (dspoff&0x7ff); } static void init(Vga* vga, Ctlr* ctlr) { Mode *mode; Mach64xx *mp; int p, x, y; mode = vga->mode; if((mode->x > 640 || mode->y > 480) && mode->z == 1) error("%s: no support for 1-bit mode other than 640x480x1\n", ctlr->name); mp = vga->private; if(mode->z > 8 && mp->pci == nil) error("%s: no support for >8-bit color without PCI\n", ctlr->name); /* * Check for Rage chip */ switch (mp->reg[ConfigChipId]&0xffff) { case ('G'<<8)|'B': /* 4742: 264GT PRO */ case ('G'<<8)|'D': /* 4744: 264GT PRO */ case ('G'<<8)|'I': /* 4749: 264GT PRO */ case ('G'<<8)|'M': /* 474D: Rage XL */ case ('G'<<8)|'P': /* 4750: 264GT PRO */ case ('G'<<8)|'Q': /* 4751: 264GT PRO */ case ('G'<<8)|'R': /* 4752: */ case ('G'<<8)|'U': /* 4755: 264GT DVD */ case ('G'<<8)|'V': /* 4756: Rage2C */ case ('G'<<8)|'Z': /* 475A: Rage2C */ case ('V'<<8)|'U': /* 5655: 264VT3 */ case ('V'<<8)|'V': /* 5656: 264VT4 */ case ('G'<<8)|'T': /* 4754: 264GT[B] */ case ('V'<<8)|'T': /* 5654: 264VT/GT/VTB */ case ('L'<<8)|'B': /* 4C42: Rage LTPro AGP */ case ('L'<<8)|'I': /* 4C49: 264LT PRO */ case ('L'<<8)|'M': /* 4C4D: Rage Mobility */ case ('L'<<8)|'P': /* 4C50: 264LT PRO */ ctlr->flag |= Uenhanced; break; } /* * Always use VCLK2. */ clock(vga, ctlr); mp->pll[PLLn2] = vga->n[0]; mp->pll[PLLp] &= ~(0x03<<(2*2)); switch(vga->p[0]){ case 1: case 3: p = 0; break; case 2: p = 1; break; case 4: case 6: p = 2; break; case 8: case 12: p = 3; break; default: p = 3; break; } mp->pll[PLLp] |= p<<(2*2); if ((1<<p) != vga->p[0]) mp->pll[PLLx] |= 1<<(4+2); else mp->pll[PLLx] &= ~(1<<(4+2)); mp->reg[ClockCntl] = 2; mp->reg[ConfigCntl] = 0; mp->reg[CrtcGenCntl] = 0x02000000|(mp->reg[CrtcGenCntl] & ~0x01400700); switch(mode->z){ default: case 1: mp->reg[CrtcGenCntl] |= 0x00000100; mp->reg[DpPixWidth] = 0x00000000; break; case 8: mp->reg[CrtcGenCntl] |= 0x01000200; mp->reg[DpPixWidth] = 0x00020202; break; case 15: mp->reg[CrtcGenCntl] |= 0x01000300; mp->reg[DpPixWidth] = 0x00030303; break; case 16: mp->reg[CrtcGenCntl] |= 0x01000400; mp->reg[DpPixWidth] = 0x00040404; break; case 24: mp->reg[CrtcGenCntl] |= 0x01000500; mp->reg[DpPixWidth] = 0x00050505; break; case 32: mp->reg[CrtcGenCntl] |= 0x01000600; mp->reg[DpPixWidth] = 0x00060606; break; } mp->reg[HTotalDisp] = (((mode->x>>3)-1)<<16)|((mode->ht>>3)-1); mp->reg[HSyncStrtWid] = (((mode->ehs - mode->shs)>>3)<<16) |((mode->shs>>3)-1); if(mode->hsync == '-') mp->reg[HSyncStrtWid] |= 0x00200000; mp->reg[VTotalDisp] = ((mode->y-1)<<16)|(mode->vt-1); mp->reg[VSyncStrtWid] = ((mode->vre - mode->vrs)<<16)|(mode->vrs-1); if(mode->vsync == '-') mp->reg[VSyncStrtWid] |= 0x00200000; mp->reg[IntCntl] = 0; /* * This used to set it to (mode->x/(8*2))<<22 for depths < 8, * but from the manual that seems wrong to me. -rsc */ mp->reg[OffPitch] = (vga->virtx/8)<<22; mp->reg[OvrClr] = Pblack; if(vga->linear && mode->z != 1) ctlr->flag |= Ulinear; /* * Heuristic fiddling on LT PRO. * Do this before setdsp so the stretching is right. */ if(mp->lcdon){ /* use non-shadowed registers */ mp->lcd[LCD_GenCtrl] &= ~0x00000404; mp->lcd[LCD_ConfigPanel] |= 0x00004000; mp->lcd[LCD_VertStretch] = 0; y = ((mp->lcd[LCD_ExtVertStretch]>>11) & 0x7FF)+1; if(mode->y < y){ x = (mode->y*1024)/y; mp->lcd[LCD_VertStretch] = 0xC0000000|x; } mp->lcd[LCD_ExtVertStretch] &= ~0x00400400; /* * The x value doesn't seem to be available on all * chips so intuit it from the y value which seems to * be reliable. */ mp->lcd[LCD_HorzStretch] &= ~0xC00000FF; x = (mp->lcd[LCD_HorzStretch]>>20) & 0xFF; if(x == 0){ switch(y){ default: break; case 480: x = 640; break; case 600: x = 800; break; case 768: x = 1024; break; case 1024: x = 1280; break; } } else x = (x+1)*8; if(mode->x < x){ x = (mode->x*4096)/x; mp->lcd[LCD_HorzStretch] |= 0xC0000000|x; } } if(ctlr->flag&Uenhanced) setdsp(vga, ctlr); ctlr->flag |= Finit; } static void load(Vga* vga, Ctlr* ctlr) { Mach64xx *mp; int i; mp = vga->private; /* * Unlock the CRTC and LCD registers. */ mp->iow32(mp, CrtcGenCntl, mp->ior32(mp, CrtcGenCntl)&~0x00400000); if(mp->lcdon) lcdw32(mp, LCD_GenCtrl, mp->lcd[LCD_GenCtrl]|0x80000000); /* * Always use an aperture on a 16Mb boundary. */ if(ctlr->flag & Ulinear) mp->reg[ConfigCntl] = ((vga->vmb/(4*1024*1024))<<4)|0x02; mp->iow32(mp, ConfigCntl, mp->reg[ConfigCntl]); mp->iow32(mp, GenTestCntl, 0); mp->iow32(mp, GenTestCntl, 0x100); if((ctlr->flag&Uenhanced) == 0) mp->iow32(mp, MemCntl, mp->reg[MemCntl] & ~0x70000); mp->iow32(mp, BusCntl, mp->reg[BusCntl]); mp->iow32(mp, HTotalDisp, mp->reg[HTotalDisp]); mp->iow32(mp, HSyncStrtWid, mp->reg[HSyncStrtWid]); mp->iow32(mp, VTotalDisp, mp->reg[VTotalDisp]); mp->iow32(mp, VSyncStrtWid, mp->reg[VSyncStrtWid]); mp->iow32(mp, IntCntl, mp->reg[IntCntl]); mp->iow32(mp, OffPitch, mp->reg[OffPitch]); if(mp->lcdon){ for(i=0; i<Nlcd; i++) lcdw32(mp, i, mp->lcd[i]); } mp->iow32(mp, GenTestCntl, mp->reg[GenTestCntl]); mp->iow32(mp, ConfigCntl, mp->reg[ConfigCntl]); mp->iow32(mp, CrtcGenCntl, mp->reg[CrtcGenCntl]); mp->iow32(mp, OvrClr, mp->reg[OvrClr]); mp->iow32(mp, OvrWidLR, mp->reg[OvrWidLR]); mp->iow32(mp, OvrWidTB, mp->reg[OvrWidTB]); if(ctlr->flag&Uenhanced){ mp->iow32(mp, DacRegs, mp->reg[DacRegs]); mp->iow32(mp, DacCntl, mp->reg[DacCntl]); mp->iow32(mp, CrtcGenCntl, mp->reg[CrtcGenCntl]&~0x02000000); mp->iow32(mp, DspOnOff, mp->reg[DspOnOff]); mp->iow32(mp, DspConfig, mp->reg[DspConfig]); mp->iow32(mp, CrtcGenCntl, mp->reg[CrtcGenCntl]); pllw(mp, PLLx, mp->pll[PLLx]); } pllw(mp, PLLn2, mp->pll[PLLn2]); pllw(mp, PLLp, mp->pll[PLLp]); pllw(mp, PLLn3, mp->pll[PLLn3]); mp->iow32(mp, ClockCntl, mp->reg[ClockCntl]); mp->iow32(mp, ClockCntl, 0x40|mp->reg[ClockCntl]); mp->iow32(mp, DpPixWidth, mp->reg[DpPixWidth]); if(vga->mode->z > 8){ int sh, i; /* * We need to initialize the palette, since the DACs use it * in true color modes. First see if the card supports an * 8-bit DAC. */ mp->iow32(mp, DacCntl, mp->reg[DacCntl] | 0x100); if(mp->ior32(mp, DacCntl)&0x100){ /* card appears to support it */ vgactlw("palettedepth", "8"); mp->reg[DacCntl] |= 0x100; } if(mp->reg[DacCntl] & 0x100) sh = 0; /* 8-bit DAC */ else sh = 2; /* 6-bit DAC */ for(i=0; i<256; i++) setpalette(i, i>>sh, i>>sh, i>>sh); } ctlr->flag |= Fload; } static void pixelclock(Vga* vga, Ctlr* ctlr) { Mach64xx *mp; ushort table, s; int memclk, ref_freq, ref_divider, min_freq, max_freq; int feedback, nmult, pd, post, value; int clock; /* * Find the pixel clock from the BIOS and current * settings. Lifted from the ATI-supplied example code. * The clocks stored in the BIOS table are in kHz/10. * * This is the clock LCDs use in vgadb to set the DSP * values. */ mp = vga->private; /* * GetPLLInfo() */ table = *(ushort*)readbios(sizeof table, 0xc0048); trace("rom table offset %uX\n", table); table = *(ushort*)readbios(sizeof table, 0xc0000+table+16); trace("freq table offset %uX\n", table); s = *(ushort*)readbios(sizeof s, 0xc0000+table+18); memclk = s*10000; trace("memclk %ud\n", memclk); s = *(ushort*)readbios(sizeof s, 0xc0000+table+8); ref_freq = s*10000; trace("ref_freq %ud\n", ref_freq); s = *(ushort*)readbios(sizeof s, 0xc0000+table+10); ref_divider = s; trace("ref_divider %ud\n", ref_divider); s = *(ushort*)readbios(sizeof s, 0xc0000+table+2); min_freq = s*10000; trace("min_freq %ud\n", min_freq); s = *(ushort*)readbios(sizeof s, 0xc0000+table+4); max_freq = s*10000; trace("max_freq %ud\n", max_freq); /* * GetDivider() */ pd = mp->pll[PLLp] & 0x03; value = (mp->pll[PLLx] & 0x10)>>2; trace("pd %uX value %uX (|%d)\n", pd, value, value|pd); value |= pd; post = 0; switch(value){ case 0: post = 1; break; case 1: post = 2; break; case 2: post = 4; break; case 3: post = 8; break; case 4: post = 3; break; case 5: post = 0; break; case 6: post = 6; break; case 7: post = 12; break; } trace("post = %d\n", post); feedback = mp->pll[PLLn0]; if(mp->pll[PLLx] & 0x08) nmult = 4; else nmult = 2; clock = (ref_freq/10000)*nmult*feedback; clock /= ref_divider*post; clock *= 10000; Bprint(&stdout, "%s pixel clock = %ud\n", ctlr->name, clock); } static void dumpmach64bios(Mach64xx*); static void dump(Vga* vga, Ctlr* ctlr) { Mach64xx *mp; int i, m, n, p; double f; static int first = 1; if((mp = vga->private) == 0) return; Bprint(&stdout, "%s pci %p io %lux %s\n", ctlr->name, mp->pci, mp->io, mp->ior32 == pciior32 ? "pciregs" : "ioregs"); if(mp->pci) Bprint(&stdout, "%s ccru %ux\n", ctlr->name, mp->pci->ccru); for(i = 0; i < Nreg; i++) Bprint(&stdout, "%s %-*s%.8luX\n", ctlr->name, 20, iorname[i], mp->reg[i]); printitem(ctlr->name, "PLL"); for(i = 0; i < Npll; i++) printreg(mp->pll[i]); Bprint(&stdout, "\n"); switch(mp->reg[ConfigChipId] & 0xFFFF){ default: break; case ('L'<<8)|'B': /* 4C42: Rage LTPro AGP */ case ('L'<<8)|'I': /* 4C49: Rage 3D LTPro */ case ('L'<<8)|'M': /* 4C4D: Rage Mobility */ case ('L'<<8)|'P': /* 4C50: Rage 3D LTPro */ for(i = 0; i < Nlcd; i++) Bprint(&stdout, "%s %-*s%.8luX\n", ctlr->name, 20, lcdname[i], mp->lcd[i]); break; } /* * (2*r*n) * f = ------- * (m*p) */ m = mp->pll[2]; for(i = 0; i < 4; i++){ n = mp->pll[7+i]; p = (mp->pll[6]>>(i*2)) & 0x03; p |= (mp->pll[11]>>(2+i)) & 0x04; switch(p){ case 0: case 1: case 2: case 3: p = 1<<p; break; case 4+0: p = 3; break; case 4+2: p = 6; break; case 4+3: p = 12; break; default: case 4+1: p = -1; break; } if(m*p == 0) Bprint(&stdout, "unknown VCLK%d\n", i); else { f = (2.0*RefFreq*n)/(m*p) + 0.5; Bprint(&stdout, "%s VCLK%d\t%ud\n", ctlr->name, i, (int)f); } } pixelclock(vga, ctlr); if(first) { first = 0; dumpmach64bios(mp); } } enum { ClockFixed=0, ClockIcs2595, ClockStg1703, ClockCh8398, ClockInternal, ClockAtt20c408, ClockIbmrgb514 }; /* * mostly derived from the xfree86 probe routines. */ static void dumpmach64bios(Mach64xx *mp) { int i, romtable, clocktable, freqtable, lcdtable, lcdpanel; uchar bios[0x10000]; memmove(bios, readbios(sizeof bios, 0xC0000), sizeof bios); /* find magic string */ for(i=0; i<1024; i++) if(strncmp((char*)bios+i, " 761295520", 10) == 0) break; if(i==1024) { Bprint(&stdout, "no ATI bios found\n"); return; } /* this is horribly endian dependent. sorry. */ romtable = *(ushort*)(bios+0x48); if(romtable+0x12 > sizeof(bios)) { Bprint(&stdout, "couldn't find ATI rom table\n"); return; } clocktable = *(ushort*)(bios+romtable+0x10); if(clocktable+0x0C > sizeof(bios)) { Bprint(&stdout, "couldn't find ATI clock table\n"); return; } freqtable = *(ushort*)(bios+clocktable-2); if(freqtable+0x20 > sizeof(bios)) { Bprint(&stdout, "couldn't find ATI frequency table\n"); return; } Bprint(&stdout, "ATI BIOS rom 0x%x freq 0x%x clock 0x%x\n", romtable, freqtable, clocktable); Bprint(&stdout, "clocks:"); for(i=0; i<16; i++) Bprint(&stdout, " %d", *(ushort*)(bios+freqtable+2*i)); Bprint(&stdout, "\n"); Bprint(&stdout, "programmable clock: %d\n", bios[clocktable]); Bprint(&stdout, "clock to program: %d\n", bios[clocktable+6]); if(*(ushort*)(bios+clocktable+8) != 1430) { Bprint(&stdout, "reference numerator: %d\n", *(ushort*)(bios+clocktable+8)*10); Bprint(&stdout, "reference denominator: 1\n"); } else { Bprint(&stdout, "default reference numerator: 157500\n"); Bprint(&stdout, "default reference denominator: 11\n"); } switch(bios[clocktable]) { case ClockIcs2595: Bprint(&stdout, "ics2595\n"); Bprint(&stdout, "reference divider: %d\n", *(ushort*)(bios+clocktable+0x0A)); break; case ClockStg1703: Bprint(&stdout, "stg1703\n"); break; case ClockCh8398: Bprint(&stdout, "ch8398\n"); break; case ClockInternal: Bprint(&stdout, "internal clock\n"); Bprint(&stdout, "reference divider in plls\n"); break; case ClockAtt20c408: Bprint(&stdout, "att 20c408\n"); break; case ClockIbmrgb514: Bprint(&stdout, "ibm rgb514\n"); Bprint(&stdout, "clock to program = 7\n"); break; default: Bprint(&stdout, "unknown clock\n"); break; } USED(mp); if(1 || mp->lcdpanelid) { lcdtable = *(ushort*)(bios+0x78); if(lcdtable+5 > sizeof bios || lcdtable+bios[lcdtable+5] > sizeof bios) { Bprint(&stdout, "can't find lcd bios table\n"); goto NoLcd; } lcdpanel = *(ushort*)(bios+lcdtable+0x0A); if(lcdpanel+0x1D > sizeof bios /*|| bios[lcdpanel] != mp->lcdpanelid*/) { Bprint(&stdout, "can't find lcd bios table0\n"); goto NoLcd; } Bprint(&stdout, "panelid %d x %d y %d\n", bios[lcdpanel], *(ushort*)(bios+lcdpanel+0x19), *(ushort*)(bios+lcdpanel+0x1B)); } NoLcd:; } Ctlr mach64xx = { "mach64xx", /* name */ snarf, /* snarf */ 0, /* options */ init, /* init */ load, /* load */ dump, /* dump */ }; Ctlr mach64xxhwgc = { "mach64xxhwgc", /* name */ 0, /* snarf */ 0, /* options */ 0, /* init */ 0, /* load */ 0, /* dump */ };
Java
/*! * address.js - Description * Copyright © 2012 by Ingenesis Limited. All rights reserved. * Licensed under the GPLv3 {@see license.txt} */ (function($) { jQuery.fn.upstate = function () { if ( typeof regions === 'undefined' ) return; $(this).change(function (e,init) { var $this = $(this), prefix = $this.attr('id').split('-')[0], country = $this.val(), state = $this.parents().find('#' + prefix + '-state'), menu = $this.parents().find('#' + prefix + '-state-menu'), options = '<option value=""></option>'; if (menu.length == 0) return true; if (menu.hasClass('hidden')) menu.removeClass('hidden').hide(); if (regions[country] || (init && menu.find('option').length > 1)) { state.setDisabled(true).addClass('_important').hide(); if (regions[country]) { $.each(regions[country], function (value,label) { options += '<option value="'+value+'">'+label+'</option>'; }); if (!init) menu.empty().append(options).setDisabled(false).show().focus(); if (menu.hasClass('auto-required')) menu.addClass('required'); } else { if (menu.hasClass('auto-required')) menu.removeClass('required'); } menu.setDisabled(false).show(); $('label[for='+state.attr('id')+']').attr('for',menu.attr('id')); } else { menu.empty().setDisabled(true).hide(); state.setDisabled(false).show().removeClass('_important'); $('label[for='+menu.attr('id')+']').attr('for',state.attr('id')); if (!init) state.val('').focus(); } }).trigger('change',[true]); return $(this); }; })(jQuery); jQuery(document).ready(function($) { var sameaddr = $('.sameaddress'), shipFields = $('#shipping-address-fields'), billFields = $('#billing-address-fields'), keepLastValue = function () { // Save the current value of the field $(this).attr('data-last', $(this).val()); }; // Handle changes to the firstname and lastname fields $('#firstname,#lastname').each(keepLastValue).change(function () { var namefield = $(this); // Reference to the modified field lastfirstname = $('#firstname').attr('data-last'), lastlastname = $('#lastname').attr('data-last'), firstlast = ( ( $('#firstname').val() ).trim() + " " + ( $('#lastname').val() ).trim() ).trim(); namefield.val( (namefield.val()).trim() ); // Update the billing name and shipping name $('#billing-name,#shipping-name').each(function() { var value = $(this).val(); if ( value.trim().length == 0 ) { // Empty billing or shipping name $('#billing-name,#shipping-name').val(firstlast); } else if ( '' != value && ( $('#firstname').val() == value || $('#lastname').val() == value ) ) { // Only one name entered (so far), add the other name $(this).val(firstlast); } else if ( 'firstname' == namefield.attr('id') && value.indexOf(lastlastname) != -1 ) { // firstname changed & last lastname matched $(this).val( value.replace(lastfirstname, namefield.val()).trim() ); } else if ( 'lastname' == namefield.attr('id') && value.indexOf(lastfirstname) != -1 ) { // lastname changed & last firstname matched $(this).val( value.replace(lastlastname, namefield.val()).trim() ); } }); }).change(keepLastValue); // Update state/province $('#billing-country,#shipping-country').upstate(); // Toggle same shipping address sameaddr.change(function (e,init) { var refocus = false, bc = $('#billing-country'), sc = $('#shipping-country'), prime = 'billing' == sameaddr.val() ? shipFields : billFields, alt = 'shipping' == sameaddr.val() ? shipFields : billFields; if (sameaddr.is(':checked')) { prime.removeClass('half'); alt.hide().find('.required').setDisabled(true); } else { prime.addClass('half'); alt.show().find('.disabled:not(._important)').setDisabled(false); if (!init) refocus = true; } if (bc.is(':visible')) bc.trigger('change.localemenu',[init]); if (sc.is(':visible')) sc.trigger('change.localemenu',[init]); if (refocus) alt.find('input:first').focus(); }).trigger('change',[true]) .click(function () { $(this).change(); }); // For IE compatibility });
Java
/* soundeffects.c * An example on how to use libmikmod to play sound effects. * * (C) 2004, Raphael Assenat (raph@raphnet.net) * * This example is distributed in the hope that it will be useful, * but WITHOUT ANY WARRENTY; without event the implied warrenty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * */ #include <stdlib.h> #include <stdio.h> #include <mikmod.h> #if !defined _WIN32 && !defined _WIN64 #include <unistd.h> /* for usleep() */ #define MikMod_Sleep(ns) usleep(ns) #else #define MikMod_Sleep(ns) Sleep(ns / 1000) #endif SAMPLE *Load(const char *fn) { char *data_buf; long data_len; FILE *fptr; /* open the file */ fptr = fopen(fn, "rb"); if (fptr == NULL) { perror("fopen"); return 0; } /* calculate the file size */ fseek(fptr, 0, SEEK_END); data_len = ftell(fptr); fseek(fptr, 0, SEEK_SET); /* allocate a buffer and load the file into it */ data_buf = (char *) malloc(data_len); if (data_buf == NULL) { perror("malloc"); fclose(fptr); return 0; } if (fread(data_buf, data_len, 1, fptr) != 1) { perror("fread"); fclose(fptr); free(data_buf); return 0; } fclose(fptr); return Sample_LoadMem(data_buf, data_len); } int main(void) { /* sound effects */ SAMPLE *sfx1, *sfx2; /* voices */ int v1, v2; int i; /* register all the drivers */ MikMod_RegisterAllDrivers(); /* initialize the library */ md_mode |= DMODE_SOFT_SNDFX; if (MikMod_Init("")) { fprintf(stderr, "Could not initialize sound, reason: %s\n", MikMod_strerror(MikMod_errno)); return 1; } /* load samples */ sfx1 = Load("first.wav"); if (!sfx1) { MikMod_Exit(); fprintf(stderr, "Could not load the first sound, reason: %s\n", MikMod_strerror(MikMod_errno)); return 1; } sfx2 = Load("second.wav"); if (!sfx2) { Sample_Free(sfx1); MikMod_Exit(); fprintf(stderr, "Could not load the second sound, reason: %s\n", MikMod_strerror(MikMod_errno)); return 1; } /* reserve 2 voices for sound effects */ MikMod_SetNumVoices(-1, 2); /* get ready to play */ MikMod_EnableOutput(); /* play first sample */ v1 = Sample_Play(sfx1, 0, 0); do { MikMod_Update(); MikMod_Sleep(100000); } while (!Voice_Stopped(v1)); for (i = 0; i < 10; i++) { MikMod_Update(); MikMod_Sleep(100000); } /* half a second later, play second sample */ v2 = Sample_Play(sfx2, 0, 0); do { MikMod_Update(); MikMod_Sleep(100000); } while (!Voice_Stopped(v2)); for (i = 0; i < 10; i++) { MikMod_Update(); MikMod_Sleep(100000); } MikMod_DisableOutput(); Sample_Free(sfx2); Sample_Free(sfx1); MikMod_Exit(); return 0; }
Java
/*++ drivers/i2c/busses/wmt-i2c-bus-3.c Copyright (c) 2013 WonderMedia Technologies, Inc. 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, see <http://www.gnu.org/licenses/>. WonderMedia Technologies, Inc. 10F, 529, Chung-Cheng Road, Hsin-Tien, Taipei 231, R.O.C. --*/ /* Include your headers here*/ #include <linux/kernel.h> #include <linux/module.h> #include <linux/i2c.h> /* #include <linux/i2c-id.h> */ #include <linux/init.h> #include <linux/time.h> #include <linux/sched.h> #include <linux/delay.h> #include <linux/errno.h> #include <linux/interrupt.h> #include <mach/hardware.h> #include <asm/irq.h> #include <mach/irqs.h> #include <mach/wmt-i2c-bus.h> #include <linux/slab.h> #include <linux/pm.h> #include <linux/syscore_ops.h> #ifdef __KERNEL__ #ifdef DEBUG #define DPRINTK printk #else #define DPRINTK(x...) #endif #else #define DPRINTK printf #endif #define MAX_BUS_READY_CNT 50 /* jiffy*/ #define MAX_TX_TIMEOUT 500 /* ms*/ #define MAX_RX_TIMEOUT 500 /* ms*/ #define CTRL_GPIO GPIO_CTRL_GP23_I2C3_BYTE_ADDR #define PU_EN_GPIO PULL_EN_GP23_I2C3_BYTE_ADDR #define PU_CTRL_GPIO PULL_CTRL_GP23_I2C3_BYTE_ADDR #define USE_UBOOT_PARA struct wmt_i2c_s { struct i2c_regs_s *regs; int irq_no ; enum i2c_mode_e i2c_mode ; int volatile isr_nack ; int volatile isr_byte_end ; int volatile isr_timeout ; int volatile isr_int_pending ; }; static int i2c_wmt_wait_bus_not_busy(void); extern int wmt_getsyspara(char *varname, unsigned char *varval, int *varlen); static unsigned int speed_mode = 1; static unsigned int is_master = 1;/*master:1, slave:0*/ unsigned int wmt_i2c3_is_master = 1; unsigned int wmt_i2c3_speed_mode = 0; static unsigned int wmt_i2c3_power_state = 0;/*0:power on, 1:suspend, 2:shutdown*/ EXPORT_SYMBOL(wmt_i2c3_is_master); /**/ /* variable*/ /*-------------------------------------------------*/ static volatile struct wmt_i2c_s i2c ; DECLARE_WAIT_QUEUE_HEAD(i2c3_wait); /* spinlock_t i2c3_wmt_irqlock = SPIN_LOCK_UNLOCKED; */ static DEFINE_SPINLOCK(i2c3_wmt_irqlock); static struct list_head wmt_i2c_fifohead; /* static spinlock_t i2c_fifolock = SPIN_LOCK_UNLOCKED; */ static DEFINE_SPINLOCK(i2c_fifolock); static int i2c_wmt_read_buf( unsigned int slave_addr, char *buf, unsigned int length, int restart, int last ); static int i2c_wmt_write_buf( unsigned int slave_addr, char *buf, unsigned int length, int restart, int last ); static void i2c_wmt_set_mode(enum i2c_mode_e mode /*!<; //[IN] mode */) { if (is_master == 0) return; i2c.i2c_mode = mode ; if (i2c.i2c_mode == I2C_STANDARD_MODE) { DPRINTK("I2C: set standard mode \n"); i2c.regs->tr_reg = I2C_TR_STD_VALUE ; /* 0x8041*/ } else if (i2c.i2c_mode == I2C_FAST_MODE) { DPRINTK("I2C: set fast mode \n"); i2c.regs->tr_reg = I2C_TR_FAST_VALUE ; /* 0x8011*/ } } static int i2c_send_request( struct i2c_msg *msg, int msg_num, int non_block, void (*callback)(void *data), void *data ) { struct wmt_i2cbusfifo *i2c_fifo_head; struct i2c_msg *pmsg = NULL; int ret = 0; int restart = 0; int last = 0; unsigned long flags; int slave_addr = msg[0].addr; if (slave_addr == WMT_I2C_API_I2C_ADDR) return ret ; if (wmt_i2c3_power_state == 2) { printk("I2C3 has been shutdown\n"); return -EIO; } i2c.isr_nack = 0 ; i2c.isr_byte_end = 0 ; i2c.isr_timeout = 0 ; i2c.isr_int_pending = 0; i2c_fifo_head = kzalloc(sizeof(struct wmt_i2cbusfifo), GFP_ATOMIC); INIT_LIST_HEAD(&i2c_fifo_head->busfifohead); pmsg = &msg[0]; i2c_fifo_head->msg = pmsg; i2c_fifo_head->msg_num = msg_num; spin_lock_irqsave(&i2c_fifolock, flags); if (list_empty(&wmt_i2c_fifohead)) { i2c_wmt_wait_bus_not_busy(); pmsg = &msg[0]; i2c_fifo_head->xfer_length = 1; i2c_fifo_head->xfer_msgnum = 0; i2c_fifo_head->restart = 0; i2c_fifo_head->non_block = non_block; if (non_block == 1) { i2c_fifo_head->callback = callback; i2c_fifo_head->data = data; } else { i2c_fifo_head->callback = 0; i2c_fifo_head->data = 0; } list_add_tail(&i2c_fifo_head->busfifohead, &wmt_i2c_fifohead); if (pmsg->flags & I2C_M_RD) { i2c_fifo_head->xfer_length = 1; ret = i2c_wmt_read_buf(pmsg->addr, pmsg->buf, pmsg->len, restart, last); } else { i2c_fifo_head->xfer_length = 1; if (pmsg->flags & I2C_M_NOSTART) i2c_fifo_head->restart = 1; else i2c_fifo_head->restart = 0; ret = i2c_wmt_write_buf(pmsg->addr, pmsg->buf, pmsg->len, restart, last); } } else { i2c_fifo_head->xfer_length = 0; i2c_fifo_head->xfer_msgnum = 0; i2c_fifo_head->restart = 0; i2c_fifo_head->non_block = non_block; if (non_block == 1) { i2c_fifo_head->callback = callback; i2c_fifo_head->data = data; } else { i2c_fifo_head->callback = 0; i2c_fifo_head->data = 0; } list_add_tail(&i2c_fifo_head->busfifohead, &wmt_i2c_fifohead); } spin_unlock_irqrestore(&i2c_fifolock, flags); if (non_block == 0) { wait_event(i2c3_wait, i2c.isr_int_pending); ret = msg_num; if (i2c.isr_nack == 1) { DPRINTK("i2c_err : write NACK error (rx) \n\r") ; ret = -EIO ; } if (i2c.isr_timeout == 1) { DPRINTK("i2c_err : write SCL timeout error (rx)\n\r") ; ret = -ETIMEDOUT ; } } return ret; } static int i2c_wmt_read_buf( unsigned int slave_addr, char *buf, unsigned int length, int restart, int last ) { unsigned short tcr_value; int ret = 0; DPRINTK("[%s]:length = %d , slave_addr = %x\n", __func__, length , slave_addr); if (length <=0) return -1; i2c.isr_nack = 0 ; i2c.isr_byte_end = 0 ; i2c.isr_timeout = 0 ; /*i2c.isr_int_pending = 0;*/ i2c.regs->cr_reg &= ~(I2C_CR_TX_END); /*clear Tx end*/ i2c.regs->cr_reg &= ~(I2C_CR_TX_NEXT_NO_ACK); /*clear NEXT_NO_ACK*/ if (length <=0) return -1; i2c.isr_nack = 0 ; i2c.isr_byte_end = 0 ; i2c.isr_timeout = 0 ; /*i2c.isr_int_pending = 0;*/ tcr_value = 0 ; if (i2c.i2c_mode == I2C_STANDARD_MODE) tcr_value = (unsigned short)(I2C_TCR_STANDARD_MODE|I2C_TCR_MASTER_READ |\ (slave_addr & I2C_TCR_SLAVE_ADDR_MASK)) ; else if (i2c.i2c_mode == I2C_FAST_MODE) tcr_value = (unsigned short)(I2C_TCR_FAST_MODE|I2C_TCR_MASTER_READ |\ (slave_addr & I2C_TCR_SLAVE_ADDR_MASK)) ; if (length == 1) i2c.regs->cr_reg |= I2C_CR_TX_NEXT_NO_ACK; /*only 8-bit to read*/ i2c.regs->tcr_reg = tcr_value ; return ret; } static int i2c_wmt_write_buf( unsigned int slave_addr, char *buf, unsigned int length, int restart, int last ) { unsigned short tcr_value ; unsigned int xfer_length ; int ret = 0 ; DPRINTK("[%s]length = %d , slave_addr = %x\n", __func__, length , slave_addr); if (slave_addr == WMT_I2C_API_I2C_ADDR) return ret ; if (is_master == 0) return -ENXIO; /* special case allow length:0, for i2c_smbus_xfer*/ /**/ if (length < 0) return -1 ; xfer_length = 0 ; /* for array index and also for checking counting*/ i2c.isr_nack = 0 ; i2c.isr_byte_end = 0 ; i2c.isr_timeout = 0 ; /*i2c.isr_int_pending = 0;*/ i2c.regs->cr_reg &= ~(I2C_CR_TX_END); /*clear Tx end*/ i2c.regs->cr_reg &= ~(I2C_CR_TX_NEXT_NO_ACK); /*clear NEXT_NO_ACK*/ if (length == 0) i2c.regs->cdr_reg = 0 ; else i2c.regs->cdr_reg = (unsigned short)(buf[xfer_length] & I2C_CDR_DATA_WRITE_MASK) ; tcr_value = 0 ; if (i2c.i2c_mode == I2C_STANDARD_MODE) tcr_value = (unsigned short)(I2C_TCR_STANDARD_MODE|I2C_TCR_MASTER_WRITE |\ (slave_addr & I2C_TCR_SLAVE_ADDR_MASK)) ; else if (i2c.i2c_mode == I2C_FAST_MODE) tcr_value = (unsigned short)(I2C_TCR_FAST_MODE|I2C_TCR_MASTER_WRITE |\ (slave_addr & I2C_TCR_SLAVE_ADDR_MASK)) ; i2c.regs->tcr_reg = tcr_value ; ret = 0 ; return ret; } static int i2c_wmt_read_msg( unsigned int slave_addr, /*!<; //[IN] Salve address */ char *buf, /*!<; //[OUT] Pointer to data */ unsigned int length, /*!<; //Data length */ int restart, /*!<; //Need to restart after a complete read */ int last /*!<; //Last read */ ) { unsigned short tcr_value ; unsigned int xfer_length ; int is_timeout ; int ret = 0 ; int wait_event_result = 0 ; if (is_master == 0) return -ENXIO; if (length <= 0) return -1 ; xfer_length = 0 ; if (restart == 0) ret = i2c_wmt_wait_bus_not_busy() ; if (ret < 0) return ret ; i2c.isr_nack = 0 ; i2c.isr_byte_end = 0 ; i2c.isr_timeout = 0 ; i2c.isr_int_pending = 0; i2c.regs->cr_reg &= ~(I2C_CR_TX_END); /*clear Tx end*/ i2c.regs->cr_reg &= ~(I2C_CR_TX_NEXT_NO_ACK); /*clear NEXT_NO_ACK*/ if (restart == 0) i2c.regs->cr_reg |= (I2C_CR_CPU_RDY); /*release SCL*/ tcr_value = 0 ; if (i2c.i2c_mode == I2C_STANDARD_MODE) { tcr_value = (unsigned short)(I2C_TCR_STANDARD_MODE|I2C_TCR_MASTER_READ |\ (slave_addr & I2C_TCR_SLAVE_ADDR_MASK)) ; } else if (i2c.i2c_mode == I2C_FAST_MODE) { tcr_value = (unsigned short)(I2C_TCR_FAST_MODE|I2C_TCR_MASTER_READ |\ (slave_addr & I2C_TCR_SLAVE_ADDR_MASK)) ; } if (length == 1) i2c.regs->cr_reg |= I2C_CR_TX_NEXT_NO_ACK; /*only 8-bit to read*/ i2c.regs->tcr_reg = tcr_value ; /*repeat start case*/ if (restart == 1) i2c.regs->cr_reg |= (I2C_CR_CPU_RDY); /*release SCL*/ ret = 0 ; for (; ;) { is_timeout = 0 ; wait_event_result = wait_event_interruptible_timeout(i2c3_wait, i2c.isr_int_pending , (MAX_RX_TIMEOUT * HZ / 1000)) ; if (likely(wait_event_result > 0)) { DPRINTK("I2C: wait interrupted (rx) \n"); ret = 0 ; } else if (likely(i2c.isr_int_pending == 0)) { DPRINTK("I2C: wait timeout (rx) \n"); is_timeout = 1 ; ret = -ETIMEDOUT ; } /**/ /* fail case*/ /**/ if (i2c.isr_nack == 1) { DPRINTK("i2c_err : write NACK error (rx) \n\r") ; ret = -EIO ; break ; } if (i2c.isr_timeout == 1) { DPRINTK("i2c_err : write SCL timeout error (rx)\n\r") ; msleep(10); ret = -ETIMEDOUT ; break ; } if (is_timeout == 1) { DPRINTK("i2c_err: write software timeout error (rx) \n\r") ; ret = -ETIMEDOUT ; break ; } /**/ /* pass case*/ /**/ if (i2c.isr_byte_end == 1) { buf[xfer_length] = (i2c.regs->cdr_reg >> 8) ; ++xfer_length ; DPRINTK("i2c_test: received BYTE_END\n\r"); } i2c.isr_int_pending = 0; i2c.isr_nack = 0 ; i2c.isr_byte_end = 0 ; i2c.isr_timeout = 0 ; if (length > xfer_length) { if ((length - 1) == xfer_length) { /* next read is the last one*/ i2c.regs->cr_reg |= (I2C_CR_TX_NEXT_NO_ACK | I2C_CR_CPU_RDY); DPRINTK("i2c_test: set CPU_RDY & TX_ACK. next data is last.\r\n"); } else { i2c.regs->cr_reg |= I2C_CR_CPU_RDY ; DPRINTK("i2c_test: more data to read. only set CPU_RDY. \r\n"); } } else if (length == xfer_length) { /* end rx xfer*/ if (last == 1) { /* stop case*/ DPRINTK("i2c_test: read completed \r\n"); break ; } else { /* restart case*/ /* ??? how to handle the restart after read ?*/ DPRINTK("i2c_test: RX ReStart Case \r\n") ; break ; } } else { DPRINTK("i2c_err : read known error\n\r") ; ret = -EIO ; break ; } } DPRINTK("i2c_test: read sequence completed\n\r"); return ret ; } static int i2c_wmt_write_msg( unsigned int slave_addr, /*!<; //[IN] Salve address */ char *buf, /*!<; //[OUT] Pointer to data */ unsigned int length, /*!<; //Data length */ int restart, /*!<; //Need to restart after a complete write */ int last /*!<; //Last read */ ) { unsigned short tcr_value ; unsigned int xfer_length ; int is_timeout ; int ret = 0 ; int wait_event_result ; DPRINTK("length = %d , slave_addr = %x\n", length , slave_addr); if (slave_addr == WMT_I2C_API_I2C_ADDR) return ret ; if (is_master == 0) return -ENXIO; /* special case allow length:0, for i2c_smbus_xfer*/ /**/ if (length < 0) return -1 ; xfer_length = 0 ; /* for array index and also for checking counting*/ if (restart == 0) ret = i2c_wmt_wait_bus_not_busy() ; if (ret < 0) return ret ; i2c.isr_nack = 0 ; i2c.isr_byte_end = 0 ; i2c.isr_timeout = 0 ; i2c.isr_int_pending = 0; /**/ /* special case allow length:0, for i2c_smbus_xfer*/ /**/ if (length == 0) i2c.regs->cdr_reg = 0 ; else i2c.regs->cdr_reg = (unsigned short)(buf[xfer_length] & I2C_CDR_DATA_WRITE_MASK) ; if (restart == 0) { i2c.regs->cr_reg &= ~(I2C_CR_TX_END); /*clear Tx end*/ i2c.regs->cr_reg |= (I2C_CR_CPU_RDY); /*release SCL*/ } /**/ /* I2C: Set transfer mode [standard/fast]*/ /**/ tcr_value = 0 ; if (i2c.i2c_mode == I2C_STANDARD_MODE) tcr_value = (unsigned short)(I2C_TCR_STANDARD_MODE|I2C_TCR_MASTER_WRITE |\ (slave_addr & I2C_TCR_SLAVE_ADDR_MASK)) ; else if (i2c.i2c_mode == I2C_FAST_MODE) tcr_value = (unsigned short)(I2C_TCR_FAST_MODE|I2C_TCR_MASTER_WRITE |\ (slave_addr & I2C_TCR_SLAVE_ADDR_MASK)) ; i2c.regs->tcr_reg = tcr_value ; if (restart == 1) i2c.regs->cr_reg |= I2C_CR_CPU_RDY ; ret = 0 ; for (; ;) { is_timeout = 0 ; /**/ /* I2C: Wait for interrupt. if ( i2c.isr_int_pending == 1 ) ==> an interrupt exsits.*/ /**/ wait_event_result = wait_event_interruptible_timeout(i2c3_wait, i2c.isr_int_pending , (MAX_TX_TIMEOUT * HZ / 1000)) ; if (likely(wait_event_result > 0)) { DPRINTK("I2C: wait interrupted (tx)\n"); ret = 0 ; } else if (likely(i2c.isr_int_pending == 0)) { DPRINTK("I2C: wait timeout (tx) \n"); is_timeout = 1 ; ret = -ETIMEDOUT ; } /**/ /* fail case*/ /**/ if (i2c.isr_nack == 1) { DPRINTK("i2c_err : write NACK error (tx) \n\r") ; ret = -EIO ; break ; } if (i2c.isr_timeout == 1) { DPRINTK("i2c_err : write SCL timeout error (tx)\n\r") ; msleep(10); ret = -ETIMEDOUT ; break ; } if (is_timeout == 1) { DPRINTK("i2c_err : write software timeout error (tx)\n\r") ; ret = -ETIMEDOUT ; break ; } /**/ /* pass case*/ /**/ if (i2c.isr_byte_end == 1) { DPRINTK("i2c: isr end byte (tx)\n\r") ; ++xfer_length ; } i2c.isr_int_pending = 0 ; i2c.isr_nack = 0 ; i2c.isr_byte_end = 0 ; i2c.isr_timeout = 0 ; if ((i2c.regs->csr_reg & I2C_CSR_RCV_ACK_MASK) == I2C_CSR_RCV_NOT_ACK) { DPRINTK("i2c_err : write RCV NACK error\n\r") ; ret = -EIO ; break ; } /**/ /* special case allow length:0, for i2c_smbus_xfer*/ /**/ if (length == 0) { i2c.regs->cr_reg = (I2C_CR_TX_END|I2C_CR_CPU_RDY|I2C_CR_ENABLE) ; break ; } if (length > xfer_length) { i2c.regs->cdr_reg = (unsigned short) (buf[xfer_length] & I2C_CDR_DATA_WRITE_MASK) ; i2c.regs->cr_reg = (I2C_CR_CPU_RDY | I2C_CR_ENABLE) ; DPRINTK("i2c_test: write register data \n\r") ; } else if (length == xfer_length) { /* end tx xfer*/ if (last == 1) { /* stop case*/ i2c.regs->cr_reg = (I2C_CR_TX_END|I2C_CR_CPU_RDY|I2C_CR_ENABLE) ; DPRINTK("i2c_test: finish write \n\r") ; break ; } else { /* restart case*/ /* handle the restart for first write then the next is read*/ i2c.regs->cr_reg = (I2C_CR_ENABLE) ; DPRINTK("i2c_test: tx restart Case \n\r") ; break ; } } else { DPRINTK("i2c_err : write unknown error\n\r") ; ret = -EIO ; break ; } } ; DPRINTK("i2c_test: write sequence completed\n\r"); return ret ; } static int i2c_wmt_wait_bus_not_busy(void) { int ret ; int cnt ; ret = 0 ; cnt = 0 ; while (1) { if ((REG16_VAL(I2C3_CSR_ADDR) & I2C_STATUS_MASK) == I2C_READY) { ret = 0; break ; } cnt++ ; if (cnt > MAX_BUS_READY_CNT) { ret = (-EBUSY) ; printk("i2c_err 3: wait but not ready time-out\n\r") ; cnt = 0; break; } } return ret ; } static void i2c_wmt_reset(void) { unsigned short tmp ; if (is_master == 0) return; /**/ /* software initial*/ /**/ i2c.regs = (struct i2c_regs_s *)I2C3_BASE_ADDR ; i2c.irq_no = IRQ_I2C3 ; if (speed_mode == 0) i2c.i2c_mode = I2C_STANDARD_MODE ; else i2c.i2c_mode = I2C_FAST_MODE ; i2c.isr_nack = 0 ; i2c.isr_byte_end = 0 ; i2c.isr_timeout = 0 ; i2c.isr_int_pending = 0; /**/ /* hardware initial*/ /**/ i2c.regs->cr_reg = 0 ; i2c.regs->div_reg = APB_96M_I2C_DIV ; i2c.regs->isr_reg = I2C_ISR_ALL_WRITE_CLEAR ; /* 0x0007*/ i2c.regs->imr_reg = I2C_IMR_ALL_ENABLE ; /* 0x0007*/ i2c.regs->cr_reg = I2C_CR_ENABLE ; tmp = i2c.regs->csr_reg ; /* read clear*/ i2c.regs->isr_reg = I2C_ISR_ALL_WRITE_CLEAR ; /* 0x0007*/ if (i2c.i2c_mode == I2C_STANDARD_MODE) i2c.regs->tr_reg = I2C_TR_STD_VALUE ; /* 0x8041*/ else if (i2c.i2c_mode == I2C_FAST_MODE) i2c.regs->tr_reg = I2C_TR_FAST_VALUE ; /* 0x8011*/ DPRINTK("Resetting I2C Controller Unit\n"); return ; } static int wmt_i2c_transfer_msg(struct wmt_i2cbusfifo *fifo_head) { int xfer_length = fifo_head->xfer_length; int xfer_msgnum = fifo_head->xfer_msgnum; struct i2c_msg *pmsg = &fifo_head->msg[xfer_msgnum]; int restart = fifo_head->restart; unsigned short tcr_value; unsigned short slave_addr = pmsg->addr; int length = pmsg->len; int ret = 0; if (pmsg->flags & I2C_M_RD) { if (restart == 0) i2c_wmt_wait_bus_not_busy(); i2c.isr_nack = 0 ; i2c.isr_byte_end = 0 ; i2c.isr_timeout = 0 ; /*i2c.isr_int_pending = 0;*/ i2c.regs->cr_reg &= ~(I2C_CR_TX_END); /*clear Tx end*/ i2c.regs->cr_reg &= ~(I2C_CR_TX_NEXT_NO_ACK); /*clear NEXT_NO_ACK*/ if (restart == 0) i2c.regs->cr_reg |= (I2C_CR_CPU_RDY); /*release SCL*/ tcr_value = 0 ; if (i2c.i2c_mode == I2C_STANDARD_MODE) { tcr_value = (unsigned short)(I2C_TCR_STANDARD_MODE|I2C_TCR_MASTER_READ |\ (slave_addr & I2C_TCR_SLAVE_ADDR_MASK)) ; } else if (i2c.i2c_mode == I2C_FAST_MODE) { tcr_value = (unsigned short)(I2C_TCR_FAST_MODE|I2C_TCR_MASTER_READ |\ (slave_addr & I2C_TCR_SLAVE_ADDR_MASK)) ; } if (length == 1) i2c.regs->cr_reg |= I2C_CR_TX_NEXT_NO_ACK; /*only 8-bit to read*/ i2c.regs->tcr_reg = tcr_value ; /*repeat start case*/ if (restart == 1) i2c.regs->cr_reg |= (I2C_CR_CPU_RDY); /*release SCL*/ } else { if (restart == 0) i2c_wmt_wait_bus_not_busy(); i2c.isr_nack = 0 ; i2c.isr_byte_end = 0 ; i2c.isr_timeout = 0 ; /*i2c.isr_int_pending = 0;*/ /**/ /* special case allow length:0, for i2c_smbus_xfer*/ /**/ if (length == 0) i2c.regs->cdr_reg = 0 ; else i2c.regs->cdr_reg = (unsigned short)(pmsg->buf[xfer_length] & I2C_CDR_DATA_WRITE_MASK) ; if (restart == 0) { i2c.regs->cr_reg &= ~(I2C_CR_TX_END); /*clear Tx end*/ i2c.regs->cr_reg |= (I2C_CR_CPU_RDY); /*release SCL*/ } /**/ /* I2C: Set transfer mode [standard/fast]*/ /**/ tcr_value = 0 ; if (i2c.i2c_mode == I2C_STANDARD_MODE) tcr_value = (unsigned short)(I2C_TCR_STANDARD_MODE|I2C_TCR_MASTER_WRITE |\ (slave_addr & I2C_TCR_SLAVE_ADDR_MASK)) ; else if (i2c.i2c_mode == I2C_FAST_MODE) tcr_value = (unsigned short)(I2C_TCR_FAST_MODE|I2C_TCR_MASTER_WRITE |\ (slave_addr & I2C_TCR_SLAVE_ADDR_MASK)) ; i2c.regs->tcr_reg = tcr_value ; if (restart == 1) i2c.regs->cr_reg |= I2C_CR_CPU_RDY ; } return ret; } static irqreturn_t i2c_wmt_handler( int this_irq, /*!<; //[IN] IRQ number */ void *dev_id /*!<; //[IN] Pointer to device ID */ ) { int wakeup ; unsigned short isr_status ; unsigned short tmp ; unsigned long flags; struct wmt_i2cbusfifo *fifo_head; int xfer_length = 0; int xfer_msgnum = 0; struct i2c_msg *pmsg; volatile unsigned short csr_reg; spin_lock_irqsave(&i2c3_wmt_irqlock, flags); isr_status = i2c.regs->isr_reg ; csr_reg = i2c.regs->csr_reg; wakeup = 0 ; fifo_head = list_first_entry(&wmt_i2c_fifohead, struct wmt_i2cbusfifo, busfifohead); if (isr_status & I2C_ISR_NACK_ADDR) { DPRINTK("[%s]:i2c NACK\n", __func__); /*spin_lock(&i2c_fifolock);*/ list_del(&fifo_head->busfifohead);/*del request*/ kfree(fifo_head); /*spin_unlock(&i2c_fifolock);*/ xfer_length = 0; i2c.regs->isr_reg = I2C_ISR_NACK_ADDR_WRITE_CLEAR ; tmp = i2c.regs->csr_reg ; /* read clear*/ i2c.isr_nack = 1 ; wakeup = 1 ; } if ((isr_status & I2C_ISR_BYTE_END && ((csr_reg & I2C_CSR_RCV_ACK_MASK) == I2C_CSR_RCV_NOT_ACK))) { /* printk("data rcv nack\n"); */ list_del(&fifo_head->busfifohead);/*del request*/ kfree(fifo_head); xfer_length = 0; i2c.regs->isr_reg = I2C_ISR_BYTE_END_WRITE_CLEAR ; i2c.isr_nack = 1 ; wakeup = 1 ; } else if (isr_status & I2C_ISR_BYTE_END) { i2c.regs->isr_reg = I2C_ISR_BYTE_END_WRITE_CLEAR ; i2c.isr_byte_end = 1 ; xfer_length = fifo_head->xfer_length; xfer_msgnum = fifo_head->xfer_msgnum; pmsg = &fifo_head->msg[xfer_msgnum]; /*read case*/ if (pmsg->flags & I2C_M_RD) { pmsg->buf[xfer_length - 1] = (i2c.regs->cdr_reg >> 8) ; /*the last data in current msg?*/ if (xfer_length == pmsg->len - 1) { /*last msg of the current request?*/ /*spin_lock(&i2c_fifolock);*/ if (pmsg->flags & I2C_M_NOSTART) { ++fifo_head->xfer_length; fifo_head->restart = 1; /* ++fifo_head->xfer_msgnum; */ i2c.regs->cr_reg |= I2C_CR_CPU_RDY; } else { ++fifo_head->xfer_length; fifo_head->restart = 0; /* ++fifo_head->xfer_msgnum; */ i2c.regs->cr_reg |= (I2C_CR_CPU_RDY | I2C_CR_TX_NEXT_NO_ACK); } /*spin_unlock(&i2c_fifolock);*/ } else if (xfer_length == pmsg->len) {/*next msg*/ if (xfer_msgnum < fifo_head->msg_num - 1) { /*spin_lock(&i2c_fifolock);*/ fifo_head->xfer_length = 0; ++fifo_head->xfer_msgnum; wmt_i2c_transfer_msg(fifo_head); ++fifo_head->xfer_length; /*spin_unlock(&i2c_fifolock);*/ } else { /*data of this msg has been transfered*/ /*spin_lock(&i2c_fifolock);*/ list_del(&fifo_head->busfifohead);/*del request*/ /*next request exist?*/ if (list_empty(&wmt_i2c_fifohead)) {/*no more reqeust*/ /*kfree(fifo_head);*/ if (fifo_head->non_block == 0) { wakeup = 1; } else { fifo_head->callback(fifo_head->data); } kfree(fifo_head); } else { /*more request*/ if (fifo_head->non_block == 0) { wakeup = 1; } else { fifo_head->callback(fifo_head->data); } kfree(fifo_head); fifo_head = list_first_entry(&wmt_i2c_fifohead, struct wmt_i2cbusfifo, busfifohead); /* if (fifo_head->non_block == 0) wakeup = 1; */ fifo_head->xfer_length = 0; wmt_i2c_transfer_msg(fifo_head); ++fifo_head->xfer_length; /* if (fifo_head->non_block == 0) { printk("2 : non callback\n"); wakeup = 1; } else { printk("2 :callback\n"); fifo_head->callback(fifo_head->data); } */ } /*spin_unlock(&i2c_fifolock);*/ } } else {/*next data*/ /*spin_lock(&i2c_fifolock);*/ ++fifo_head->xfer_length; /*spin_unlock(&i2c_fifolock);*/ i2c.regs->cr_reg |= I2C_CR_CPU_RDY; } } else { /*write case*/ /*the last data in current msg?*/ if (xfer_length == pmsg->len) { /*last msg of the current request?*/ if (xfer_msgnum < fifo_head->msg_num - 1) { /*spin_lock(&i2c_fifolock);*/ if (pmsg->flags & I2C_M_NOSTART) { ++fifo_head->xfer_length; fifo_head->restart = 1; } else { ++fifo_head->xfer_length; fifo_head->restart = 0; i2c.regs->cr_reg &= ~(I2C_CR_TX_END); udelay(2); i2c.regs->cr_reg |= (I2C_CR_TX_END); } /*access next msg*/ fifo_head->xfer_length = 0; ++fifo_head->xfer_msgnum; wmt_i2c_transfer_msg(fifo_head); ++fifo_head->xfer_length; /*spin_unlock(&i2c_fifolock);*/ } else {/*this request finish*/ /*spin_lock(&i2c_fifolock);*/ /*next request exist?*/ list_del(&fifo_head->busfifohead);/*del request*/ if (list_empty(&wmt_i2c_fifohead)) { /*kfree(fifo_head);*/ /* if (fifo_head->non_block == 0) wakeup = 1; */ i2c.regs->cr_reg &= ~(I2C_CR_TX_END); udelay(2); i2c.regs->cr_reg |= (I2C_CR_TX_END); if (fifo_head->non_block == 0) { wakeup = 1; } else { fifo_head->callback(fifo_head->data); } kfree(fifo_head); } else { i2c.regs->cr_reg &= ~(I2C_CR_TX_END); udelay(2); i2c.regs->cr_reg |= (I2C_CR_TX_END); if (fifo_head->non_block == 0) { wakeup = 1; } else { fifo_head->callback(fifo_head->data); } kfree(fifo_head); fifo_head = list_first_entry(&wmt_i2c_fifohead, struct wmt_i2cbusfifo, busfifohead); /* if (fifo_head->non_block == 0) wakeup = 1; */ /*next msg*/ fifo_head->xfer_length = 0; ++fifo_head->xfer_msgnum; wmt_i2c_transfer_msg(fifo_head); ++fifo_head->xfer_length; /* if (fifo_head->non_block == 0) { printk("4:non callback\n"); wakeup = 1; } else { printk("4:callback\n"); fifo_head->callback(fifo_head->data); } */ } /*spin_unlock(&i2c_fifolock);*/ } } else {/*next data*/ i2c.regs->cdr_reg = (unsigned short) (pmsg->buf[fifo_head->xfer_length] & I2C_CDR_DATA_WRITE_MASK); /*spin_lock(&i2c_fifolock);*/ ++fifo_head->xfer_length; /*spin_unlock(&i2c_fifolock);*/ i2c.regs->cr_reg |= (I2C_CR_CPU_RDY | I2C_CR_ENABLE); } } } if (isr_status & I2C_ISR_SCL_TIME_OUT) { DPRINTK("[%s]SCL timeout\n", __func__); #if 0 i2c.regs->cr_reg |= BIT7;/*reset status*/ /*spin_lock(&i2c_fifolock);*/ list_del(&fifo_head->busfifohead);/*del request*/ /*spin_unlock(&i2c_fifolock);*/ xfer_length = 0; i2c.regs->isr_reg = I2C_ISR_SCL_TIME_OUT_WRITE_CLEAR | I2C_ISR_BYTE_END_WRITE_CLEAR; i2c.isr_timeout = 1 ; wakeup = 1; #endif i2c.regs->isr_reg = I2C_ISR_SCL_TIME_OUT_WRITE_CLEAR ; } if (wakeup) { /*spin_lock_irqsave(&i2c_wmt_irqlock, flags);*/ i2c.isr_int_pending = 1; /*spin_unlock_irqrestore(&i2c_wmt_irqlock, flags);*/ wake_up(&i2c3_wait); } else DPRINTK("i2c_err : unknown I2C ISR Handle 0x%4.4X" , isr_status) ; spin_unlock_irqrestore(&i2c3_wmt_irqlock, flags); return IRQ_HANDLED; } static int i2c_wmt_resource_init(void) { if (is_master == 0) return 0; if (request_irq(i2c.irq_no , &i2c_wmt_handler, IRQF_DISABLED, "i2c", 0) < 0) { DPRINTK(KERN_INFO "I2C: Failed to register I2C irq %i\n", i2c.irq_no); return -ENODEV; } return 0; } static void i2c_wmt_resource_release(void) { if (is_master == 0) return; free_irq(i2c.irq_no, 0); } static struct i2c_algo_wmt_data i2c_wmt_data = { write_msg: i2c_wmt_write_msg, read_msg: i2c_wmt_read_msg, send_request: i2c_send_request, wait_bus_not_busy: i2c_wmt_wait_bus_not_busy, reset: i2c_wmt_reset, set_mode: i2c_wmt_set_mode, udelay: I2C_ALGO_UDELAY, timeout: I2C_ALGO_TIMEOUT, }; static struct i2c_adapter i2c_wmt_ops = { .owner = THIS_MODULE, /* .id = I2C_ALGO_WMT, */ .algo_data = &i2c_wmt_data, .name = "wmt_i2c3_adapter", .retries = I2C_ADAPTER_RETRIES, .nr = 3, }; #ifdef CONFIG_PM static struct i2c_regs_s wmt_i2c_reg ; static void i2c_shutdown(void) { printk("i2c3 shutdown\n"); wmt_i2c3_power_state = 2; while (!list_empty(&wmt_i2c_fifohead)) msleep(1); while (1) {/*wait busy clear*/ if ((REG16_VAL(I2C3_CSR_ADDR) & I2C_STATUS_MASK) == I2C_READY) break ; msleep(1); } return; } static int i2c_suspend(void) { printk("i2c3 suspend\n"); wmt_i2c_reg.imr_reg = i2c.regs->imr_reg; wmt_i2c_reg.tr_reg = i2c.regs->tr_reg; wmt_i2c_reg.div_reg = i2c.regs->div_reg; return 0; } static void i2c_resume(void) { printk("i2c3 resume\n"); GPIO_CTRL_GP23_I2C3_BYTE_VAL &= ~(BIT0 | BIT1); PULL_EN_GP23_I2C3_BYTE_VAL |= (BIT0 | BIT1); PULL_CTRL_GP23_I2C3_BYTE_VAL |= (BIT0 | BIT1); PIN_SHARING_SEL_4BYTE_VAL &= ~BIT28; auto_pll_divisor(DEV_I2C3, CLK_ENABLE, 0, 0); auto_pll_divisor(DEV_I2C3, SET_DIV, 2, 20);/*20M Hz*/ i2c.regs->cr_reg = 0 ; i2c.regs->div_reg = wmt_i2c_reg.div_reg; i2c.regs->imr_reg = wmt_i2c_reg.imr_reg; i2c.regs->tr_reg = wmt_i2c_reg.tr_reg ; i2c.regs->cr_reg = 0x001 ; } #else #define i2c_suspend NULL #define i2c_resume NULL #define i2c_shutdown NULL #endif extern int wmt_i2c_add_bus(struct i2c_adapter *); extern int wmt_i2c_del_bus(struct i2c_adapter *); #ifdef CONFIG_PM static struct syscore_ops wmt_i2c_syscore_ops = { .suspend = i2c_suspend, .resume = i2c_resume, .shutdown = i2c_shutdown, }; #endif static int __init i2c_adap_wmt_init(void) { unsigned short tmp ; char varname[] = "wmt.i2c.param"; #ifdef CONFIG_I2C_SLAVE_WMT char varname1[] = "wmt.bus.i2c.slave_port"; #endif unsigned char buf[80]; int ret; unsigned int port_num; int idx = 0; int varlen = 80; unsigned int pllb_freq = 0; unsigned int tr_val = 0; #ifdef CONFIG_I2C_SLAVE_WMT #ifdef USE_UBOOT_PARA ret = wmt_getsyspara(varname1, buf, &varlen); #else ret = 1; #endif is_master = 1; if (ret == 0) { ret = sscanf(buf, "%x", &port_num); while (ret) { if (port_num != 0) is_master = 1; else { is_master = 0; break; } idx += ret; ret = sscanf(buf + idx, ",%x", &port_num); } } else is_master = 1; #endif wmt_i2c3_is_master = is_master; if (is_master == 1) { #ifdef USE_UBOOT_PARA ret = wmt_getsyspara(varname, buf, &varlen); #else ret = 1; #endif if (ret == 0) { ret = sscanf(buf, "%x:%x", &port_num, &speed_mode); idx += 3; while (ret) { if (ret < 2) speed_mode = 0; else { if (port_num != 3) speed_mode = 0; else break; } ret = sscanf(buf + idx, ",%x:%x", &port_num, &speed_mode); idx += 4; } } if (speed_mode > 1) speed_mode = 0; wmt_i2c3_speed_mode = speed_mode; /**/ /* software initial*/ /**/ i2c.regs = (struct i2c_regs_s *)I2C3_BASE_ADDR ; i2c.irq_no = IRQ_I2C3 ; printk("PORT 3 speed_mode = %d\n", speed_mode); if (speed_mode == 0) i2c.i2c_mode = I2C_STANDARD_MODE ; else if (speed_mode == 1) i2c.i2c_mode = I2C_FAST_MODE ; i2c.isr_nack = 0 ; i2c.isr_byte_end = 0 ; i2c.isr_timeout = 0 ; i2c.isr_int_pending = 0; /**/ /* hardware initial*/ /**/ auto_pll_divisor(DEV_I2C3, CLK_ENABLE, 0, 0); pllb_freq = auto_pll_divisor(DEV_I2C3, SET_DIV, 2, 20);/*20M Hz*/ printk("pllb_freq = %d\n", pllb_freq); if ((pllb_freq%(1000*2*100)) != 0) tr_val = pllb_freq/(1000*2*100) + 1; else tr_val = pllb_freq/(1000*2*100); *(volatile unsigned char *)CTRL_GPIO &= ~(BIT0 | BIT1); *(volatile unsigned char *)PU_EN_GPIO |= (BIT0 | BIT1); *(volatile unsigned char *)PU_CTRL_GPIO |= (BIT0 | BIT1); PIN_SHARING_SEL_4BYTE_VAL &= ~BIT28; i2c.regs->cr_reg = 0 ; i2c.regs->div_reg = APB_96M_I2C_DIV ; i2c.regs->isr_reg = I2C_ISR_ALL_WRITE_CLEAR ; /* 0x0007*/ i2c.regs->imr_reg = I2C_IMR_ALL_ENABLE ; /* 0x0007*/ i2c.regs->cr_reg = I2C_CR_ENABLE ; tmp = i2c.regs->csr_reg ; /* read clear*/ i2c.regs->isr_reg = I2C_ISR_ALL_WRITE_CLEAR ; /* 0x0007*/ if (i2c.i2c_mode == I2C_STANDARD_MODE) i2c.regs->tr_reg = 0xff00|tr_val; else if (i2c.i2c_mode == I2C_FAST_MODE) { tr_val /= 4; i2c.regs->tr_reg = 0xff00|tr_val ; } } if (i2c_wmt_resource_init() == 0) { if (wmt_i2c_add_bus(&i2c_wmt_ops) < 0) { i2c_wmt_resource_release(); printk(KERN_INFO "i2c: Failed to add bus\n"); return -ENODEV; } } else return -ENODEV; INIT_LIST_HEAD(&wmt_i2c_fifohead); #ifdef CONFIG_PM register_syscore_ops(&wmt_i2c_syscore_ops); #endif printk(KERN_INFO "i2c: successfully added bus\n"); #ifdef I2C_REG_TEST printk("i2c.regs->cr_reg= 0x%08x\n\r", i2c.regs->cr_reg); printk("i2c.regs->tcr_reg= 0x%08x\n\r", i2c.regs->tcr_reg); printk("i2c.regs->csr_reg= 0x%08x\n\r", i2c.regs->csr_reg); printk("i2c.regs->isr_reg= 0x%08x\n\r", i2c.regs->isr_reg); printk("i2c.regs->imr_reg= 0x%08x\n\r", i2c.regs->imr_reg); printk("i2c.regs->cdr_reg= 0x%08x\n\r", i2c.regs->cdr_reg); printk("i2c.regs->tr_reg= 0x%08x\n\r", i2c.regs->tr_reg); printk("i2c.regs->div_reg= 0x%08x\n\r", i2c.regs->div_reg); #endif return 0; } subsys_initcall(i2c_adap_wmt_init); static void i2c_adap_wmt_exit(void) { wmt_i2c_del_bus(&i2c_wmt_ops); i2c_wmt_resource_release(); printk(KERN_INFO "i2c: successfully removed bus\n"); } MODULE_AUTHOR("WonderMedia Technologies, Inc."); MODULE_DESCRIPTION("WMT I2C Adapter Driver"); MODULE_LICENSE("GPL"); module_exit(i2c_adap_wmt_exit);
Java
/* BlueZ - Bluetooth protocol stack for Linux Copyright (C) 2010 Nokia Corporation Copyright (c) 2011-2012 The Linux Foundation. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) AND AUTHOR(S) BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ALL LIABILITY, INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS, RELATING TO USE OF THIS SOFTWARE IS DISCLAIMED. */ /* Bluetooth HCI Management interface */ #include <linux/uaccess.h> #include <linux/interrupt.h> #include <linux/module.h> #include <asm/unaligned.h> #include <net/bluetooth/bluetooth.h> #include <net/bluetooth/hci_core.h> #include <net/bluetooth/l2cap.h> #include <net/bluetooth/mgmt.h> #include <net/bluetooth/smp.h> #define MGMT_VERSION 0 #define MGMT_REVISION 1 #define SCAN_IDLE 0x00 #define SCAN_LE 0x01 #define SCAN_BR 0x02 struct pending_cmd { struct list_head list; __u16 opcode; int index; void *param; struct sock *sk; void *user_data; }; struct mgmt_pending_free_work { struct work_struct work; struct sock *sk; }; LIST_HEAD(cmd_list); static int cmd_status(struct sock *sk, u16 index, u16 cmd, u8 status) { struct sk_buff *skb; struct mgmt_hdr *hdr; struct mgmt_ev_cmd_status *ev; BT_DBG("sock %p, index %u, cmd %u, status %u", sk, index, cmd, status); skb = alloc_skb(sizeof(*hdr) + sizeof(*ev), GFP_ATOMIC); if (!skb) return -ENOMEM; hdr = (void *) skb_put(skb, sizeof(*hdr)); hdr->opcode = cpu_to_le16(MGMT_EV_CMD_STATUS); hdr->index = cpu_to_le16(index); hdr->len = cpu_to_le16(sizeof(*ev)); ev = (void *) skb_put(skb, sizeof(*ev)); ev->status = status; put_unaligned_le16(cmd, &ev->opcode); if (sock_queue_rcv_skb(sk, skb) < 0) kfree_skb(skb); return 0; } static int cmd_complete(struct sock *sk, u16 index, u16 cmd, void *rp, size_t rp_len) { struct sk_buff *skb; struct mgmt_hdr *hdr; struct mgmt_ev_cmd_complete *ev; BT_DBG("sock %p", sk); skb = alloc_skb(sizeof(*hdr) + sizeof(*ev) + rp_len, GFP_ATOMIC); if (!skb) return -ENOMEM; hdr = (void *) skb_put(skb, sizeof(*hdr)); hdr->opcode = cpu_to_le16(MGMT_EV_CMD_COMPLETE); hdr->index = cpu_to_le16(index); hdr->len = cpu_to_le16(sizeof(*ev) + rp_len); ev = (void *) skb_put(skb, sizeof(*ev) + rp_len); put_unaligned_le16(cmd, &ev->opcode); if (rp) memcpy(ev->data, rp, rp_len); if (sock_queue_rcv_skb(sk, skb) < 0) kfree_skb(skb); return 0; } static int read_version(struct sock *sk) { struct mgmt_rp_read_version rp; BT_DBG("sock %p", sk); rp.version = MGMT_VERSION; put_unaligned_le16(MGMT_REVISION, &rp.revision); return cmd_complete(sk, MGMT_INDEX_NONE, MGMT_OP_READ_VERSION, &rp, sizeof(rp)); } static int read_index_list(struct sock *sk) { struct mgmt_rp_read_index_list *rp; struct list_head *p; size_t rp_len; u16 count; int i, err; BT_DBG("sock %p", sk); read_lock(&hci_dev_list_lock); count = 0; list_for_each(p, &hci_dev_list) { struct hci_dev *d = list_entry(p, struct hci_dev, list); if (d->dev_type != HCI_BREDR) continue; count++; } rp_len = sizeof(*rp) + (2 * count); rp = kmalloc(rp_len, GFP_ATOMIC); if (!rp) { read_unlock(&hci_dev_list_lock); return -ENOMEM; } put_unaligned_le16(0, &rp->num_controllers); i = 0; list_for_each(p, &hci_dev_list) { struct hci_dev *d = list_entry(p, struct hci_dev, list); hci_del_off_timer(d); if (d->dev_type != HCI_BREDR) continue; set_bit(HCI_MGMT, &d->flags); if (test_bit(HCI_SETUP, &d->flags)) continue; put_unaligned_le16(d->id, &rp->index[i++]); put_unaligned_le16((u16)i, &rp->num_controllers); BT_DBG("Added hci%u", d->id); } read_unlock(&hci_dev_list_lock); err = cmd_complete(sk, MGMT_INDEX_NONE, MGMT_OP_READ_INDEX_LIST, rp, rp_len); kfree(rp); return err; } static int read_controller_info(struct sock *sk, u16 index) { struct mgmt_rp_read_info rp; struct hci_dev *hdev; BT_DBG("sock %p hci%u", sk, index); hdev = hci_dev_get(index); if (!hdev) return cmd_status(sk, index, MGMT_OP_READ_INFO, ENODEV); hci_del_off_timer(hdev); hci_dev_lock_bh(hdev); set_bit(HCI_MGMT, &hdev->flags); memset(&rp, 0, sizeof(rp)); rp.type = hdev->dev_type; rp.powered = test_bit(HCI_UP, &hdev->flags); rp.connectable = test_bit(HCI_PSCAN, &hdev->flags); rp.discoverable = test_bit(HCI_ISCAN, &hdev->flags); rp.pairable = test_bit(HCI_PSCAN, &hdev->flags); if (test_bit(HCI_AUTH, &hdev->flags)) rp.sec_mode = 3; else if (hdev->ssp_mode > 0) rp.sec_mode = 4; else rp.sec_mode = 2; bacpy(&rp.bdaddr, &hdev->bdaddr); memcpy(rp.features, hdev->features, 8); memcpy(rp.dev_class, hdev->dev_class, 3); put_unaligned_le16(hdev->manufacturer, &rp.manufacturer); rp.hci_ver = hdev->hci_ver; put_unaligned_le16(hdev->hci_rev, &rp.hci_rev); memcpy(rp.name, hdev->dev_name, sizeof(hdev->dev_name)); rp.le_white_list_size = hdev->le_white_list_size; hci_dev_unlock_bh(hdev); hci_dev_put(hdev); return cmd_complete(sk, index, MGMT_OP_READ_INFO, &rp, sizeof(rp)); } static void mgmt_pending_free_worker(struct work_struct *work) { struct mgmt_pending_free_work *free_work = container_of(work, struct mgmt_pending_free_work, work); BT_DBG("sk %p", free_work->sk); sock_put(free_work->sk); kfree(free_work); } static void mgmt_pending_free(struct pending_cmd *cmd) { struct mgmt_pending_free_work *free_work; struct sock *sk = cmd->sk; BT_DBG("opcode %d, sk %p", cmd->opcode, sk); kfree(cmd->param); kfree(cmd); free_work = kzalloc(sizeof(*free_work), GFP_ATOMIC); if (free_work) { INIT_WORK(&free_work->work, mgmt_pending_free_worker); free_work->sk = sk; if (!schedule_work(&free_work->work)) kfree(free_work); } } static struct pending_cmd *mgmt_pending_add(struct sock *sk, u16 opcode, u16 index, void *data, u16 len) { struct pending_cmd *cmd; BT_DBG("%d", opcode); cmd = kmalloc(sizeof(*cmd), GFP_ATOMIC); if (!cmd) return NULL; cmd->opcode = opcode; cmd->index = index; cmd->param = kmalloc(len, GFP_ATOMIC); if (!cmd->param) { kfree(cmd); return NULL; } if (data) memcpy(cmd->param, data, len); cmd->sk = sk; sock_hold(sk); list_add(&cmd->list, &cmd_list); return cmd; } static void mgmt_pending_foreach(u16 opcode, int index, void (*cb)(struct pending_cmd *cmd, void *data), void *data) { struct list_head *p, *n; BT_DBG(" %d", opcode); list_for_each_safe(p, n, &cmd_list) { struct pending_cmd *cmd; cmd = list_entry(p, struct pending_cmd, list); if (opcode > 0 && cmd->opcode != opcode) continue; if (index >= 0 && cmd->index != index) continue; cb(cmd, data); } } static struct pending_cmd *mgmt_pending_find(u16 opcode, int index) { struct list_head *p; BT_DBG(" %d", opcode); list_for_each(p, &cmd_list) { struct pending_cmd *cmd; cmd = list_entry(p, struct pending_cmd, list); if (cmd->opcode != opcode) continue; if (index >= 0 && cmd->index != index) continue; return cmd; } return NULL; } static void mgmt_pending_remove(struct pending_cmd *cmd) { BT_DBG(" %d", cmd->opcode); list_del(&cmd->list); mgmt_pending_free(cmd); } static int set_powered(struct sock *sk, u16 index, unsigned char *data, u16 len) { struct mgmt_mode *cp; struct hci_dev *hdev; struct pending_cmd *cmd; int err, up; cp = (void *) data; BT_DBG("request for hci%u", index); if (len != sizeof(*cp)) return cmd_status(sk, index, MGMT_OP_SET_POWERED, EINVAL); hdev = hci_dev_get(index); if (!hdev) return cmd_status(sk, index, MGMT_OP_SET_POWERED, ENODEV); hci_dev_lock_bh(hdev); up = test_bit(HCI_UP, &hdev->flags); if ((cp->val && up) || (!cp->val && !up)) { err = cmd_status(sk, index, MGMT_OP_SET_POWERED, EALREADY); goto failed; } if (mgmt_pending_find(MGMT_OP_SET_POWERED, index)) { err = cmd_status(sk, index, MGMT_OP_SET_POWERED, EBUSY); goto failed; } cmd = mgmt_pending_add(sk, MGMT_OP_SET_POWERED, index, data, len); if (!cmd) { err = -ENOMEM; goto failed; } hci_dev_unlock_bh(hdev); if (cp->val) queue_work(hdev->workqueue, &hdev->power_on); else queue_work(hdev->workqueue, &hdev->power_off); err = 0; hci_dev_put(hdev); return err; failed: hci_dev_unlock_bh(hdev); hci_dev_put(hdev); return err; } static u8 get_service_classes(struct hci_dev *hdev) { struct list_head *p; u8 val = 0; list_for_each(p, &hdev->uuids) { struct bt_uuid *uuid = list_entry(p, struct bt_uuid, list); val |= uuid->svc_hint; } return val; } static int update_class(struct hci_dev *hdev) { u8 cod[3]; int err = 0; BT_DBG("%s", hdev->name); if (test_bit(HCI_SERVICE_CACHE, &hdev->flags)) return 0; cod[0] = hdev->minor_class; cod[1] = hdev->major_class; cod[2] = get_service_classes(hdev); if (memcmp(cod, hdev->dev_class, 3) == 0) return 0; err = hci_send_cmd(hdev, HCI_OP_WRITE_CLASS_OF_DEV, sizeof(cod), cod); if (err == 0) memcpy(hdev->dev_class, cod, 3); return err; } static int set_limited_discoverable(struct sock *sk, u16 index, unsigned char *data, u16 len) { struct mgmt_mode *cp; struct hci_dev *hdev; struct pending_cmd *cmd; struct hci_cp_write_current_iac_lap dcp; int update_cod; int err = 0; /* General Inquiry LAP: 0x9E8B33, Limited Inquiry LAP: 0x9E8B00 */ u8 lap[] = { 0x33, 0x8b, 0x9e, 0x00, 0x8b, 0x9e }; cp = (void *) data; BT_DBG("hci%u discoverable: %d", index, cp->val); if (!cp || len != sizeof(*cp)) return cmd_status(sk, index, MGMT_OP_SET_LIMIT_DISCOVERABLE, EINVAL); hdev = hci_dev_get(index); if (!hdev) return cmd_status(sk, index, MGMT_OP_SET_LIMIT_DISCOVERABLE, ENODEV); hci_dev_lock_bh(hdev); if (!test_bit(HCI_UP, &hdev->flags)) { err = cmd_status(sk, index, MGMT_OP_SET_LIMIT_DISCOVERABLE, ENETDOWN); goto failed; } if (mgmt_pending_find(MGMT_OP_SET_LIMIT_DISCOVERABLE, index)) { err = cmd_status(sk, index, MGMT_OP_SET_LIMIT_DISCOVERABLE, EBUSY); goto failed; } if (cp->val == test_bit(HCI_ISCAN, &hdev->flags) && test_bit(HCI_PSCAN, &hdev->flags)) { err = cmd_status(sk, index, MGMT_OP_SET_LIMIT_DISCOVERABLE, EALREADY); goto failed; } cmd = mgmt_pending_add(sk, MGMT_OP_SET_LIMIT_DISCOVERABLE, index, data, len); if (!cmd) { err = -ENOMEM; goto failed; } memset(&dcp, 0, sizeof(dcp)); dcp.num_current_iac = cp->val ? 2 : 1; memcpy(&dcp.lap, lap, dcp.num_current_iac * 3); update_cod = 1; if (cp->val) { if (hdev->major_class & MGMT_MAJOR_CLASS_LIMITED) update_cod = 0; hdev->major_class |= MGMT_MAJOR_CLASS_LIMITED; } else { if (!(hdev->major_class & MGMT_MAJOR_CLASS_LIMITED)) update_cod = 0; hdev->major_class &= ~MGMT_MAJOR_CLASS_LIMITED; } if (update_cod) err = update_class(hdev); if (err >= 0) err = hci_send_cmd(hdev, HCI_OP_WRITE_CURRENT_IAC_LAP, sizeof(dcp), &dcp); if (err < 0) mgmt_pending_remove(cmd); failed: hci_dev_unlock_bh(hdev); hci_dev_put(hdev); return err; } static int set_discoverable(struct sock *sk, u16 index, unsigned char *data, u16 len) { struct mgmt_mode *cp; struct hci_dev *hdev; struct pending_cmd *cmd; u8 scan; int err; cp = (void *) data; BT_DBG("request for hci%u", index); if (len != sizeof(*cp)) return cmd_status(sk, index, MGMT_OP_SET_DISCOVERABLE, EINVAL); hdev = hci_dev_get(index); if (!hdev) return cmd_status(sk, index, MGMT_OP_SET_DISCOVERABLE, ENODEV); hci_dev_lock_bh(hdev); if (!test_bit(HCI_UP, &hdev->flags)) { err = cmd_status(sk, index, MGMT_OP_SET_DISCOVERABLE, ENETDOWN); goto failed; } if (mgmt_pending_find(MGMT_OP_SET_DISCOVERABLE, index) || mgmt_pending_find(MGMT_OP_SET_CONNECTABLE, index)) { err = cmd_status(sk, index, MGMT_OP_SET_DISCOVERABLE, EBUSY); goto failed; } if (cp->val == test_bit(HCI_ISCAN, &hdev->flags) && test_bit(HCI_PSCAN, &hdev->flags)) { err = cmd_status(sk, index, MGMT_OP_SET_DISCOVERABLE, EALREADY); goto failed; } cmd = mgmt_pending_add(sk, MGMT_OP_SET_DISCOVERABLE, index, data, len); if (!cmd) { err = -ENOMEM; goto failed; } scan = SCAN_PAGE; if (cp->val) scan |= SCAN_INQUIRY; err = hci_send_cmd(hdev, HCI_OP_WRITE_SCAN_ENABLE, 1, &scan); if (err < 0) mgmt_pending_remove(cmd); failed: hci_dev_unlock_bh(hdev); hci_dev_put(hdev); return err; } static int set_connectable(struct sock *sk, u16 index, unsigned char *data, u16 len) { struct mgmt_mode *cp; struct hci_dev *hdev; struct pending_cmd *cmd; u8 scan; int err; cp = (void *) data; BT_DBG("request for hci%u", index); if (len != sizeof(*cp)) return cmd_status(sk, index, MGMT_OP_SET_CONNECTABLE, EINVAL); hdev = hci_dev_get(index); if (!hdev) return cmd_status(sk, index, MGMT_OP_SET_CONNECTABLE, ENODEV); hci_dev_lock_bh(hdev); if (!test_bit(HCI_UP, &hdev->flags)) { err = cmd_status(sk, index, MGMT_OP_SET_CONNECTABLE, ENETDOWN); goto failed; } if (mgmt_pending_find(MGMT_OP_SET_DISCOVERABLE, index) || mgmt_pending_find(MGMT_OP_SET_CONNECTABLE, index)) { err = cmd_status(sk, index, MGMT_OP_SET_CONNECTABLE, EBUSY); goto failed; } if (cp->val == test_bit(HCI_PSCAN, &hdev->flags)) { err = cmd_status(sk, index, MGMT_OP_SET_CONNECTABLE, EALREADY); goto failed; } cmd = mgmt_pending_add(sk, MGMT_OP_SET_CONNECTABLE, index, data, len); if (!cmd) { err = -ENOMEM; goto failed; } if (cp->val) scan = SCAN_PAGE; else scan = 0; err = hci_send_cmd(hdev, HCI_OP_WRITE_SCAN_ENABLE, 1, &scan); if (err < 0) mgmt_pending_remove(cmd); failed: hci_dev_unlock_bh(hdev); hci_dev_put(hdev); return err; } static int mgmt_event(u16 event, u16 index, void *data, u16 data_len, struct sock *skip_sk) { struct sk_buff *skb; struct mgmt_hdr *hdr; BT_DBG("hci%d %d", index, event); skb = alloc_skb(sizeof(*hdr) + data_len, GFP_ATOMIC); if (!skb) return -ENOMEM; bt_cb(skb)->channel = HCI_CHANNEL_CONTROL; hdr = (void *) skb_put(skb, sizeof(*hdr)); hdr->opcode = cpu_to_le16(event); hdr->index = cpu_to_le16(index); hdr->len = cpu_to_le16(data_len); if (data) memcpy(skb_put(skb, data_len), data, data_len); hci_send_to_sock(NULL, skb, skip_sk); kfree_skb(skb); return 0; } static int send_mode_rsp(struct sock *sk, u16 opcode, u16 index, u8 val) { struct mgmt_mode rp; rp.val = val; return cmd_complete(sk, index, opcode, &rp, sizeof(rp)); } static int set_pairable(struct sock *sk, u16 index, unsigned char *data, u16 len) { struct mgmt_mode *cp, ev; struct hci_dev *hdev; int err; cp = (void *) data; BT_DBG("request for hci%u", index); if (len != sizeof(*cp)) return cmd_status(sk, index, MGMT_OP_SET_PAIRABLE, EINVAL); hdev = hci_dev_get(index); if (!hdev) return cmd_status(sk, index, MGMT_OP_SET_PAIRABLE, ENODEV); hci_dev_lock_bh(hdev); if (cp->val) set_bit(HCI_PAIRABLE, &hdev->flags); else clear_bit(HCI_PAIRABLE, &hdev->flags); err = send_mode_rsp(sk, MGMT_OP_SET_PAIRABLE, index, cp->val); if (err < 0) goto failed; ev.val = cp->val; err = mgmt_event(MGMT_EV_PAIRABLE, index, &ev, sizeof(ev), sk); failed: hci_dev_unlock_bh(hdev); hci_dev_put(hdev); return err; } #define EIR_FLAGS 0x01 /* flags */ #define EIR_UUID16_SOME 0x02 /* 16-bit UUID, more available */ #define EIR_UUID16_ALL 0x03 /* 16-bit UUID, all listed */ #define EIR_UUID32_SOME 0x04 /* 32-bit UUID, more available */ #define EIR_UUID32_ALL 0x05 /* 32-bit UUID, all listed */ #define EIR_UUID128_SOME 0x06 /* 128-bit UUID, more available */ #define EIR_UUID128_ALL 0x07 /* 128-bit UUID, all listed */ #define EIR_NAME_SHORT 0x08 /* shortened local name */ #define EIR_NAME_COMPLETE 0x09 /* complete local name */ #define EIR_TX_POWER 0x0A /* transmit power level */ #define EIR_DEVICE_ID 0x10 /* device ID */ #define PNP_INFO_SVCLASS_ID 0x1200 static u8 bluetooth_base_uuid[] = { 0xFB, 0x34, 0x9B, 0x5F, 0x80, 0x00, 0x00, 0x80, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; static u16 get_uuid16(u8 *uuid128) { u32 val; int i; for (i = 0; i < 12; i++) { if (bluetooth_base_uuid[i] != uuid128[i]) return 0; } memcpy(&val, &uuid128[12], 4); val = le32_to_cpu(val); if (val > 0xffff) return 0; return (u16) val; } static void create_eir(struct hci_dev *hdev, u8 *data) { u8 *ptr = data; u16 eir_len = 0; u16 uuid16_list[HCI_MAX_EIR_LENGTH / sizeof(u16)]; int i, truncated = 0; struct list_head *p; size_t name_len; name_len = strnlen(hdev->dev_name, HCI_MAX_EIR_LENGTH); if (name_len > 0) { /* EIR Data type */ if (name_len > 48) { name_len = 48; ptr[1] = EIR_NAME_SHORT; } else ptr[1] = EIR_NAME_COMPLETE; /* EIR Data length */ ptr[0] = name_len + 1; memcpy(ptr + 2, hdev->dev_name, name_len); eir_len += (name_len + 2); ptr += (name_len + 2); } memset(uuid16_list, 0, sizeof(uuid16_list)); /* Group all UUID16 types */ list_for_each(p, &hdev->uuids) { struct bt_uuid *uuid = list_entry(p, struct bt_uuid, list); u16 uuid16; uuid16 = get_uuid16(uuid->uuid); if (uuid16 == 0) return; if (uuid16 < 0x1100) continue; if (uuid16 == PNP_INFO_SVCLASS_ID) continue; /* Stop if not enough space to put next UUID */ if (eir_len + 2 + sizeof(u16) > HCI_MAX_EIR_LENGTH) { truncated = 1; break; } /* Check for duplicates */ for (i = 0; uuid16_list[i] != 0; i++) if (uuid16_list[i] == uuid16) break; if (uuid16_list[i] == 0) { uuid16_list[i] = uuid16; eir_len += sizeof(u16); } } if (uuid16_list[0] != 0) { u8 *length = ptr; /* EIR Data type */ ptr[1] = truncated ? EIR_UUID16_SOME : EIR_UUID16_ALL; ptr += 2; eir_len += 2; for (i = 0; uuid16_list[i] != 0; i++) { *ptr++ = (uuid16_list[i] & 0x00ff); *ptr++ = (uuid16_list[i] & 0xff00) >> 8; } /* EIR Data length */ *length = (i * sizeof(u16)) + 1; } } static int update_eir(struct hci_dev *hdev) { struct hci_cp_write_eir cp; if (!(hdev->features[6] & LMP_EXT_INQ)) return 0; if (hdev->ssp_mode == 0) return 0; if (test_bit(HCI_SERVICE_CACHE, &hdev->flags)) return 0; memset(&cp, 0, sizeof(cp)); create_eir(hdev, cp.data); if (memcmp(cp.data, hdev->eir, sizeof(cp.data)) == 0) return 0; memcpy(hdev->eir, cp.data, sizeof(cp.data)); return hci_send_cmd(hdev, HCI_OP_WRITE_EIR, sizeof(cp), &cp); } static int add_uuid(struct sock *sk, u16 index, unsigned char *data, u16 len) { struct mgmt_cp_add_uuid *cp; struct hci_dev *hdev; struct bt_uuid *uuid; int err; cp = (void *) data; BT_DBG("request for hci%u", index); if (len != sizeof(*cp)) return cmd_status(sk, index, MGMT_OP_ADD_UUID, EINVAL); hdev = hci_dev_get(index); if (!hdev) return cmd_status(sk, index, MGMT_OP_ADD_UUID, ENODEV); hci_dev_lock_bh(hdev); uuid = kmalloc(sizeof(*uuid), GFP_ATOMIC); if (!uuid) { err = -ENOMEM; goto failed; } memcpy(uuid->uuid, cp->uuid, 16); uuid->svc_hint = cp->svc_hint; list_add(&uuid->list, &hdev->uuids); if (test_bit(HCI_UP, &hdev->flags)) { err = update_class(hdev); if (err < 0) goto failed; err = update_eir(hdev); if (err < 0) goto failed; } else err = 0; err = cmd_complete(sk, index, MGMT_OP_ADD_UUID, NULL, 0); failed: hci_dev_unlock_bh(hdev); hci_dev_put(hdev); return err; } static int remove_uuid(struct sock *sk, u16 index, unsigned char *data, u16 len) { struct list_head *p, *n; struct mgmt_cp_remove_uuid *cp; struct hci_dev *hdev; u8 bt_uuid_any[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; int err, found; cp = (void *) data; BT_DBG("request for hci%u", index); if (len != sizeof(*cp)) return cmd_status(sk, index, MGMT_OP_REMOVE_UUID, EINVAL); hdev = hci_dev_get(index); if (!hdev) return cmd_status(sk, index, MGMT_OP_REMOVE_UUID, ENODEV); hci_dev_lock_bh(hdev); if (memcmp(cp->uuid, bt_uuid_any, 16) == 0) { err = hci_uuids_clear(hdev); goto unlock; } found = 0; list_for_each_safe(p, n, &hdev->uuids) { struct bt_uuid *match = list_entry(p, struct bt_uuid, list); if (memcmp(match->uuid, cp->uuid, 16) != 0) continue; list_del(&match->list); kfree(match); found++; } if (found == 0) { err = cmd_status(sk, index, MGMT_OP_REMOVE_UUID, ENOENT); goto unlock; } if (test_bit(HCI_UP, &hdev->flags)) { err = update_class(hdev); if (err < 0) goto unlock; err = update_eir(hdev); if (err < 0) goto unlock; } else err = 0; err = cmd_complete(sk, index, MGMT_OP_REMOVE_UUID, NULL, 0); unlock: hci_dev_unlock_bh(hdev); hci_dev_put(hdev); return err; } static int set_dev_class(struct sock *sk, u16 index, unsigned char *data, u16 len) { struct hci_dev *hdev; struct mgmt_cp_set_dev_class *cp; int err; cp = (void *) data; BT_DBG("request for hci%u", index); if (len != sizeof(*cp)) return cmd_status(sk, index, MGMT_OP_SET_DEV_CLASS, EINVAL); hdev = hci_dev_get(index); if (!hdev) return cmd_status(sk, index, MGMT_OP_SET_DEV_CLASS, ENODEV); hci_dev_lock_bh(hdev); hdev->major_class &= ~MGMT_MAJOR_CLASS_MASK; hdev->major_class |= cp->major & MGMT_MAJOR_CLASS_MASK; hdev->minor_class = cp->minor; if (test_bit(HCI_UP, &hdev->flags)) { err = update_class(hdev); if (err == 0) err = cmd_complete(sk, index, MGMT_OP_SET_DEV_CLASS, hdev->dev_class, sizeof(u8)*3); } else err = cmd_complete(sk, index, MGMT_OP_SET_DEV_CLASS, NULL, 0); hci_dev_unlock_bh(hdev); hci_dev_put(hdev); return err; } static int set_service_cache(struct sock *sk, u16 index, unsigned char *data, u16 len) { struct hci_dev *hdev; struct mgmt_cp_set_service_cache *cp; int err; cp = (void *) data; if (len != sizeof(*cp)) return cmd_status(sk, index, MGMT_OP_SET_SERVICE_CACHE, EINVAL); hdev = hci_dev_get(index); if (!hdev) return cmd_status(sk, index, MGMT_OP_SET_SERVICE_CACHE, ENODEV); hci_dev_lock_bh(hdev); BT_DBG("hci%u enable %d", index, cp->enable); if (cp->enable) { set_bit(HCI_SERVICE_CACHE, &hdev->flags); err = 0; } else { clear_bit(HCI_SERVICE_CACHE, &hdev->flags); if (test_bit(HCI_UP, &hdev->flags)) { err = update_class(hdev); if (err == 0) err = update_eir(hdev); } else err = 0; } if (err == 0) err = cmd_complete(sk, index, MGMT_OP_SET_SERVICE_CACHE, NULL, 0); hci_dev_unlock_bh(hdev); hci_dev_put(hdev); return err; } static int load_keys(struct sock *sk, u16 index, unsigned char *data, u16 len) { struct hci_dev *hdev; struct mgmt_cp_load_keys *cp; u16 key_count, expected_len; int i, err; cp = (void *) data; if (len < sizeof(*cp)) return -EINVAL; key_count = get_unaligned_le16(&cp->key_count); expected_len = sizeof(*cp) + key_count * sizeof(struct mgmt_key_info); if (expected_len > len) { BT_ERR("load_keys: expected at least %u bytes, got %u bytes", expected_len, len); return -EINVAL; } hdev = hci_dev_get(index); if (!hdev) return cmd_status(sk, index, MGMT_OP_LOAD_KEYS, ENODEV); BT_DBG("hci%u debug_keys %u key_count %u", index, cp->debug_keys, key_count); hci_dev_lock_bh(hdev); hci_link_keys_clear(hdev); set_bit(HCI_LINK_KEYS, &hdev->flags); if (cp->debug_keys) set_bit(HCI_DEBUG_KEYS, &hdev->flags); else clear_bit(HCI_DEBUG_KEYS, &hdev->flags); len -= sizeof(*cp); i = 0; while (i < len) { struct mgmt_key_info *key = (void *) cp->keys + i; i += sizeof(*key); if (key->key_type == KEY_TYPE_LTK) { struct key_master_id *id = (void *) key->data; if (key->dlen != sizeof(struct key_master_id)) continue; hci_add_ltk(hdev, 0, &key->bdaddr, key->addr_type, key->pin_len, key->auth, id->ediv, id->rand, key->val); continue; } hci_add_link_key(hdev, 0, &key->bdaddr, key->val, key->key_type, key->pin_len); } err = cmd_complete(sk, index, MGMT_OP_LOAD_KEYS, NULL, 0); hci_dev_unlock_bh(hdev); hci_dev_put(hdev); return err; } static int remove_key(struct sock *sk, u16 index, unsigned char *data, u16 len) { struct hci_dev *hdev; struct mgmt_cp_remove_key *cp; struct hci_conn *conn; int err; cp = (void *) data; if (len != sizeof(*cp)) return cmd_status(sk, index, MGMT_OP_REMOVE_KEY, EINVAL); hdev = hci_dev_get(index); if (!hdev) return cmd_status(sk, index, MGMT_OP_REMOVE_KEY, ENODEV); hci_dev_lock_bh(hdev); err = hci_remove_link_key(hdev, &cp->bdaddr); if (err < 0) { err = cmd_status(sk, index, MGMT_OP_REMOVE_KEY, -err); goto unlock; } err = 0; if (!test_bit(HCI_UP, &hdev->flags) || !cp->disconnect) goto unlock; conn = hci_conn_hash_lookup_ba(hdev, ACL_LINK, &cp->bdaddr); if (conn) { struct hci_cp_disconnect dc; put_unaligned_le16(conn->handle, &dc.handle); dc.reason = 0x13; /* Remote User Terminated Connection */ err = hci_send_cmd(hdev, HCI_OP_DISCONNECT, 0, NULL); } unlock: hci_dev_unlock_bh(hdev); hci_dev_put(hdev); return err; } static int disconnect(struct sock *sk, u16 index, unsigned char *data, u16 len) { struct hci_dev *hdev; struct mgmt_cp_disconnect *cp; struct hci_cp_disconnect dc; struct pending_cmd *cmd; struct hci_conn *conn; int err; BT_DBG(""); cp = (void *) data; if (len != sizeof(*cp)) return cmd_status(sk, index, MGMT_OP_DISCONNECT, EINVAL); hdev = hci_dev_get(index); if (!hdev) return cmd_status(sk, index, MGMT_OP_DISCONNECT, ENODEV); hci_dev_lock_bh(hdev); if (!test_bit(HCI_UP, &hdev->flags)) { err = cmd_status(sk, index, MGMT_OP_DISCONNECT, ENETDOWN); goto failed; } if (mgmt_pending_find(MGMT_OP_DISCONNECT, index)) { err = cmd_status(sk, index, MGMT_OP_DISCONNECT, EBUSY); goto failed; } conn = hci_conn_hash_lookup_ba(hdev, ACL_LINK, &cp->bdaddr); if (!conn) { conn = hci_conn_hash_lookup_ba(hdev, LE_LINK, &cp->bdaddr); if (!conn) { err = cmd_status(sk, index, MGMT_OP_DISCONNECT, ENOTCONN); goto failed; } } cmd = mgmt_pending_add(sk, MGMT_OP_DISCONNECT, index, data, len); if (!cmd) { err = -ENOMEM; goto failed; } put_unaligned_le16(conn->handle, &dc.handle); dc.reason = 0x13; /* Remote User Terminated Connection */ err = hci_send_cmd(hdev, HCI_OP_DISCONNECT, sizeof(dc), &dc); if (err < 0) mgmt_pending_remove(cmd); failed: hci_dev_unlock_bh(hdev); hci_dev_put(hdev); return err; } static u8 link_to_mgmt(u8 link_type, u8 addr_type) { switch (link_type) { case LE_LINK: switch (addr_type) { case ADDR_LE_DEV_PUBLIC: return MGMT_ADDR_LE_PUBLIC; case ADDR_LE_DEV_RANDOM: return MGMT_ADDR_LE_RANDOM; default: return MGMT_ADDR_INVALID; } case ACL_LINK: return MGMT_ADDR_BREDR; default: return MGMT_ADDR_INVALID; } } static int get_connections(struct sock *sk, u16 index) { struct mgmt_rp_get_connections *rp; struct hci_dev *hdev; struct list_head *p; size_t rp_len; u16 count; int i, err; BT_DBG(""); hdev = hci_dev_get(index); if (!hdev) return cmd_status(sk, index, MGMT_OP_GET_CONNECTIONS, ENODEV); hci_dev_lock_bh(hdev); count = 0; list_for_each(p, &hdev->conn_hash.list) { count++; } rp_len = sizeof(*rp) + (count * sizeof(bdaddr_t)); rp = kmalloc(rp_len, GFP_ATOMIC); if (!rp) { err = -ENOMEM; goto unlock; } put_unaligned_le16(count, &rp->conn_count); read_lock(&hci_dev_list_lock); i = 0; list_for_each(p, &hdev->conn_hash.list) { struct hci_conn *c = list_entry(p, struct hci_conn, list); bacpy(&rp->conn[i++], &c->dst); } read_unlock(&hci_dev_list_lock); err = cmd_complete(sk, index, MGMT_OP_GET_CONNECTIONS, rp, rp_len); unlock: kfree(rp); hci_dev_unlock_bh(hdev); hci_dev_put(hdev); return err; } static int pin_code_reply(struct sock *sk, u16 index, unsigned char *data, u16 len) { struct hci_dev *hdev; struct mgmt_cp_pin_code_reply *cp; struct hci_cp_pin_code_reply reply; struct pending_cmd *cmd; int err; BT_DBG(""); cp = (void *) data; if (len != sizeof(*cp)) return cmd_status(sk, index, MGMT_OP_PIN_CODE_REPLY, EINVAL); hdev = hci_dev_get(index); if (!hdev) return cmd_status(sk, index, MGMT_OP_PIN_CODE_REPLY, ENODEV); hci_dev_lock_bh(hdev); if (!test_bit(HCI_UP, &hdev->flags)) { err = cmd_status(sk, index, MGMT_OP_PIN_CODE_REPLY, ENETDOWN); goto failed; } cmd = mgmt_pending_add(sk, MGMT_OP_PIN_CODE_REPLY, index, data, len); if (!cmd) { err = -ENOMEM; goto failed; } bacpy(&reply.bdaddr, &cp->bdaddr); reply.pin_len = cp->pin_len; memcpy(reply.pin_code, cp->pin_code, 16); err = hci_send_cmd(hdev, HCI_OP_PIN_CODE_REPLY, sizeof(reply), &reply); if (err < 0) mgmt_pending_remove(cmd); failed: hci_dev_unlock_bh(hdev); hci_dev_put(hdev); return err; } static int encrypt_link(struct sock *sk, u16 index, unsigned char *data, u16 len) { struct hci_dev *hdev; struct mgmt_cp_encrypt_link *cp; struct hci_cp_set_conn_encrypt enc; struct hci_conn *conn; int err = 0; BT_DBG(""); cp = (void *) data; if (len != sizeof(*cp)) return cmd_status(sk, index, MGMT_OP_ENCRYPT_LINK, EINVAL); hdev = hci_dev_get(index); if (!hdev) return cmd_status(sk, index, MGMT_OP_ENCRYPT_LINK, ENODEV); hci_dev_lock_bh(hdev); if (!test_bit(HCI_UP, &hdev->flags)) { err = cmd_status(sk, index, MGMT_OP_ENCRYPT_LINK, ENETDOWN); goto done; } conn = hci_conn_hash_lookup_ba(hdev, ACL_LINK, &cp->bdaddr); if (!conn) { err = cmd_status(sk, index, MGMT_OP_ENCRYPT_LINK, ENOTCONN); goto done; } if (test_and_set_bit(HCI_CONN_ENCRYPT_PEND, &conn->pend)) { err = cmd_status(sk, index, MGMT_OP_ENCRYPT_LINK, EINPROGRESS); goto done; } if (conn->link_mode & HCI_LM_AUTH) { enc.handle = cpu_to_le16(conn->handle); enc.encrypt = cp->enable; err = hci_send_cmd(hdev, HCI_OP_SET_CONN_ENCRYPT, sizeof(enc), &enc); } else { conn->auth_initiator = 1; if (!test_and_set_bit(HCI_CONN_AUTH_PEND, &conn->pend)) { struct hci_cp_auth_requested cp; cp.handle = cpu_to_le16(conn->handle); err = hci_send_cmd(conn->hdev, HCI_OP_AUTH_REQUESTED, sizeof(cp), &cp); } } done: hci_dev_unlock_bh(hdev); hci_dev_put(hdev); return err; } static int pin_code_neg_reply(struct sock *sk, u16 index, unsigned char *data, u16 len) { struct hci_dev *hdev; struct mgmt_cp_pin_code_neg_reply *cp; struct pending_cmd *cmd; int err; BT_DBG(""); cp = (void *) data; if (len != sizeof(*cp)) return cmd_status(sk, index, MGMT_OP_PIN_CODE_NEG_REPLY, EINVAL); hdev = hci_dev_get(index); if (!hdev) return cmd_status(sk, index, MGMT_OP_PIN_CODE_NEG_REPLY, ENODEV); hci_dev_lock_bh(hdev); if (!test_bit(HCI_UP, &hdev->flags)) { err = cmd_status(sk, index, MGMT_OP_PIN_CODE_NEG_REPLY, ENETDOWN); goto failed; } cmd = mgmt_pending_add(sk, MGMT_OP_PIN_CODE_NEG_REPLY, index, data, len); if (!cmd) { err = -ENOMEM; goto failed; } err = hci_send_cmd(hdev, HCI_OP_PIN_CODE_NEG_REPLY, sizeof(cp->bdaddr), &cp->bdaddr); if (err < 0) mgmt_pending_remove(cmd); failed: hci_dev_unlock_bh(hdev); hci_dev_put(hdev); return err; } static int le_add_dev_white_list(struct sock *sk, u16 index, unsigned char *data, u16 len) { struct hci_dev *hdev; struct mgmt_cp_le_add_dev_white_list *cp; int err = 0; BT_DBG(""); cp = (void *) data; if (len != sizeof(*cp)) return cmd_status(sk, index, MGMT_OP_LE_ADD_DEV_WHITE_LIST, EINVAL); hdev = hci_dev_get(index); if (!hdev) return cmd_status(sk, index, MGMT_OP_LE_ADD_DEV_WHITE_LIST, ENODEV); hci_dev_lock_bh(hdev); if (!test_bit(HCI_UP, &hdev->flags)) { err = cmd_status(sk, index, MGMT_OP_LE_ADD_DEV_WHITE_LIST, ENETDOWN); goto failed; } hci_le_add_dev_white_list(hdev, &cp->bdaddr); failed: hci_dev_unlock_bh(hdev); hci_dev_put(hdev); return err; } static int le_remove_dev_white_list(struct sock *sk, u16 index, unsigned char *data, u16 len) { struct hci_dev *hdev; struct mgmt_cp_le_remove_dev_white_list *cp; int err = 0; BT_DBG(""); cp = (void *) data; if (len != sizeof(*cp)) return cmd_status(sk, index, MGMT_OP_LE_REMOVE_DEV_WHITE_LIST, EINVAL); hdev = hci_dev_get(index); if (!hdev) return cmd_status(sk, index, MGMT_OP_LE_REMOVE_DEV_WHITE_LIST, ENODEV); hci_dev_lock_bh(hdev); if (!test_bit(HCI_UP, &hdev->flags)) { err = cmd_status(sk, index, MGMT_OP_LE_REMOVE_DEV_WHITE_LIST, ENETDOWN); goto failed; } hci_le_remove_dev_white_list(hdev, &cp->bdaddr); failed: hci_dev_unlock_bh(hdev); hci_dev_put(hdev); return err; } static int le_create_conn_white_list(struct sock *sk, u16 index) { struct hci_dev *hdev; struct hci_conn *conn; u8 sec_level, auth_type; struct pending_cmd *cmd; bdaddr_t bdaddr; int err = 0; BT_DBG(""); hdev = hci_dev_get(index); if (!hdev) return cmd_status(sk, index, MGMT_OP_LE_CREATE_CONN_WHITE_LIST, ENODEV); hci_dev_lock_bh(hdev); if (!test_bit(HCI_UP, &hdev->flags)) { err = cmd_status(sk, index, MGMT_OP_LE_CREATE_CONN_WHITE_LIST, ENETDOWN); goto failed; } cmd = mgmt_pending_add(sk, MGMT_OP_LE_CREATE_CONN_WHITE_LIST, index, NULL, 0); if (!cmd) { err = -ENOMEM; goto failed; } sec_level = BT_SECURITY_MEDIUM; auth_type = HCI_AT_GENERAL_BONDING; memset(&bdaddr, 0, sizeof(bdaddr)); conn = hci_le_connect(hdev, 0, BDADDR_ANY, sec_level, auth_type, NULL); if (IS_ERR(conn)) { err = PTR_ERR(conn); mgmt_pending_remove(cmd); } failed: hci_dev_unlock_bh(hdev); hci_dev_put(hdev); return err; } static int le_cancel_create_conn_white_list(struct sock *sk, u16 index) { struct hci_dev *hdev; int err = 0; BT_DBG(""); hdev = hci_dev_get(index); if (!hdev) return cmd_status(sk, index, MGMT_OP_LE_CANCEL_CREATE_CONN_WHITE_LIST, ENODEV); hci_dev_lock_bh(hdev); if (!test_bit(HCI_UP, &hdev->flags)) { err = cmd_status(sk, index, MGMT_OP_LE_CANCEL_CREATE_CONN_WHITE_LIST, ENETDOWN); goto failed; } hci_le_cancel_create_connect(hdev, BDADDR_ANY); failed: hci_dev_unlock_bh(hdev); hci_dev_put(hdev); return err; } static int le_clear_white_list(struct sock *sk, u16 index) { struct hci_dev *hdev; int err; BT_DBG(""); hdev = hci_dev_get(index); if (!hdev) return cmd_status(sk, index, MGMT_OP_LE_CLEAR_WHITE_LIST, ENODEV); hci_dev_lock_bh(hdev); if (!test_bit(HCI_UP, &hdev->flags)) { err = cmd_status(sk, index, MGMT_OP_LE_CLEAR_WHITE_LIST, ENETDOWN); goto failed; } err = hci_send_cmd(hdev, HCI_OP_LE_CLEAR_WHITE_LIST, 0, NULL); failed: hci_dev_unlock_bh(hdev); hci_dev_put(hdev); return err; } static int set_io_capability(struct sock *sk, u16 index, unsigned char *data, u16 len) { struct hci_dev *hdev; struct mgmt_cp_set_io_capability *cp; BT_DBG(""); cp = (void *) data; if (len != sizeof(*cp)) return cmd_status(sk, index, MGMT_OP_SET_IO_CAPABILITY, EINVAL); hdev = hci_dev_get(index); if (!hdev) return cmd_status(sk, index, MGMT_OP_SET_IO_CAPABILITY, ENODEV); hci_dev_lock_bh(hdev); hdev->io_capability = cp->io_capability; BT_DBG("%s IO capability set to 0x%02x", hdev->name, hdev->io_capability); hci_dev_unlock_bh(hdev); hci_dev_put(hdev); return cmd_complete(sk, index, MGMT_OP_SET_IO_CAPABILITY, NULL, 0); } static inline struct pending_cmd *find_pairing(struct hci_conn *conn) { struct hci_dev *hdev = conn->hdev; struct list_head *p; list_for_each(p, &cmd_list) { struct pending_cmd *cmd; cmd = list_entry(p, struct pending_cmd, list); if (cmd->opcode != MGMT_OP_PAIR_DEVICE) continue; if (cmd->index != hdev->id) continue; if (cmd->user_data != conn) continue; return cmd; } return NULL; } static void pairing_complete(struct pending_cmd *cmd, u8 status) { struct mgmt_rp_pair_device rp; struct hci_conn *conn = cmd->user_data; BT_DBG(" %u", status); bacpy(&rp.bdaddr, &conn->dst); rp.status = status; cmd_complete(cmd->sk, cmd->index, MGMT_OP_PAIR_DEVICE, &rp, sizeof(rp)); /* So we don't get further callbacks for this connection */ conn->connect_cfm_cb = NULL; conn->security_cfm_cb = NULL; conn->disconn_cfm_cb = NULL; mgmt_pending_remove(cmd); } static void pairing_complete_cb(struct hci_conn *conn, u8 status) { struct pending_cmd *cmd; BT_DBG(" %u", status); cmd = find_pairing(conn); if (!cmd) { BT_DBG("Unable to find a pending command"); return; } pairing_complete(cmd, status); hci_conn_put(conn); } static void pairing_security_complete_cb(struct hci_conn *conn, u8 status) { struct pending_cmd *cmd; BT_DBG(" %u", status); cmd = find_pairing(conn); if (!cmd) { BT_DBG("Unable to find a pending command"); return; } if (conn->type == LE_LINK) smp_link_encrypt_cmplt(conn->l2cap_data, status, status ? 0 : 1); else pairing_complete(cmd, status); } static void pairing_connect_complete_cb(struct hci_conn *conn, u8 status) { struct pending_cmd *cmd; BT_DBG("conn: %p %u", conn, status); cmd = find_pairing(conn); if (!cmd) { BT_DBG("Unable to find a pending command"); return; } if (status || conn->pending_sec_level < BT_SECURITY_MEDIUM) pairing_complete(cmd, status); hci_conn_put(conn); } static void discovery_terminated(struct pending_cmd *cmd, void *data) { struct hci_dev *hdev; struct mgmt_mode ev = {0}; BT_DBG(""); hdev = hci_dev_get(cmd->index); if (!hdev) goto not_found; del_timer(&hdev->disco_le_timer); del_timer(&hdev->disco_timer); hci_dev_put(hdev); not_found: mgmt_event(MGMT_EV_DISCOVERING, cmd->index, &ev, sizeof(ev), NULL); list_del(&cmd->list); mgmt_pending_free(cmd); } static int pair_device(struct sock *sk, u16 index, unsigned char *data, u16 len) { struct hci_dev *hdev; struct mgmt_cp_pair_device *cp; struct pending_cmd *cmd; u8 sec_level, auth_type, io_cap; struct hci_conn *conn; struct adv_entry *entry; int err; BT_DBG(""); cp = (void *) data; if (len != sizeof(*cp)) return cmd_status(sk, index, MGMT_OP_PAIR_DEVICE, EINVAL); hdev = hci_dev_get(index); if (!hdev) return cmd_status(sk, index, MGMT_OP_PAIR_DEVICE, ENODEV); hci_dev_lock_bh(hdev); io_cap = cp->io_cap; sec_level = BT_SECURITY_MEDIUM; auth_type = HCI_AT_DEDICATED_BONDING; entry = hci_find_adv_entry(hdev, &cp->bdaddr); if (entry && entry->flags & 0x04) { conn = hci_le_connect(hdev, 0, &cp->bdaddr, sec_level, auth_type, NULL); } else { /* ACL-SSP does not support io_cap 0x04 (KeyboadDisplay) */ if (io_cap == 0x04) io_cap = 0x01; conn = hci_connect(hdev, ACL_LINK, 0, &cp->bdaddr, sec_level, auth_type); conn->auth_initiator = 1; } if (IS_ERR(conn)) { err = PTR_ERR(conn); goto unlock; } if (conn->connect_cfm_cb) { hci_conn_put(conn); err = cmd_status(sk, index, MGMT_OP_PAIR_DEVICE, EBUSY); goto unlock; } cmd = mgmt_pending_add(sk, MGMT_OP_PAIR_DEVICE, index, data, len); if (!cmd) { err = -ENOMEM; hci_conn_put(conn); goto unlock; } conn->connect_cfm_cb = pairing_connect_complete_cb; conn->security_cfm_cb = pairing_security_complete_cb; conn->disconn_cfm_cb = pairing_complete_cb; conn->io_capability = io_cap; cmd->user_data = conn; if (conn->state == BT_CONNECTED && hci_conn_security(conn, sec_level, auth_type)) pairing_complete(cmd, 0); err = 0; unlock: hci_dev_unlock_bh(hdev); hci_dev_put(hdev); return err; } static int user_confirm_reply(struct sock *sk, u16 index, unsigned char *data, u16 len, u16 opcode) { struct mgmt_cp_user_confirm_reply *cp = (void *) data; u16 mgmt_op = opcode, hci_op; struct pending_cmd *cmd; struct hci_dev *hdev; struct hci_conn *le_conn; int err; BT_DBG("%d", mgmt_op); if (mgmt_op == MGMT_OP_USER_CONFIRM_NEG_REPLY) hci_op = HCI_OP_USER_CONFIRM_NEG_REPLY; else hci_op = HCI_OP_USER_CONFIRM_REPLY; if (len < sizeof(*cp)) return cmd_status(sk, index, mgmt_op, EINVAL); hdev = hci_dev_get(index); if (!hdev) return cmd_status(sk, index, mgmt_op, ENODEV); hci_dev_lock_bh(hdev); if (!test_bit(HCI_UP, &hdev->flags)) { err = cmd_status(sk, index, mgmt_op, ENETDOWN); goto done; } le_conn = hci_conn_hash_lookup_ba(hdev, LE_LINK, &cp->bdaddr); if (le_conn) { err = le_user_confirm_reply(le_conn, mgmt_op, (void *) cp); goto done; } BT_DBG("BR/EDR: %s", mgmt_op == MGMT_OP_USER_CONFIRM_NEG_REPLY ? "Reject" : "Accept"); cmd = mgmt_pending_add(sk, mgmt_op, index, data, len); if (!cmd) { err = -ENOMEM; goto done; } err = hci_send_cmd(hdev, hci_op, sizeof(cp->bdaddr), &cp->bdaddr); if (err < 0) mgmt_pending_remove(cmd); done: hci_dev_unlock_bh(hdev); hci_dev_put(hdev); return err; } static int resolve_name(struct sock *sk, u16 index, unsigned char *data, u16 len) { struct mgmt_cp_resolve_name *mgmt_cp = (void *) data; struct hci_cp_remote_name_req hci_cp; struct hci_dev *hdev; struct pending_cmd *cmd; int err; BT_DBG(""); if (len != sizeof(*mgmt_cp)) return cmd_status(sk, index, MGMT_OP_RESOLVE_NAME, EINVAL); hdev = hci_dev_get(index); if (!hdev) return cmd_status(sk, index, MGMT_OP_RESOLVE_NAME, ENODEV); hci_dev_lock_bh(hdev); cmd = mgmt_pending_add(sk, MGMT_OP_RESOLVE_NAME, index, data, len); if (!cmd) { err = -ENOMEM; goto failed; } memset(&hci_cp, 0, sizeof(hci_cp)); bacpy(&hci_cp.bdaddr, &mgmt_cp->bdaddr); err = hci_send_cmd(hdev, HCI_OP_REMOTE_NAME_REQ, sizeof(hci_cp), &hci_cp); if (err < 0) mgmt_pending_remove(cmd); failed: hci_dev_unlock_bh(hdev); hci_dev_put(hdev); return err; } static int cancel_resolve_name(struct sock *sk, u16 index, unsigned char *data, u16 len) { struct mgmt_cp_cancel_resolve_name *mgmt_cp = (void *) data; struct hci_cp_remote_name_req_cancel hci_cp; struct hci_dev *hdev; int err; BT_DBG(""); if (len != sizeof(*mgmt_cp)) return cmd_status(sk, index, MGMT_OP_CANCEL_RESOLVE_NAME, EINVAL); hdev = hci_dev_get(index); if (!hdev) return cmd_status(sk, index, MGMT_OP_CANCEL_RESOLVE_NAME, ENODEV); hci_dev_lock_bh(hdev); memset(&hci_cp, 0, sizeof(hci_cp)); bacpy(&hci_cp.bdaddr, &mgmt_cp->bdaddr); err = hci_send_cmd(hdev, HCI_OP_REMOTE_NAME_REQ_CANCEL, sizeof(hci_cp), &hci_cp); hci_dev_unlock_bh(hdev); hci_dev_put(hdev); return err; } static int set_connection_params(struct sock *sk, u16 index, unsigned char *data, u16 len) { struct mgmt_cp_set_connection_params *cp = (void *) data; struct hci_dev *hdev; struct hci_conn *conn; int err; BT_DBG(""); if (len != sizeof(*cp)) return cmd_status(sk, index, MGMT_OP_SET_CONNECTION_PARAMS, EINVAL); hdev = hci_dev_get(index); if (!hdev) return cmd_status(sk, index, MGMT_OP_SET_CONNECTION_PARAMS, ENODEV); hci_dev_lock_bh(hdev); conn = hci_conn_hash_lookup_ba(hdev, LE_LINK, &cp->bdaddr); if (!conn) { err = cmd_status(sk, index, MGMT_OP_SET_CONNECTION_PARAMS, ENOTCONN); goto failed; } hci_le_conn_update(conn, le16_to_cpu(cp->interval_min), le16_to_cpu(cp->interval_max), le16_to_cpu(cp->slave_latency), le16_to_cpu(cp->timeout_multiplier)); err = cmd_status(sk, index, MGMT_OP_SET_CONNECTION_PARAMS, 0); failed: hci_dev_unlock_bh(hdev); hci_dev_put(hdev); return err; } static int read_tx_power_level(struct sock *sk, u16 index, unsigned char *data, u16 len) { struct hci_dev *hdev; struct mgmt_cp_read_tx_power_level *cp = (void *) data; struct hci_cp_read_tx_power hci_cp; struct pending_cmd *cmd; struct hci_conn *conn; int err; BT_DBG("hci%u", index); if (len != sizeof(*cp)) return cmd_status(sk, index, MGMT_OP_READ_TX_POWER_LEVEL, EINVAL); hdev = hci_dev_get(index); if (!hdev) return cmd_status(sk, index, MGMT_OP_READ_TX_POWER_LEVEL, ENODEV); hci_dev_lock_bh(hdev); if (!test_bit(HCI_UP, &hdev->flags)) { err = cmd_status(sk, index, MGMT_OP_READ_TX_POWER_LEVEL, ENETDOWN); goto unlock; } if (mgmt_pending_find(MGMT_OP_READ_TX_POWER_LEVEL, index)) { err = cmd_status(sk, index, MGMT_OP_READ_TX_POWER_LEVEL, EBUSY); goto unlock; } cmd = mgmt_pending_add(sk, MGMT_OP_READ_TX_POWER_LEVEL, index, data, len); if (!cmd) { err = -ENOMEM; goto unlock; } conn = hci_conn_hash_lookup_ba(hdev, ACL_LINK, &cp->bdaddr); if (!conn) conn = hci_conn_hash_lookup_ba(hdev, LE_LINK, &cp->bdaddr); if (!conn) { err = cmd_status(sk, index, MGMT_OP_READ_TX_POWER_LEVEL, ENOTCONN); mgmt_pending_remove(cmd); goto unlock; } put_unaligned_le16(conn->handle, &hci_cp.handle); put_unaligned_le16(cp->type, &hci_cp.type); err = hci_send_cmd(hdev, HCI_OP_READ_TX_POWER, sizeof(hci_cp), &hci_cp); if (err < 0) mgmt_pending_remove(cmd); unlock: hci_dev_unlock_bh(hdev); hci_dev_put(hdev); return err; } static int set_rssi_reporter(struct sock *sk, u16 index, unsigned char *data, u16 len) { struct mgmt_cp_set_rssi_reporter *cp = (void *) data; struct hci_dev *hdev; struct hci_conn *conn; int err = 0; if (len != sizeof(*cp)) return cmd_status(sk, index, MGMT_OP_SET_RSSI_REPORTER, EINVAL); hdev = hci_dev_get(index); if (!hdev) return cmd_status(sk, index, MGMT_OP_SET_RSSI_REPORTER, ENODEV); hci_dev_lock_bh(hdev); conn = hci_conn_hash_lookup_ba(hdev, LE_LINK, &cp->bdaddr); if (!conn) { err = cmd_status(sk, index, MGMT_OP_SET_RSSI_REPORTER, ENOTCONN); goto failed; } BT_DBG("updateOnThreshExceed %d ", cp->updateOnThreshExceed); hci_conn_set_rssi_reporter(conn, cp->rssi_threshold, __le16_to_cpu(cp->interval), cp->updateOnThreshExceed); failed: hci_dev_unlock_bh(hdev); hci_dev_put(hdev); return err; } static int unset_rssi_reporter(struct sock *sk, u16 index, unsigned char *data, u16 len) { struct mgmt_cp_unset_rssi_reporter *cp = (void *) data; struct hci_dev *hdev; struct hci_conn *conn; int err = 0; if (len != sizeof(*cp)) return cmd_status(sk, index, MGMT_OP_UNSET_RSSI_REPORTER, EINVAL); hdev = hci_dev_get(index); if (!hdev) return cmd_status(sk, index, MGMT_OP_UNSET_RSSI_REPORTER, ENODEV); hci_dev_lock_bh(hdev); conn = hci_conn_hash_lookup_ba(hdev, LE_LINK, &cp->bdaddr); if (!conn) { err = cmd_status(sk, index, MGMT_OP_UNSET_RSSI_REPORTER, ENOTCONN); goto failed; } hci_conn_unset_rssi_reporter(conn); failed: hci_dev_unlock_bh(hdev); hci_dev_put(hdev); return err; } static int le_cancel_create_conn(struct sock *sk, u16 index, unsigned char *data, u16 len) { struct mgmt_cp_le_cancel_create_conn *cp = (void *) data; struct hci_dev *hdev; int err = 0; if (len != sizeof(*cp)) return cmd_status(sk, index, MGMT_OP_LE_CANCEL_CREATE_CONN, EINVAL); hdev = hci_dev_get(index); if (!hdev) return cmd_status(sk, index, MGMT_OP_LE_CANCEL_CREATE_CONN, ENODEV); hci_dev_lock_bh(hdev); if (!test_bit(HCI_UP, &hdev->flags)) { err = cmd_status(sk, index, MGMT_OP_LE_CANCEL_CREATE_CONN, ENETDOWN); goto failed; } hci_le_cancel_create_connect(hdev, &cp->bdaddr); failed: hci_dev_unlock_bh(hdev); hci_dev_put(hdev); return err; } static int set_local_name(struct sock *sk, u16 index, unsigned char *data, u16 len) { struct mgmt_cp_set_local_name *mgmt_cp = (void *) data; struct hci_cp_write_local_name hci_cp; struct hci_dev *hdev; struct pending_cmd *cmd; int err; BT_DBG(""); if (len != sizeof(*mgmt_cp)) return cmd_status(sk, index, MGMT_OP_SET_LOCAL_NAME, EINVAL); hdev = hci_dev_get(index); if (!hdev) return cmd_status(sk, index, MGMT_OP_SET_LOCAL_NAME, ENODEV); hci_dev_lock_bh(hdev); cmd = mgmt_pending_add(sk, MGMT_OP_SET_LOCAL_NAME, index, data, len); if (!cmd) { err = -ENOMEM; goto failed; } memcpy(hci_cp.name, mgmt_cp->name, sizeof(hci_cp.name)); err = hci_send_cmd(hdev, HCI_OP_WRITE_LOCAL_NAME, sizeof(hci_cp), &hci_cp); if (err < 0) mgmt_pending_remove(cmd); failed: hci_dev_unlock_bh(hdev); hci_dev_put(hdev); return err; } static void discovery_rsp(struct pending_cmd *cmd, void *data) { struct mgmt_mode ev; BT_DBG(""); if (cmd->opcode == MGMT_OP_START_DISCOVERY) { ev.val = 1; cmd_status(cmd->sk, cmd->index, MGMT_OP_START_DISCOVERY, 0); } else { ev.val = 0; cmd_complete(cmd->sk, cmd->index, MGMT_OP_STOP_DISCOVERY, NULL, 0); if (cmd->opcode == MGMT_OP_STOP_DISCOVERY) { struct hci_dev *hdev = hci_dev_get(cmd->index); if (hdev) { del_timer(&hdev->disco_le_timer); del_timer(&hdev->disco_timer); hci_dev_put(hdev); } } } mgmt_event(MGMT_EV_DISCOVERING, cmd->index, &ev, sizeof(ev), NULL); list_del(&cmd->list); mgmt_pending_free(cmd); } void mgmt_inquiry_started(u16 index) { BT_DBG(""); mgmt_pending_foreach(MGMT_OP_START_DISCOVERY, index, discovery_rsp, NULL); } void mgmt_inquiry_complete_evt(u16 index, u8 status) { struct hci_dev *hdev; struct hci_cp_le_set_scan_enable le_cp = {1, 0}; struct mgmt_mode cp = {0}; int err = -1; hdev = hci_dev_get(index); if (hdev) BT_DBG("disco_state: %d", hdev->disco_state); if (!hdev || !lmp_le_capable(hdev)) { mgmt_pending_foreach(MGMT_OP_STOP_DISCOVERY, index, discovery_terminated, NULL); mgmt_event(MGMT_EV_DISCOVERING, index, &cp, sizeof(cp), NULL); hdev->disco_state = SCAN_IDLE; if (hdev) goto done; else return; } if (hdev->disco_state != SCAN_IDLE) { err = hci_send_cmd(hdev, HCI_OP_LE_SET_SCAN_ENABLE, sizeof(le_cp), &le_cp); if (err >= 0) { mod_timer(&hdev->disco_le_timer, jiffies + msecs_to_jiffies(hdev->disco_int_phase * 1000)); hdev->disco_state = SCAN_LE; } else hdev->disco_state = SCAN_IDLE; } if (hdev->disco_state == SCAN_IDLE) mgmt_event(MGMT_EV_DISCOVERING, index, &cp, sizeof(cp), NULL); if (err < 0) mgmt_pending_foreach(MGMT_OP_STOP_DISCOVERY, index, discovery_terminated, NULL); done: hci_dev_put(hdev); } void mgmt_disco_timeout(unsigned long data) { struct hci_dev *hdev = (void *) data; struct pending_cmd *cmd; struct mgmt_mode cp = {0}; BT_DBG("hci%d", hdev->id); hdev = hci_dev_get(hdev->id); if (!hdev) return; hci_dev_lock_bh(hdev); del_timer(&hdev->disco_le_timer); if (hdev->disco_state != SCAN_IDLE) { struct hci_cp_le_set_scan_enable le_cp = {0, 0}; if (test_bit(HCI_UP, &hdev->flags)) { if (hdev->disco_state == SCAN_LE) hci_send_cmd(hdev, HCI_OP_LE_SET_SCAN_ENABLE, sizeof(le_cp), &le_cp); else hci_send_cmd(hdev, HCI_OP_INQUIRY_CANCEL, 0, NULL); } hdev->disco_state = SCAN_IDLE; } mgmt_event(MGMT_EV_DISCOVERING, hdev->id, &cp, sizeof(cp), NULL); cmd = mgmt_pending_find(MGMT_OP_STOP_DISCOVERY, hdev->id); if (cmd) mgmt_pending_remove(cmd); hci_dev_unlock_bh(hdev); hci_dev_put(hdev); } void mgmt_disco_le_timeout(unsigned long data) { struct hci_dev *hdev = (void *)data; struct hci_cp_le_set_scan_enable le_cp = {0, 0}; BT_DBG("hci%d", hdev->id); hdev = hci_dev_get(hdev->id); if (!hdev) return; hci_dev_lock_bh(hdev); if (test_bit(HCI_UP, &hdev->flags)) { if (hdev->disco_state == SCAN_LE) hci_send_cmd(hdev, HCI_OP_LE_SET_SCAN_ENABLE, sizeof(le_cp), &le_cp); /* re-start BR scan */ if (hdev->disco_state != SCAN_IDLE) { struct hci_cp_inquiry cp = {{0x33, 0x8b, 0x9e}, 4, 0}; hdev->disco_int_phase *= 2; hdev->disco_int_count = 0; cp.num_rsp = (u8) hdev->disco_int_phase; hci_send_cmd(hdev, HCI_OP_INQUIRY, sizeof(cp), &cp); hdev->disco_state = SCAN_BR; } } hci_dev_unlock_bh(hdev); hci_dev_put(hdev); } static int start_discovery(struct sock *sk, u16 index) { struct hci_cp_inquiry cp = {{0x33, 0x8b, 0x9e}, 8, 0}; struct hci_dev *hdev; struct pending_cmd *cmd; int err; BT_DBG(""); hdev = hci_dev_get(index); if (!hdev) return cmd_status(sk, index, MGMT_OP_START_DISCOVERY, ENODEV); BT_DBG("disco_state: %d", hdev->disco_state); hci_dev_lock_bh(hdev); if (hdev->disco_state && timer_pending(&hdev->disco_timer)) { err = -EBUSY; goto failed; } cmd = mgmt_pending_add(sk, MGMT_OP_START_DISCOVERY, index, NULL, 0); if (!cmd) { err = -ENOMEM; goto failed; } /* If LE Capable, we will alternate between BR/EDR and LE */ if (lmp_le_capable(hdev)) { struct hci_cp_le_set_scan_parameters le_cp; /* Shorten BR scan params */ cp.num_rsp = 1; cp.length /= 2; /* Setup LE scan params */ memset(&le_cp, 0, sizeof(le_cp)); le_cp.type = 0x01; /* Active scanning */ /* The recommended value for scan interval and window is * 11.25 msec. It is calculated by: time = n * 0.625 msec */ le_cp.interval = cpu_to_le16(0x0012); le_cp.window = cpu_to_le16(0x0012); le_cp.own_bdaddr_type = 0; /* Public address */ le_cp.filter = 0; /* Accept all adv packets */ hci_send_cmd(hdev, HCI_OP_LE_SET_SCAN_PARAMETERS, sizeof(le_cp), &le_cp); } err = hci_send_cmd(hdev, HCI_OP_INQUIRY, sizeof(cp), &cp); if (err < 0) { mgmt_pending_remove(cmd); hdev->disco_state = SCAN_IDLE; } else if (lmp_le_capable(hdev)) { cmd = mgmt_pending_find(MGMT_OP_STOP_DISCOVERY, index); if (!cmd) mgmt_pending_add(sk, MGMT_OP_STOP_DISCOVERY, index, NULL, 0); hdev->disco_int_phase = 1; hdev->disco_int_count = 0; hdev->disco_state = SCAN_BR; del_timer(&hdev->disco_le_timer); del_timer(&hdev->disco_timer); mod_timer(&hdev->disco_timer, jiffies + msecs_to_jiffies(20000)); } else hdev->disco_state = SCAN_BR; failed: hci_dev_unlock_bh(hdev); hci_dev_put(hdev); if (err < 0) return cmd_status(sk, index, MGMT_OP_START_DISCOVERY, -err); return err; } static int stop_discovery(struct sock *sk, u16 index) { struct hci_cp_le_set_scan_enable le_cp = {0, 0}; struct mgmt_mode mode_cp = {0}; struct hci_dev *hdev; struct pending_cmd *cmd = NULL; int err = -EPERM; u8 state; BT_DBG(""); hdev = hci_dev_get(index); if (!hdev) return cmd_status(sk, index, MGMT_OP_STOP_DISCOVERY, ENODEV); BT_DBG("disco_state: %d", hdev->disco_state); hci_dev_lock_bh(hdev); state = hdev->disco_state; hdev->disco_state = SCAN_IDLE; del_timer(&hdev->disco_le_timer); del_timer(&hdev->disco_timer); if (state == SCAN_LE) { err = hci_send_cmd(hdev, HCI_OP_LE_SET_SCAN_ENABLE, sizeof(le_cp), &le_cp); if (err >= 0) { mgmt_pending_foreach(MGMT_OP_STOP_DISCOVERY, index, discovery_terminated, NULL); err = cmd_complete(sk, index, MGMT_OP_STOP_DISCOVERY, NULL, 0); } } else if (state == SCAN_BR) err = hci_send_cmd(hdev, HCI_OP_INQUIRY_CANCEL, 0, NULL); cmd = mgmt_pending_find(MGMT_OP_STOP_DISCOVERY, index); if (err < 0 && cmd) mgmt_pending_remove(cmd); mgmt_event(MGMT_EV_DISCOVERING, index, &mode_cp, sizeof(mode_cp), NULL); hci_dev_unlock_bh(hdev); hci_dev_put(hdev); if (err < 0) return cmd_status(sk, index, MGMT_OP_STOP_DISCOVERY, -err); else return err; } static int read_local_oob_data(struct sock *sk, u16 index) { struct hci_dev *hdev; struct pending_cmd *cmd; int err; BT_DBG("hci%u", index); hdev = hci_dev_get(index); if (!hdev) return cmd_status(sk, index, MGMT_OP_READ_LOCAL_OOB_DATA, ENODEV); hci_dev_lock_bh(hdev); if (!test_bit(HCI_UP, &hdev->flags)) { err = cmd_status(sk, index, MGMT_OP_READ_LOCAL_OOB_DATA, ENETDOWN); goto unlock; } if (!(hdev->features[6] & LMP_SIMPLE_PAIR)) { err = cmd_status(sk, index, MGMT_OP_READ_LOCAL_OOB_DATA, EOPNOTSUPP); goto unlock; } if (mgmt_pending_find(MGMT_OP_READ_LOCAL_OOB_DATA, index)) { err = cmd_status(sk, index, MGMT_OP_READ_LOCAL_OOB_DATA, EBUSY); goto unlock; } cmd = mgmt_pending_add(sk, MGMT_OP_READ_LOCAL_OOB_DATA, index, NULL, 0); if (!cmd) { err = -ENOMEM; goto unlock; } err = hci_send_cmd(hdev, HCI_OP_READ_LOCAL_OOB_DATA, 0, NULL); if (err < 0) mgmt_pending_remove(cmd); unlock: hci_dev_unlock_bh(hdev); hci_dev_put(hdev); return err; } static int add_remote_oob_data(struct sock *sk, u16 index, unsigned char *data, u16 len) { struct hci_dev *hdev; struct mgmt_cp_add_remote_oob_data *cp = (void *) data; int err; BT_DBG("hci%u ", index); if (len != sizeof(*cp)) return cmd_status(sk, index, MGMT_OP_ADD_REMOTE_OOB_DATA, EINVAL); hdev = hci_dev_get(index); if (!hdev) return cmd_status(sk, index, MGMT_OP_ADD_REMOTE_OOB_DATA, ENODEV); hci_dev_lock_bh(hdev); err = hci_add_remote_oob_data(hdev, &cp->bdaddr, cp->hash, cp->randomizer); if (err < 0) err = cmd_status(sk, index, MGMT_OP_ADD_REMOTE_OOB_DATA, -err); else err = cmd_complete(sk, index, MGMT_OP_ADD_REMOTE_OOB_DATA, NULL, 0); hci_dev_unlock_bh(hdev); hci_dev_put(hdev); return err; } static int remove_remote_oob_data(struct sock *sk, u16 index, unsigned char *data, u16 len) { struct hci_dev *hdev; struct mgmt_cp_remove_remote_oob_data *cp = (void *) data; int err; BT_DBG("hci%u ", index); if (len != sizeof(*cp)) return cmd_status(sk, index, MGMT_OP_REMOVE_REMOTE_OOB_DATA, EINVAL); hdev = hci_dev_get(index); if (!hdev) return cmd_status(sk, index, MGMT_OP_REMOVE_REMOTE_OOB_DATA, ENODEV); hci_dev_lock_bh(hdev); err = hci_remove_remote_oob_data(hdev, &cp->bdaddr); if (err < 0) err = cmd_status(sk, index, MGMT_OP_REMOVE_REMOTE_OOB_DATA, -err); else err = cmd_complete(sk, index, MGMT_OP_REMOVE_REMOTE_OOB_DATA, NULL, 0); hci_dev_unlock_bh(hdev); hci_dev_put(hdev); return err; } int mgmt_control(struct sock *sk, struct msghdr *msg, size_t msglen) { unsigned char *buf; struct mgmt_hdr *hdr; u16 opcode, index, len; int err; BT_DBG("got %zu bytes", msglen); if (msglen < sizeof(*hdr)) return -EINVAL; buf = kmalloc(msglen, GFP_KERNEL); if (!buf) return -ENOMEM; if (memcpy_fromiovec(buf, msg->msg_iov, msglen)) { err = -EFAULT; goto done; } hdr = (struct mgmt_hdr *) buf; opcode = get_unaligned_le16(&hdr->opcode); index = get_unaligned_le16(&hdr->index); len = get_unaligned_le16(&hdr->len); if (len != msglen - sizeof(*hdr)) { err = -EINVAL; goto done; } BT_DBG("got opcode %x", opcode); switch (opcode) { case MGMT_OP_READ_VERSION: err = read_version(sk); break; case MGMT_OP_READ_INDEX_LIST: err = read_index_list(sk); break; case MGMT_OP_READ_INFO: err = read_controller_info(sk, index); break; case MGMT_OP_SET_POWERED: err = set_powered(sk, index, buf + sizeof(*hdr), len); break; case MGMT_OP_SET_DISCOVERABLE: err = set_discoverable(sk, index, buf + sizeof(*hdr), len); break; case MGMT_OP_SET_LIMIT_DISCOVERABLE: err = set_limited_discoverable(sk, index, buf + sizeof(*hdr), len); break; case MGMT_OP_SET_CONNECTABLE: err = set_connectable(sk, index, buf + sizeof(*hdr), len); break; case MGMT_OP_SET_PAIRABLE: err = set_pairable(sk, index, buf + sizeof(*hdr), len); break; case MGMT_OP_ADD_UUID: err = add_uuid(sk, index, buf + sizeof(*hdr), len); break; case MGMT_OP_REMOVE_UUID: err = remove_uuid(sk, index, buf + sizeof(*hdr), len); break; case MGMT_OP_SET_DEV_CLASS: err = set_dev_class(sk, index, buf + sizeof(*hdr), len); break; case MGMT_OP_SET_SERVICE_CACHE: err = set_service_cache(sk, index, buf + sizeof(*hdr), len); break; case MGMT_OP_LOAD_KEYS: err = load_keys(sk, index, buf + sizeof(*hdr), len); break; case MGMT_OP_REMOVE_KEY: err = remove_key(sk, index, buf + sizeof(*hdr), len); break; case MGMT_OP_DISCONNECT: err = disconnect(sk, index, buf + sizeof(*hdr), len); break; case MGMT_OP_GET_CONNECTIONS: err = get_connections(sk, index); break; case MGMT_OP_PIN_CODE_REPLY: err = pin_code_reply(sk, index, buf + sizeof(*hdr), len); break; case MGMT_OP_PIN_CODE_NEG_REPLY: err = pin_code_neg_reply(sk, index, buf + sizeof(*hdr), len); break; case MGMT_OP_SET_IO_CAPABILITY: err = set_io_capability(sk, index, buf + sizeof(*hdr), len); break; case MGMT_OP_PAIR_DEVICE: err = pair_device(sk, index, buf + sizeof(*hdr), len); break; case MGMT_OP_USER_CONFIRM_REPLY: case MGMT_OP_USER_PASSKEY_REPLY: case MGMT_OP_USER_CONFIRM_NEG_REPLY: err = user_confirm_reply(sk, index, buf + sizeof(*hdr), len, opcode); break; case MGMT_OP_SET_LOCAL_NAME: err = set_local_name(sk, index, buf + sizeof(*hdr), len); break; case MGMT_OP_START_DISCOVERY: err = start_discovery(sk, index); break; case MGMT_OP_STOP_DISCOVERY: err = stop_discovery(sk, index); break; case MGMT_OP_RESOLVE_NAME: err = resolve_name(sk, index, buf + sizeof(*hdr), len); break; case MGMT_OP_CANCEL_RESOLVE_NAME: err = cancel_resolve_name(sk, index, buf + sizeof(*hdr), len); break; case MGMT_OP_SET_CONNECTION_PARAMS: err = set_connection_params(sk, index, buf + sizeof(*hdr), len); break; case MGMT_OP_SET_RSSI_REPORTER: err = set_rssi_reporter(sk, index, buf + sizeof(*hdr), len); break; case MGMT_OP_UNSET_RSSI_REPORTER: err = unset_rssi_reporter(sk, index, buf + sizeof(*hdr), len); break; case MGMT_OP_READ_LOCAL_OOB_DATA: err = read_local_oob_data(sk, index); break; case MGMT_OP_ADD_REMOTE_OOB_DATA: err = add_remote_oob_data(sk, index, buf + sizeof(*hdr), len); break; case MGMT_OP_REMOVE_REMOTE_OOB_DATA: err = remove_remote_oob_data(sk, index, buf + sizeof(*hdr), len); break; case MGMT_OP_ENCRYPT_LINK: err = encrypt_link(sk, index, buf + sizeof(*hdr), len); break; case MGMT_OP_LE_ADD_DEV_WHITE_LIST: err = le_add_dev_white_list(sk, index, buf + sizeof(*hdr), len); break; case MGMT_OP_LE_REMOVE_DEV_WHITE_LIST: err = le_remove_dev_white_list(sk, index, buf + sizeof(*hdr), len); break; case MGMT_OP_LE_CLEAR_WHITE_LIST: err = le_clear_white_list(sk, index); break; case MGMT_OP_LE_CREATE_CONN_WHITE_LIST: err = le_create_conn_white_list(sk, index); break; case MGMT_OP_LE_CANCEL_CREATE_CONN_WHITE_LIST: err = le_cancel_create_conn_white_list(sk, index); break; case MGMT_OP_LE_CANCEL_CREATE_CONN: err = le_cancel_create_conn(sk, index, buf + sizeof(*hdr), len); break; case MGMT_OP_READ_TX_POWER_LEVEL: err = read_tx_power_level(sk, index, buf + sizeof(*hdr), len); break; default: BT_DBG("Unknown op %u", opcode); err = cmd_status(sk, index, opcode, 0x01); break; } if (err < 0) goto done; err = msglen; done: kfree(buf); return err; } static void cmd_status_rsp(struct pending_cmd *cmd, void *data) { u8 *status = data; cmd_status(cmd->sk, cmd->index, cmd->opcode, *status); mgmt_pending_remove(cmd); } int mgmt_index_added(u16 index) { BT_DBG("%d", index); return mgmt_event(MGMT_EV_INDEX_ADDED, index, NULL, 0, NULL); } int mgmt_index_removed(u16 index) { u8 status = ENODEV; BT_DBG("%d", index); mgmt_pending_foreach(0, index, cmd_status_rsp, &status); return mgmt_event(MGMT_EV_INDEX_REMOVED, index, NULL, 0, NULL); } struct cmd_lookup { u8 val; struct sock *sk; }; static void mode_rsp(struct pending_cmd *cmd, void *data) { struct mgmt_mode *cp = cmd->param; struct cmd_lookup *match = data; if (cp->val != match->val) return; send_mode_rsp(cmd->sk, cmd->opcode, cmd->index, cp->val); list_del(&cmd->list); if (match->sk == NULL) { match->sk = cmd->sk; sock_hold(match->sk); } mgmt_pending_free(cmd); } int mgmt_powered(u16 index, u8 powered) { struct mgmt_mode ev; struct cmd_lookup match = { powered, NULL }; int ret; BT_DBG("hci%u %d", index, powered); mgmt_pending_foreach(MGMT_OP_SET_POWERED, index, mode_rsp, &match); if (!powered) { u8 status = ENETDOWN; mgmt_pending_foreach(0, index, cmd_status_rsp, &status); } ev.val = powered; ret = mgmt_event(MGMT_EV_POWERED, index, &ev, sizeof(ev), match.sk); if (match.sk) sock_put(match.sk); return ret; } int mgmt_set_powered_failed(struct hci_dev *hdev, int err) { struct pending_cmd *cmd; u8 status; cmd = mgmt_pending_find(MGMT_OP_SET_POWERED, hdev->id); if (!cmd) return -ENOENT; if (err == -ERFKILL) status = MGMT_STATUS_RFKILLED; else status = MGMT_STATUS_FAILED; err = cmd_status(cmd->sk, hdev->id, MGMT_OP_SET_POWERED, status); mgmt_pending_remove(cmd); return err; } int mgmt_discoverable(u16 index, u8 discoverable) { struct mgmt_mode ev; struct cmd_lookup match = { discoverable, NULL }; int ret; mgmt_pending_foreach(MGMT_OP_SET_DISCOVERABLE, index, mode_rsp, &match); ev.val = discoverable; ret = mgmt_event(MGMT_EV_DISCOVERABLE, index, &ev, sizeof(ev), match.sk); if (match.sk) sock_put(match.sk); return ret; } int mgmt_connectable(u16 index, u8 connectable) { struct mgmt_mode ev; struct cmd_lookup match = { connectable, NULL }; int ret; mgmt_pending_foreach(MGMT_OP_SET_CONNECTABLE, index, mode_rsp, &match); ev.val = connectable; ret = mgmt_event(MGMT_EV_CONNECTABLE, index, &ev, sizeof(ev), match.sk); if (match.sk) sock_put(match.sk); return ret; } int mgmt_new_key(u16 index, struct link_key *key, u8 bonded) { struct mgmt_ev_new_key *ev; int err, total; total = sizeof(struct mgmt_ev_new_key) + key->dlen; ev = kzalloc(total, GFP_ATOMIC); if (!ev) return -ENOMEM; bacpy(&ev->key.bdaddr, &key->bdaddr); ev->key.addr_type = key->addr_type; ev->key.key_type = key->key_type; memcpy(ev->key.val, key->val, 16); ev->key.pin_len = key->pin_len; ev->key.auth = key->auth; ev->store_hint = bonded; ev->key.dlen = key->dlen; memcpy(ev->key.data, key->data, key->dlen); err = mgmt_event(MGMT_EV_NEW_KEY, index, ev, total, NULL); kfree(ev); return err; } int mgmt_connected(u16 index, bdaddr_t *bdaddr, u8 le) { struct mgmt_ev_connected ev; struct pending_cmd *cmd; struct hci_dev *hdev; BT_DBG("hci%u", index); hdev = hci_dev_get(index); if (!hdev) return -ENODEV; bacpy(&ev.bdaddr, bdaddr); ev.le = le; cmd = mgmt_pending_find(MGMT_OP_LE_CREATE_CONN_WHITE_LIST, index); if (cmd) { BT_ERR("mgmt_connected remove mgmt pending white_list"); mgmt_pending_remove(cmd); } return mgmt_event(MGMT_EV_CONNECTED, index, &ev, sizeof(ev), NULL); } int mgmt_le_conn_params(u16 index, bdaddr_t *bdaddr, u16 interval, u16 latency, u16 timeout) { struct mgmt_ev_le_conn_params ev; bacpy(&ev.bdaddr, bdaddr); ev.interval = interval; ev.latency = latency; ev.timeout = timeout; return mgmt_event(MGMT_EV_LE_CONN_PARAMS, index, &ev, sizeof(ev), NULL); } static void disconnect_rsp(struct pending_cmd *cmd, void *data) { struct mgmt_cp_disconnect *cp = cmd->param; struct sock **sk = data; struct mgmt_rp_disconnect rp; bacpy(&rp.bdaddr, &cp->bdaddr); cmd_complete(cmd->sk, cmd->index, MGMT_OP_DISCONNECT, &rp, sizeof(rp)); *sk = cmd->sk; sock_hold(*sk); mgmt_pending_remove(cmd); } int mgmt_disconnected(u16 index, bdaddr_t *bdaddr, u8 reason) { struct mgmt_ev_disconnected ev; struct sock *sk = NULL; int err; bacpy(&ev.bdaddr, bdaddr); ev.reason = reason; err = mgmt_event(MGMT_EV_DISCONNECTED, index, &ev, sizeof(ev), sk); if (sk) sock_put(sk); mgmt_pending_foreach(MGMT_OP_DISCONNECT, index, disconnect_rsp, &sk); return err; } int mgmt_disconnect_failed(u16 index) { struct pending_cmd *cmd; int err; cmd = mgmt_pending_find(MGMT_OP_DISCONNECT, index); if (!cmd) return -ENOENT; err = cmd_status(cmd->sk, index, MGMT_OP_DISCONNECT, EIO); mgmt_pending_remove(cmd); return err; } int mgmt_connect_failed(u16 index, bdaddr_t *bdaddr, u8 status) { struct mgmt_ev_connect_failed ev; bacpy(&ev.bdaddr, bdaddr); ev.status = status; return mgmt_event(MGMT_EV_CONNECT_FAILED, index, &ev, sizeof(ev), NULL); } int mgmt_pin_code_request(u16 index, bdaddr_t *bdaddr) { struct mgmt_ev_pin_code_request ev; BT_DBG("hci%u", index); bacpy(&ev.bdaddr, bdaddr); ev.secure = 0; return mgmt_event(MGMT_EV_PIN_CODE_REQUEST, index, &ev, sizeof(ev), NULL); } int mgmt_pin_code_reply_complete(u16 index, bdaddr_t *bdaddr, u8 status) { struct pending_cmd *cmd; struct mgmt_rp_pin_code_reply rp; int err; cmd = mgmt_pending_find(MGMT_OP_PIN_CODE_REPLY, index); if (!cmd) return -ENOENT; bacpy(&rp.bdaddr, bdaddr); rp.status = status; err = cmd_complete(cmd->sk, index, MGMT_OP_PIN_CODE_REPLY, &rp, sizeof(rp)); mgmt_pending_remove(cmd); return err; } int mgmt_pin_code_neg_reply_complete(u16 index, bdaddr_t *bdaddr, u8 status) { struct pending_cmd *cmd; struct mgmt_rp_pin_code_reply rp; int err; cmd = mgmt_pending_find(MGMT_OP_PIN_CODE_NEG_REPLY, index); if (!cmd) return -ENOENT; bacpy(&rp.bdaddr, bdaddr); rp.status = status; err = cmd_complete(cmd->sk, index, MGMT_OP_PIN_CODE_NEG_REPLY, &rp, sizeof(rp)); mgmt_pending_remove(cmd); return err; } int mgmt_user_confirm_request(u16 index, u8 event, bdaddr_t *bdaddr, __le32 value) { struct mgmt_ev_user_confirm_request ev; struct hci_conn *conn = NULL; struct hci_dev *hdev; u8 loc_cap, rem_cap, loc_mitm, rem_mitm; BT_DBG("hci%u", index); hdev = hci_dev_get(index); if (!hdev) return -ENODEV; conn = hci_conn_hash_lookup_ba(hdev, ACL_LINK, bdaddr); ev.auto_confirm = 0; if (!conn || event != HCI_EV_USER_CONFIRM_REQUEST) goto no_auto_confirm; loc_cap = (conn->io_capability == 0x04) ? 0x01 : conn->io_capability; rem_cap = conn->remote_cap; loc_mitm = conn->auth_type & 0x01; rem_mitm = conn->remote_auth & 0x01; if ((conn->auth_type & HCI_AT_DEDICATED_BONDING) && conn->auth_initiator && rem_cap == 0x03) ev.auto_confirm = 1; else if (loc_cap == 0x01 && (rem_cap == 0x00 || rem_cap == 0x03)) { if (!loc_mitm && !rem_mitm) value = 0; goto no_auto_confirm; } /* Show bonding dialog if neither side requires no bonding */ if ((conn->auth_type > 0x01) && (conn->remote_auth > 0x01)) { if (!loc_mitm && !rem_mitm) value = 0; goto no_auto_confirm; } if ((!loc_mitm || rem_cap == 0x03) && (!rem_mitm || loc_cap == 0x03)) ev.auto_confirm = 1; no_auto_confirm: bacpy(&ev.bdaddr, bdaddr); ev.event = event; put_unaligned_le32(value, &ev.value); hci_dev_put(hdev); return mgmt_event(MGMT_EV_USER_CONFIRM_REQUEST, index, &ev, sizeof(ev), NULL); } int mgmt_user_passkey_request(u16 index, bdaddr_t *bdaddr) { struct mgmt_ev_user_passkey_request ev; BT_DBG("hci%u", index); bacpy(&ev.bdaddr, bdaddr); return mgmt_event(MGMT_EV_USER_PASSKEY_REQUEST, index, &ev, sizeof(ev), NULL); } static int confirm_reply_complete(u16 index, bdaddr_t *bdaddr, u8 status, u8 opcode) { struct pending_cmd *cmd; struct mgmt_rp_user_confirm_reply rp; int err; cmd = mgmt_pending_find(opcode, index); if (!cmd) return -ENOENT; bacpy(&rp.bdaddr, bdaddr); rp.status = status; err = cmd_complete(cmd->sk, index, opcode, &rp, sizeof(rp)); mgmt_pending_remove(cmd); return err; } int mgmt_user_confirm_reply_complete(u16 index, bdaddr_t *bdaddr, u8 status) { return confirm_reply_complete(index, bdaddr, status, MGMT_OP_USER_CONFIRM_REPLY); } int mgmt_user_confirm_neg_reply_complete(u16 index, bdaddr_t *bdaddr, u8 status) { return confirm_reply_complete(index, bdaddr, status, MGMT_OP_USER_CONFIRM_NEG_REPLY); } int mgmt_auth_failed(u16 index, bdaddr_t *bdaddr, u8 status) { struct mgmt_ev_auth_failed ev; bacpy(&ev.bdaddr, bdaddr); ev.status = status; return mgmt_event(MGMT_EV_AUTH_FAILED, index, &ev, sizeof(ev), NULL); } int mgmt_set_local_name_complete(u16 index, u8 *name, u8 status) { struct pending_cmd *cmd; struct hci_dev *hdev; struct mgmt_cp_set_local_name ev; int err; memset(&ev, 0, sizeof(ev)); memcpy(ev.name, name, HCI_MAX_NAME_LENGTH); cmd = mgmt_pending_find(MGMT_OP_SET_LOCAL_NAME, index); if (!cmd) goto send_event; if (status) { err = cmd_status(cmd->sk, index, MGMT_OP_SET_LOCAL_NAME, EIO); goto failed; } hdev = hci_dev_get(index); if (hdev) { update_eir(hdev); hci_dev_put(hdev); } err = cmd_complete(cmd->sk, index, MGMT_OP_SET_LOCAL_NAME, &ev, sizeof(ev)); if (err < 0) goto failed; send_event: err = mgmt_event(MGMT_EV_LOCAL_NAME_CHANGED, index, &ev, sizeof(ev), cmd ? cmd->sk : NULL); failed: if (cmd) mgmt_pending_remove(cmd); return err; } int mgmt_read_local_oob_data_reply_complete(u16 index, u8 *hash, u8 *randomizer, u8 status) { struct pending_cmd *cmd; int err; BT_DBG("hci%u status %u", index, status); cmd = mgmt_pending_find(MGMT_OP_READ_LOCAL_OOB_DATA, index); if (!cmd) return -ENOENT; if (status) { err = cmd_status(cmd->sk, index, MGMT_OP_READ_LOCAL_OOB_DATA, EIO); } else { struct mgmt_rp_read_local_oob_data rp; memcpy(rp.hash, hash, sizeof(rp.hash)); memcpy(rp.randomizer, randomizer, sizeof(rp.randomizer)); err = cmd_complete(cmd->sk, index, MGMT_OP_READ_LOCAL_OOB_DATA, &rp, sizeof(rp)); } mgmt_pending_remove(cmd); return err; } void mgmt_read_rssi_complete(u16 index, s8 rssi, bdaddr_t *bdaddr, u16 handle, u8 status) { struct mgmt_ev_rssi_update ev; struct hci_conn *conn; struct hci_dev *hdev; if (status) return; hdev = hci_dev_get(index); conn = hci_conn_hash_lookup_handle(hdev, handle); if (!conn) return; BT_DBG("rssi_update_thresh_exceed : %d ", conn->rssi_update_thresh_exceed); BT_DBG("RSSI Threshold : %d , recvd RSSI : %d ", conn->rssi_threshold, rssi); if (conn->rssi_update_thresh_exceed == 1) { BT_DBG("rssi_update_thresh_exceed == 1"); if (rssi > conn->rssi_threshold) { memset(&ev, 0, sizeof(ev)); bacpy(&ev.bdaddr, bdaddr); ev.rssi = rssi; mgmt_event(MGMT_EV_RSSI_UPDATE, index, &ev, sizeof(ev), NULL); } else { hci_conn_set_rssi_reporter(conn, conn->rssi_threshold, conn->rssi_update_interval, conn->rssi_update_thresh_exceed); } } else { BT_DBG("rssi_update_thresh_exceed == 0"); if (rssi < conn->rssi_threshold) { memset(&ev, 0, sizeof(ev)); bacpy(&ev.bdaddr, bdaddr); ev.rssi = rssi; mgmt_event(MGMT_EV_RSSI_UPDATE, index, &ev, sizeof(ev), NULL); } else { hci_conn_set_rssi_reporter(conn, conn->rssi_threshold, conn->rssi_update_interval, conn->rssi_update_thresh_exceed); } } } int mgmt_read_tx_power_failed(u16 index) { struct pending_cmd *cmd; int err; cmd = mgmt_pending_find(MGMT_OP_READ_TX_POWER_LEVEL, index); if (!cmd) return -ENOENT; err = cmd_status(cmd->sk, index, MGMT_OP_READ_TX_POWER_LEVEL, EIO); mgmt_pending_remove(cmd); return err; } int mgmt_read_tx_power_complete(u16 index, bdaddr_t *bdaddr, s8 level, u8 status) { struct pending_cmd *cmd; struct mgmt_rp_read_tx_power_level rp; int err; cmd = mgmt_pending_find(MGMT_OP_READ_TX_POWER_LEVEL, index); if (!cmd) return -ENOENT; bacpy(&rp.bdaddr, bdaddr); rp.status = status; rp.level = level; err = cmd_complete(cmd->sk, index, MGMT_OP_READ_TX_POWER_LEVEL, &rp, sizeof(rp)); mgmt_pending_remove(cmd); return err; } int mgmt_device_found(u16 index, bdaddr_t *bdaddr, u8 link_type, u8 addr_type, u8 le, u8 *dev_class, s8 rssi, u8 eir_len, u8 *eir) { struct mgmt_ev_device_found ev; struct hci_dev *hdev; int err; BT_DBG("le: %d", le); memset(&ev, 0, sizeof(ev)); bacpy(&ev.addr.bdaddr, bdaddr); ev.addr.type = link_to_mgmt(link_type, addr_type); ev.rssi = rssi; ev.le = le; if (dev_class) memcpy(ev.dev_class, dev_class, sizeof(ev.dev_class)); if (eir && eir_len) memcpy(ev.eir, eir, eir_len); err = mgmt_event(MGMT_EV_DEVICE_FOUND, index, &ev, sizeof(ev), NULL); if (err < 0) return err; hdev = hci_dev_get(index); if (!hdev) return 0; if (hdev->disco_state == SCAN_IDLE) goto done; hdev->disco_int_count++; if (hdev->disco_int_count >= hdev->disco_int_phase) { /* Inquiry scan for General Discovery LAP */ struct hci_cp_inquiry cp = {{0x33, 0x8b, 0x9e}, 4, 0}; struct hci_cp_le_set_scan_enable le_cp = {0, 0}; hdev->disco_int_phase *= 2; hdev->disco_int_count = 0; if (hdev->disco_state == SCAN_LE) { /* cancel LE scan */ hci_send_cmd(hdev, HCI_OP_LE_SET_SCAN_ENABLE, sizeof(le_cp), &le_cp); /* start BR scan */ cp.num_rsp = (u8) hdev->disco_int_phase; hci_send_cmd(hdev, HCI_OP_INQUIRY, sizeof(cp), &cp); hdev->disco_state = SCAN_BR; del_timer_sync(&hdev->disco_le_timer); } } done: hci_dev_put(hdev); return 0; } int mgmt_remote_name(u16 index, bdaddr_t *bdaddr, u8 status, u8 *name) { struct mgmt_ev_remote_name ev; memset(&ev, 0, sizeof(ev)); bacpy(&ev.bdaddr, bdaddr); ev.status = status; memcpy(ev.name, name, HCI_MAX_NAME_LENGTH); return mgmt_event(MGMT_EV_REMOTE_NAME, index, &ev, sizeof(ev), NULL); } int mgmt_encrypt_change(u16 index, bdaddr_t *bdaddr, u8 status) { struct mgmt_ev_encrypt_change ev; BT_DBG("hci%u", index); bacpy(&ev.bdaddr, bdaddr); ev.status = status; return mgmt_event(MGMT_EV_ENCRYPT_CHANGE, index, &ev, sizeof(ev), NULL); } int mgmt_remote_class(u16 index, bdaddr_t *bdaddr, u8 dev_class[3]) { struct mgmt_ev_remote_class ev; memset(&ev, 0, sizeof(ev)); bacpy(&ev.bdaddr, bdaddr); memcpy(ev.dev_class, dev_class, 3); return mgmt_event(MGMT_EV_REMOTE_CLASS, index, &ev, sizeof(ev), NULL); } int mgmt_remote_version(u16 index, bdaddr_t *bdaddr, u8 ver, u16 mnf, u16 sub_ver) { struct mgmt_ev_remote_version ev; memset(&ev, 0, sizeof(ev)); bacpy(&ev.bdaddr, bdaddr); ev.lmp_ver = ver; ev.manufacturer = mnf; ev.lmp_subver = sub_ver; return mgmt_event(MGMT_EV_REMOTE_VERSION, index, &ev, sizeof(ev), NULL); } int mgmt_remote_features(u16 index, bdaddr_t *bdaddr, u8 features[8]) { struct mgmt_ev_remote_features ev; memset(&ev, 0, sizeof(ev)); bacpy(&ev.bdaddr, bdaddr); memcpy(ev.features, features, sizeof(ev.features)); return mgmt_event(MGMT_EV_REMOTE_FEATURES, index, &ev, sizeof(ev), NULL); }
Java
/* * Copyright (C) 2013 Apple 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: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef NetworkProcessPlatformStrategies_h #define NetworkProcessPlatformStrategies_h #include <WebCore/LoaderStrategy.h> #include <WebCore/PlatformStrategies.h> namespace WebKit { class NetworkProcessPlatformStrategies : public WebCore::PlatformStrategies { public: static void initialize(); private: // WebCore::PlatformStrategies WebCore::CookiesStrategy* createCookiesStrategy() override; WebCore::LoaderStrategy* createLoaderStrategy() override; WebCore::PasteboardStrategy* createPasteboardStrategy() override; WebCore::PluginStrategy* createPluginStrategy() override; WebCore::BlobRegistry* createBlobRegistry() override; }; } // namespace WebKit #endif // NetworkProcessPlatformStrategies_h
Java
cmd_arch/arm/vfp/entry.o := /home/milind/toolchain/arm-eabi-4.6/bin/arm-eabi-gcc -Wp,-MD,arch/arm/vfp/.entry.o.d -nostdinc -isystem /home/milind/toolchain/arm-eabi-4.6/bin/../lib/gcc/arm-eabi/4.6.x-google/include -I/home/milind/work/kernel/android_kernel_samsung_i9082/arch/arm/include -Iarch/arm/include/generated -Iinclude -include include/generated/autoconf.h -D__KERNEL__ -mlittle-endian -Iarch/arm/mach-capri/include -Iarch/arm/plat-kona/include -D__ASSEMBLY__ -mabi=aapcs-linux -mno-thumb-interwork -funwind-tables -D__LINUX_ARM_ARCH__=7 -march=armv7-a -include asm/unified.h -mfpu=vfp3 -mfloat-abi=softfp -gdwarf-2 -c -o arch/arm/vfp/entry.o arch/arm/vfp/entry.S source_arch/arm/vfp/entry.o := arch/arm/vfp/entry.S deps_arch/arm/vfp/entry.o := \ $(wildcard include/config/preempt.h) \ /home/milind/work/kernel/android_kernel_samsung_i9082/arch/arm/include/asm/unified.h \ $(wildcard include/config/arm/asm/unified.h) \ $(wildcard include/config/thumb2/kernel.h) \ /home/milind/work/kernel/android_kernel_samsung_i9082/arch/arm/include/asm/thread_info.h \ $(wildcard include/config/arm/thumbee.h) \ include/linux/compiler.h \ $(wildcard include/config/sparse/rcu/pointer.h) \ $(wildcard include/config/trace/branch/profiling.h) \ $(wildcard include/config/profile/all/branches.h) \ $(wildcard include/config/enable/must/check.h) \ $(wildcard include/config/enable/warn/deprecated.h) \ /home/milind/work/kernel/android_kernel_samsung_i9082/arch/arm/include/asm/fpstate.h \ $(wildcard include/config/vfpv3.h) \ $(wildcard include/config/smp.h) \ $(wildcard include/config/iwmmxt.h) \ /home/milind/work/kernel/android_kernel_samsung_i9082/arch/arm/include/asm/vfpmacros.h \ /home/milind/work/kernel/android_kernel_samsung_i9082/arch/arm/include/asm/hwcap.h \ /home/milind/work/kernel/android_kernel_samsung_i9082/arch/arm/include/asm/vfp.h \ arch/arm/vfp/../kernel/entry-header.S \ $(wildcard include/config/frame/pointer.h) \ $(wildcard include/config/alignment/trap.h) \ $(wildcard include/config/cpu/v6.h) \ $(wildcard include/config/cpu/32v6k.h) \ $(wildcard include/config/have/hw/breakpoint.h) \ include/linux/init.h \ $(wildcard include/config/modules.h) \ $(wildcard include/config/hotplug.h) \ include/linux/linkage.h \ /home/milind/work/kernel/android_kernel_samsung_i9082/arch/arm/include/asm/linkage.h \ /home/milind/work/kernel/android_kernel_samsung_i9082/arch/arm/include/asm/assembler.h \ $(wildcard include/config/cpu/feroceon.h) \ $(wildcard include/config/trace/irqflags.h) \ /home/milind/work/kernel/android_kernel_samsung_i9082/arch/arm/include/asm/ptrace.h \ $(wildcard include/config/cpu/endian/be8.h) \ $(wildcard include/config/arm/thumb.h) \ /home/milind/work/kernel/android_kernel_samsung_i9082/arch/arm/include/asm/domain.h \ $(wildcard include/config/io/36.h) \ $(wildcard include/config/cpu/use/domains.h) \ /home/milind/work/kernel/android_kernel_samsung_i9082/arch/arm/include/asm/asm-offsets.h \ include/generated/asm-offsets.h \ /home/milind/work/kernel/android_kernel_samsung_i9082/arch/arm/include/asm/errno.h \ include/asm-generic/errno.h \ include/asm-generic/errno-base.h \ arch/arm/vfp/entry.o: $(deps_arch/arm/vfp/entry.o) $(deps_arch/arm/vfp/entry.o):
Java
package org.xmlvm.ios; import java.util.*; import org.xmlvm.XMLVMSkeletonOnly; @XMLVMSkeletonOnly public class CFGregorianDate { /* * Variables */ public int year; public byte month; public byte day; public byte hour; public byte minute; public double second; /* * Constructors */ /** Default constructor */ CFGregorianDate() {} /* * Instance methods */ /** * Boolean CFGregorianDateIsValid(CFGregorianDate gdate, CFOptionFlags unitFlags); */ public byte isValid(long unitFlags){ throw new RuntimeException("Stub"); } /** * CFAbsoluteTime CFGregorianDateGetAbsoluteTime(CFGregorianDate gdate, CFTimeZoneRef tz); */ public double getAbsoluteTime(NSTimeZone tz){ throw new RuntimeException("Stub"); } }
Java
/* * synergy -- mouse and keyboard sharing utility * Copyright (C) 2012 Bolton Software Ltd. * Copyright (C) 2012 Nick Bolton * * This package is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * found in the file COPYING that should have accompanied this file. * * This package 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/>. */ #include "IpcClient.h" #include <QTcpSocket> #include <QHostAddress> #include <iostream> #include <QTimer> #include "IpcReader.h" #include "Ipc.h" IpcClient::IpcClient() : m_ReaderStarted(false), m_Enabled(false) { m_Socket = new QTcpSocket(this); connect(m_Socket, SIGNAL(connected()), this, SLOT(connected())); connect(m_Socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(error(QAbstractSocket::SocketError))); m_Reader = new IpcReader(m_Socket); connect(m_Reader, SIGNAL(readLogLine(const QString&)), this, SLOT(handleReadLogLine(const QString&))); } IpcClient::~IpcClient() { } void IpcClient::connected() { char typeBuf[1]; typeBuf[0] = kIpcClientGui; sendHello(); infoMessage("connection established"); } void IpcClient::connectToHost() { m_Enabled = true; infoMessage("connecting to service..."); m_Socket->connectToHost(QHostAddress(QHostAddress::LocalHost), IPC_PORT); if (!m_ReaderStarted) { m_Reader->start(); m_ReaderStarted = true; } } void IpcClient::disconnectFromHost() { infoMessage("service disconnect"); m_Reader->stop(); m_Socket->close(); } void IpcClient::error(QAbstractSocket::SocketError error) { QString text; switch (error) { case 0: text = "connection refused"; break; case 1: text = "remote host closed"; break; default: text = QString("code=%1").arg(error); break; } errorMessage(QString("ipc connection error, %1").arg(text)); QTimer::singleShot(1000, this, SLOT(retryConnect())); } void IpcClient::retryConnect() { if (m_Enabled) { connectToHost(); } } void IpcClient::sendHello() { QDataStream stream(m_Socket); stream.writeRawData(kIpcMsgHello, 4); char typeBuf[1]; typeBuf[0] = kIpcClientGui; stream.writeRawData(typeBuf, 1); } void IpcClient::sendCommand(const QString& command, bool elevate) { QDataStream stream(m_Socket); stream.writeRawData(kIpcMsgCommand, 4); std::string stdStringCommand = command.toStdString(); const char* charCommand = stdStringCommand.c_str(); int length = strlen(charCommand); char lenBuf[4]; intToBytes(length, lenBuf, 4); stream.writeRawData(lenBuf, 4); stream.writeRawData(charCommand, length); char elevateBuf[1]; elevateBuf[0] = elevate ? 1 : 0; stream.writeRawData(elevateBuf, 1); } void IpcClient::handleReadLogLine(const QString& text) { readLogLine(text); } // TODO: qt must have a built in way of converting int to bytes. void IpcClient::intToBytes(int value, char *buffer, int size) { if (size == 1) { buffer[0] = value & 0xff; } else if (size == 2) { buffer[0] = (value >> 8) & 0xff; buffer[1] = value & 0xff; } else if (size == 4) { buffer[0] = (value >> 24) & 0xff; buffer[1] = (value >> 16) & 0xff; buffer[2] = (value >> 8) & 0xff; buffer[3] = value & 0xff; } else { // TODO: other sizes, if needed. } }
Java
#if UNITY_4_3 || UNITY_4_3_0 || UNITY_4_3_1 #define UNITY_4_3 #elif UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2 #define UNITY_4 #elif UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5 #define UNITY_3 #endif using UnityEngine; using UnityEditor; using System.Collections; using ProBuilder2.Common; using ProBuilder2.MeshOperations; using ProBuilder2.EditorEnum; namespace ProBuilder2.Actions { public class ExtrudeFace : Editor { const int EXTRUDE = 100; [MenuItem("Tools/" + pb_Constant.PRODUCT_NAME + "/Geometry/Extrude %#e", false, EXTRUDE + 1)] public static void ExtrudeNoTranslation() { PerformExtrusion(0f); } [MenuItem("Tools/" + pb_Constant.PRODUCT_NAME + "/Geometry/Extrude with Translation %e", false, EXTRUDE)] public static void Extrude() { PerformExtrusion(.25f); } private static void PerformExtrusion(float dist) { SelectMode mode = pb_Editor.instance.GetSelectionMode(); pb_Object[] pbs = pbUtil.GetComponents<pb_Object>(Selection.transforms); #if !UNITY_4_3 Undo.RegisterUndo(pbUtil.GetComponents<pb_Object>(Selection.transforms), "extrude selected."); #else Undo.RecordObjects(pbUtil.GetComponents<pb_Object>(Selection.transforms), "extrude selected."); #endif int extrudedFaceCount = 0; foreach(pb_Object pb in pbs) { switch(mode) { case SelectMode.Face: if(pb.selected_faces.Length < 1) continue; extrudedFaceCount += pb.selected_faces.Length; pb.Extrude(pb.selected_faces, dist); break; case SelectMode.Edge: if(pb.selected_edges.Length < 1) continue; pb_Edge[] newEdges = pb.Extrude(pb.selected_edges, dist, pb_Preferences_Internal.GetBool(pb_Constant.pbPerimeterEdgeExtrusionOnly)); if(newEdges != null) { extrudedFaceCount += pb.selected_edges.Length; pb.selected_edges = newEdges; pb.selected_triangles = pb.SharedTrianglesWithTriangles( pb.selected_edges.ToIntArray() ); } break; } pb.GenerateUV2(true); } if(extrudedFaceCount > 0) { string val = ""; if(mode == SelectMode.Edge) val = (extrudedFaceCount > 1 ? extrudedFaceCount + " Edges" : "Edge"); else val = (extrudedFaceCount > 1 ? extrudedFaceCount + " Faces" : "Face"); pb_Editor_Utility.ShowNotification("Extrude " + val, "Extrudes the selected faces / edges."); } if(pb_Editor.instance) pb_Editor.instance.UpdateSelection(); } } }
Java
/** * OpenKM, Open Document Management System (http://www.openkm.com) * Copyright (c) 2006-2017 Paco Avila & Josep Llort * <p> * No bytes were intentionally harmed during the development of this application. * <p> * 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. * <p> * 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. * <p> * 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. */ package com.openkm.frontend.client.bean; import com.google.gwt.user.client.rpc.IsSerializable; /** * @author jllort * */ public class GWTUserConfig implements IsSerializable { private String user = ""; private String homePath = ""; private String homeType = ""; private String homeNode = ""; /** * GWTUserConfig */ public GWTUserConfig() { } public String getUser() { return user; } public void setUser(String user) { this.user = user; } public String getHomePath() { return homePath; } public void setHomePath(String homePath) { this.homePath = homePath; } public String getHomeType() { return homeType; } public void setHomeType(String homeType) { this.homeType = homeType; } public String getHomeNode() { return homeNode; } public void setHomeNode(String homeNode) { this.homeNode = homeNode; } }
Java
#ifndef __STDDEF #define __STDDEF /* $Id: stddef.h,v 1.1 2002/08/28 23:59:20 drh Exp $ */ #ifndef NULL #define NULL ((void*)0) #endif #define offsetof(ty,mem) ((size_t)((char*)&((ty*)0)->mem - (char*)0)) typedef long ptrdiff_t; #if !defined(_SIZE_T) && !defined(_SIZE_T_) && !defined(_SIZE_T_DEFINED) #define _SIZE_T #define _SIZE_T_ #define _SIZE_T_DEFINED typedef unsigned long size_t; #endif #if !defined(_WCHAR_T) && !defined(_WCHAR_T_) && !defined(_WCHAR_T_DEFINED) #define _WCHAR_T #define _WCHAR_T_ #define _WCHAR_T_DEFINED #if (_WCHAR_T_SIZE + 0) == 1 typedef unsigned char wchar_t; #elif (_WCHAR_T_SIZE + 0) == 2 typedef unsigned short wchar_t; #elif (_WCHAR_T_SIZE + 0) == 4 typedef unsigned int wchar_t; #else typedef unsigned short wchar_t; #endif #endif #endif /* __STDDEF */
Java
/*************************************************************************/ /*! @File @Title System Description Header @Copyright Copyright (c) Imagination Technologies Ltd. All Rights Reserved @Description This header provides system-specific declarations and macros @License Dual MIT/GPLv2 The contents of this file are subject to the MIT license as set out below. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. Alternatively, the contents of this file may be used under the terms of the GNU General Public License Version 2 ("GPL") in which case the provisions of GPL are applicable instead of those above. If you wish to allow use of your version of this file only under the terms of GPL, and not to allow others to use your version of this file under the terms of the MIT license, indicate your decision by deleting the provisions above and replace them with the notice and other provisions required by GPL as set out in the file called "GPL-COPYING" included in this distribution. If you do not delete the provisions above, a recipient may use your version of this file under the terms of either the MIT license or GPL. This License is also included in this distribution in the file called "MIT-COPYING". EXCEPT AS OTHERWISE STATED IN A NEGOTIATED AGREEMENT: (A) THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT; AND (B) IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /**************************************************************************/ #if !defined(__APOLLO_H__) #define __APOLLO_H__ #define TC_SYSTEM_NAME "Rogue Test Chip" /* Valid values for the TC_MEMORY_CONFIG configuration option */ #define TC_MEMORY_LOCAL (1) #define TC_MEMORY_HOST (2) #define TC_MEMORY_HYBRID (3) #define TC_MEMORY_DIRECT_MAPPED (4) #define RGX_TC_CORE_CLOCK_SPEED (90000000) #define RGX_TC_MEM_CLOCK_SPEED (65000000) #if defined(SUPPORT_DISPLAY_CLASS) || defined(SUPPORT_DRM_DC_MODULE) /* Memory reserved for use by the PDP DC. */ #define RGX_TC_RESERVE_DC_MEM_SIZE (32 * 1024 * 1024) #endif #if defined(SUPPORT_ION) /* Memory reserved for use by ion. */ #define RGX_TC_RESERVE_ION_MEM_SIZE (384 * 1024 * 1024) #endif /* Apollo reg on base register 0 */ #define SYS_APOLLO_REG_PCI_BASENUM (0) #define SYS_APOLLO_REG_REGION_SIZE (0x00010000) #define SYS_APOLLO_REG_SYS_OFFSET (0x0000) #define SYS_APOLLO_REG_SYS_SIZE (0x0400) #define SYS_APOLLO_REG_PLL_OFFSET (0x1000) #define SYS_APOLLO_REG_PLL_SIZE (0x0400) #define SYS_APOLLO_REG_HOST_OFFSET (0x4050) #define SYS_APOLLO_REG_HOST_SIZE (0x0014) #define SYS_APOLLO_REG_PDP_OFFSET (0xC000) #define SYS_APOLLO_REG_PDP_SIZE (0x0400) /* Offsets for flashing Apollo PROMs from base 0 */ #define APOLLO_FLASH_STAT_OFFSET (0x4058) #define APOLLO_FLASH_DATA_WRITE_OFFSET (0x4050) #define APOLLO_FLASH_RESET_OFFSET (0x4060) #define APOLLO_FLASH_FIFO_STATUS_MASK (0xF) #define APOLLO_FLASH_FIFO_STATUS_SHIFT (0) #define APOLLO_FLASH_PROGRAM_STATUS_MASK (0xF) #define APOLLO_FLASH_PROGAM_STATUS_SHIFT (16) #define APOLLO_FLASH_PROG_COMPLETE_BIT (0x1) #define APOLLO_FLASH_PROG_PROGRESS_BIT (0x2) #define APOLLO_FLASH_PROG_FAILED_BIT (0x4) #define APOLLO_FLASH_INV_FILETYPE_BIT (0x8) #define APOLLO_FLASH_FIFO_SIZE (8) /* RGX reg on base register 1 */ #define SYS_RGX_REG_PCI_BASENUM (1) #define SYS_RGX_REG_REGION_SIZE (0x00004000) /* Device memory (including HP mapping) on base register 2 */ #define SYS_DEV_MEM_PCI_BASENUM (2) /* number of bytes that are broken */ #define SYS_DEV_MEM_BROKEN_BYTES (1024 * 1024) #define SYS_DEV_MEM_REGION_SIZE (0x40000000 - SYS_DEV_MEM_BROKEN_BYTES) #endif /* if !defined(__APOLLO_H__) */
Java
/* $Id: PDMDevHlp.cpp $ */ /** @file * PDM - Pluggable Device and Driver Manager, Device Helpers. */ /* * Copyright (C) 2006-2015 Oracle Corporation * * This file is part of VirtualBox Open Source Edition (OSE), as * available from http://www.virtualbox.org. This file is free software; * you can redistribute it and/or modify it under the terms of the GNU * General Public License (GPL) as published by the Free Software * Foundation, in version 2 as it comes in the "COPYING" file of the * VirtualBox OSE distribution. VirtualBox OSE is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. */ /******************************************************************************* * Header Files * *******************************************************************************/ #define LOG_GROUP LOG_GROUP_PDM_DEVICE #include "PDMInternal.h" #include <VBox/vmm/pdm.h> #include <VBox/vmm/mm.h> #include <VBox/vmm/hm.h> #include <VBox/vmm/pgm.h> #include <VBox/vmm/iom.h> #ifdef VBOX_WITH_REM # include <VBox/vmm/rem.h> #endif #include <VBox/vmm/dbgf.h> #include <VBox/vmm/vmapi.h> #include <VBox/vmm/vm.h> #include <VBox/vmm/uvm.h> #include <VBox/vmm/vmm.h> #include <VBox/version.h> #include <VBox/log.h> #include <VBox/err.h> #include <iprt/asm.h> #include <iprt/assert.h> #include <iprt/ctype.h> #include <iprt/string.h> #include <iprt/thread.h> #include "dtrace/VBoxVMM.h" #include "PDMInline.h" /******************************************************************************* * Defined Constants And Macros * *******************************************************************************/ /** @def PDM_DEVHLP_DEADLOCK_DETECTION * Define this to enable the deadlock detection when accessing physical memory. */ #if /*defined(DEBUG_bird) ||*/ defined(DOXYGEN_RUNNING) # define PDM_DEVHLP_DEADLOCK_DETECTION /**< @todo enable DevHlp deadlock detection! */ #endif /** * Wrapper around PDMR3LdrGetSymbolRCLazy. */ DECLINLINE(int) pdmR3DevGetSymbolRCLazy(PPDMDEVINS pDevIns, const char *pszSymbol, PRTRCPTR ppvValue) { PVM pVM = pDevIns->Internal.s.pVMR3; if (HMIsEnabled(pVM)) { *ppvValue = NIL_RTRCPTR; return VINF_SUCCESS; } return PDMR3LdrGetSymbolRCLazy(pVM, pDevIns->Internal.s.pDevR3->pReg->szRCMod, pDevIns->Internal.s.pDevR3->pszRCSearchPath, pszSymbol, ppvValue); } /** * Wrapper around PDMR3LdrGetSymbolR0Lazy. */ DECLINLINE(int) pdmR3DevGetSymbolR0Lazy(PPDMDEVINS pDevIns, const char *pszSymbol, PRTR0PTR ppvValue) { return PDMR3LdrGetSymbolR0Lazy(pDevIns->Internal.s.pVMR3, pDevIns->Internal.s.pDevR3->pReg->szR0Mod, pDevIns->Internal.s.pDevR3->pszR0SearchPath, pszSymbol, ppvValue); } /** @name R3 DevHlp * @{ */ /** @interface_method_impl{PDMDEVHLPR3,pfnIOPortRegister} */ static DECLCALLBACK(int) pdmR3DevHlp_IOPortRegister(PPDMDEVINS pDevIns, RTIOPORT Port, RTIOPORT cPorts, RTHCPTR pvUser, PFNIOMIOPORTOUT pfnOut, PFNIOMIOPORTIN pfnIn, PFNIOMIOPORTOUTSTRING pfnOutStr, PFNIOMIOPORTINSTRING pfnInStr, const char *pszDesc) { PDMDEV_ASSERT_DEVINS(pDevIns); LogFlow(("pdmR3DevHlp_IOPortRegister: caller='%s'/%d: Port=%#x cPorts=%#x pvUser=%p pfnOut=%p pfnIn=%p pfnOutStr=%p pfnInStr=%p p32_tszDesc=%p:{%s}\n", pDevIns->pReg->szName, pDevIns->iInstance, Port, cPorts, pvUser, pfnOut, pfnIn, pfnOutStr, pfnInStr, pszDesc, pszDesc)); VM_ASSERT_EMT(pDevIns->Internal.s.pVMR3); #if 0 /** @todo needs a real string cache for this */ if (pDevIns->iInstance > 0) { char *pszDesc2 = MMR3HeapAPrintf(pVM, MM_TAG_PDM_DEVICE_DESC, "%s [%u]", pszDesc, pDevIns->iInstance); if (pszDesc2) pszDesc = pszDesc2; } #endif int rc = IOMR3IOPortRegisterR3(pDevIns->Internal.s.pVMR3, pDevIns, Port, cPorts, pvUser, pfnOut, pfnIn, pfnOutStr, pfnInStr, pszDesc); LogFlow(("pdmR3DevHlp_IOPortRegister: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc)); return rc; } /** @interface_method_impl{PDMDEVHLPR3,pfnIOPortRegisterRC} */ static DECLCALLBACK(int) pdmR3DevHlp_IOPortRegisterRC(PPDMDEVINS pDevIns, RTIOPORT Port, RTIOPORT cPorts, RTRCPTR pvUser, const char *pszOut, const char *pszIn, const char *pszOutStr, const char *pszInStr, const char *pszDesc) { PDMDEV_ASSERT_DEVINS(pDevIns); PVM pVM = pDevIns->Internal.s.pVMR3; VM_ASSERT_EMT(pVM); LogFlow(("pdmR3DevHlp_IOPortRegisterRC: caller='%s'/%d: Port=%#x cPorts=%#x pvUser=%p pszOut=%p:{%s} pszIn=%p:{%s} pszOutStr=%p:{%s} pszInStr=%p:{%s} pszDesc=%p:{%s}\n", pDevIns->pReg->szName, pDevIns->iInstance, Port, cPorts, pvUser, pszOut, pszOut, pszIn, pszIn, pszOutStr, pszOutStr, pszInStr, pszInStr, pszDesc, pszDesc)); /* * Resolve the functions (one of the can be NULL). */ int rc = VINF_SUCCESS; if ( pDevIns->pReg->szRCMod[0] && (pDevIns->pReg->fFlags & PDM_DEVREG_FLAGS_RC) && !HMIsEnabled(pVM)) { RTRCPTR RCPtrIn = NIL_RTRCPTR; if (pszIn) { rc = pdmR3DevGetSymbolRCLazy(pDevIns, pszIn, &RCPtrIn); AssertMsgRC(rc, ("Failed to resolve %s.%s (pszIn)\n", pDevIns->pReg->szRCMod, pszIn)); } RTRCPTR RCPtrOut = NIL_RTRCPTR; if (pszOut && RT_SUCCESS(rc)) { rc = pdmR3DevGetSymbolRCLazy(pDevIns, pszOut, &RCPtrOut); AssertMsgRC(rc, ("Failed to resolve %s.%s (pszOut)\n", pDevIns->pReg->szRCMod, pszOut)); } RTRCPTR RCPtrInStr = NIL_RTRCPTR; if (pszInStr && RT_SUCCESS(rc)) { rc = pdmR3DevGetSymbolRCLazy(pDevIns, pszInStr, &RCPtrInStr); AssertMsgRC(rc, ("Failed to resolve %s.%s (pszInStr)\n", pDevIns->pReg->szRCMod, pszInStr)); } RTRCPTR RCPtrOutStr = NIL_RTRCPTR; if (pszOutStr && RT_SUCCESS(rc)) { rc = pdmR3DevGetSymbolRCLazy(pDevIns, pszOutStr, &RCPtrOutStr); AssertMsgRC(rc, ("Failed to resolve %s.%s (pszOutStr)\n", pDevIns->pReg->szRCMod, pszOutStr)); } if (RT_SUCCESS(rc)) { #if 0 /** @todo needs a real string cache for this */ if (pDevIns->iInstance > 0) { char *pszDesc2 = MMR3HeapAPrintf(pVM, MM_TAG_PDM_DEVICE_DESC, "%s [%u]", pszDesc, pDevIns->iInstance); if (pszDesc2) pszDesc = pszDesc2; } #endif rc = IOMR3IOPortRegisterRC(pVM, pDevIns, Port, cPorts, pvUser, RCPtrOut, RCPtrIn, RCPtrOutStr, RCPtrInStr, pszDesc); } } else if (!HMIsEnabled(pVM)) { AssertMsgFailed(("No RC module for this driver!\n")); rc = VERR_INVALID_PARAMETER; } LogFlow(("pdmR3DevHlp_IOPortRegisterRC: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc)); return rc; } /** @interface_method_impl{PDMDEVHLPR3,pfnIOPortRegisterR0} */ static DECLCALLBACK(int) pdmR3DevHlp_IOPortRegisterR0(PPDMDEVINS pDevIns, RTIOPORT Port, RTIOPORT cPorts, RTR0PTR pvUser, const char *pszOut, const char *pszIn, const char *pszOutStr, const char *pszInStr, const char *pszDesc) { PDMDEV_ASSERT_DEVINS(pDevIns); VM_ASSERT_EMT(pDevIns->Internal.s.pVMR3); LogFlow(("pdmR3DevHlp_IOPortRegisterR0: caller='%s'/%d: Port=%#x cPorts=%#x pvUser=%p pszOut=%p:{%s} pszIn=%p:{%s} pszOutStr=%p:{%s} pszInStr=%p:{%s} pszDesc=%p:{%s}\n", pDevIns->pReg->szName, pDevIns->iInstance, Port, cPorts, pvUser, pszOut, pszOut, pszIn, pszIn, pszOutStr, pszOutStr, pszInStr, pszInStr, pszDesc, pszDesc)); /* * Resolve the functions (one of the can be NULL). */ int rc = VINF_SUCCESS; if ( pDevIns->pReg->szR0Mod[0] && (pDevIns->pReg->fFlags & PDM_DEVREG_FLAGS_R0)) { R0PTRTYPE(PFNIOMIOPORTIN) pfnR0PtrIn = 0; if (pszIn) { rc = pdmR3DevGetSymbolR0Lazy(pDevIns, pszIn, &pfnR0PtrIn); AssertMsgRC(rc, ("Failed to resolve %s.%s (pszIn)\n", pDevIns->pReg->szR0Mod, pszIn)); } R0PTRTYPE(PFNIOMIOPORTOUT) pfnR0PtrOut = 0; if (pszOut && RT_SUCCESS(rc)) { rc = pdmR3DevGetSymbolR0Lazy(pDevIns, pszOut, &pfnR0PtrOut); AssertMsgRC(rc, ("Failed to resolve %s.%s (pszOut)\n", pDevIns->pReg->szR0Mod, pszOut)); } R0PTRTYPE(PFNIOMIOPORTINSTRING) pfnR0PtrInStr = 0; if (pszInStr && RT_SUCCESS(rc)) { rc = pdmR3DevGetSymbolR0Lazy(pDevIns, pszInStr, &pfnR0PtrInStr); AssertMsgRC(rc, ("Failed to resolve %s.%s (pszInStr)\n", pDevIns->pReg->szR0Mod, pszInStr)); } R0PTRTYPE(PFNIOMIOPORTOUTSTRING) pfnR0PtrOutStr = 0; if (pszOutStr && RT_SUCCESS(rc)) { rc = pdmR3DevGetSymbolR0Lazy(pDevIns, pszOutStr, &pfnR0PtrOutStr); AssertMsgRC(rc, ("Failed to resolve %s.%s (pszOutStr)\n", pDevIns->pReg->szR0Mod, pszOutStr)); } if (RT_SUCCESS(rc)) { #if 0 /** @todo needs a real string cache for this */ if (pDevIns->iInstance > 0) { char *pszDesc2 = MMR3HeapAPrintf(pVM, MM_TAG_PDM_DEVICE_DESC, "%s [%u]", pszDesc, pDevIns->iInstance); if (pszDesc2) pszDesc = pszDesc2; } #endif rc = IOMR3IOPortRegisterR0(pDevIns->Internal.s.pVMR3, pDevIns, Port, cPorts, pvUser, pfnR0PtrOut, pfnR0PtrIn, pfnR0PtrOutStr, pfnR0PtrInStr, pszDesc); } } else { AssertMsgFailed(("No R0 module for this driver!\n")); rc = VERR_INVALID_PARAMETER; } LogFlow(("pdmR3DevHlp_IOPortRegisterR0: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc)); return rc; } /** @interface_method_impl{PDMDEVHLPR3,pfnIOPortDeregister} */ static DECLCALLBACK(int) pdmR3DevHlp_IOPortDeregister(PPDMDEVINS pDevIns, RTIOPORT Port, RTIOPORT cPorts) { PDMDEV_ASSERT_DEVINS(pDevIns); VM_ASSERT_EMT(pDevIns->Internal.s.pVMR3); LogFlow(("pdmR3DevHlp_IOPortDeregister: caller='%s'/%d: Port=%#x cPorts=%#x\n", pDevIns->pReg->szName, pDevIns->iInstance, Port, cPorts)); int rc = IOMR3IOPortDeregister(pDevIns->Internal.s.pVMR3, pDevIns, Port, cPorts); LogFlow(("pdmR3DevHlp_IOPortDeregister: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc)); return rc; } /** @interface_method_impl{PDMDEVHLPR3,pfnMMIORegister} */ static DECLCALLBACK(int) pdmR3DevHlp_MMIORegister(PPDMDEVINS pDevIns, RTGCPHYS GCPhysStart, uint32_t cbRange, RTHCPTR pvUser, PFNIOMMMIOWRITE pfnWrite, PFNIOMMMIOREAD pfnRead, PFNIOMMMIOFILL pfnFill, uint32_t fFlags, const char *pszDesc) { PDMDEV_ASSERT_DEVINS(pDevIns); PVM pVM = pDevIns->Internal.s.pVMR3; VM_ASSERT_EMT(pVM); LogFlow(("pdmR3DevHlp_MMIORegister: caller='%s'/%d: GCPhysStart=%RGp cbRange=%#x pvUser=%p pfnWrite=%p pfnRead=%p pfnFill=%p fFlags=%#x pszDesc=%p:{%s}\n", pDevIns->pReg->szName, pDevIns->iInstance, GCPhysStart, cbRange, pvUser, pfnWrite, pfnRead, pfnFill, pszDesc, fFlags, pszDesc)); if (pDevIns->iInstance > 0) { char *pszDesc2 = MMR3HeapAPrintf(pVM, MM_TAG_PDM_DEVICE_DESC, "%s [%u]", pszDesc, pDevIns->iInstance); if (pszDesc2) pszDesc = pszDesc2; } int rc = IOMR3MmioRegisterR3(pVM, pDevIns, GCPhysStart, cbRange, pvUser, pfnWrite, pfnRead, pfnFill, fFlags, pszDesc); LogFlow(("pdmR3DevHlp_MMIORegister: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc)); return rc; } /** @interface_method_impl{PDMDEVHLPR3,pfnMMIORegisterRC} */ static DECLCALLBACK(int) pdmR3DevHlp_MMIORegisterRC(PPDMDEVINS pDevIns, RTGCPHYS GCPhysStart, uint32_t cbRange, RTRCPTR pvUser, const char *pszWrite, const char *pszRead, const char *pszFill) { PDMDEV_ASSERT_DEVINS(pDevIns); PVM pVM = pDevIns->Internal.s.pVMR3; VM_ASSERT_EMT(pVM); LogFlow(("pdmR3DevHlp_MMIORegisterRC: caller='%s'/%d: GCPhysStart=%RGp cbRange=%#x pvUser=%p pszWrite=%p:{%s} pszRead=%p:{%s} pszFill=%p:{%s}\n", pDevIns->pReg->szName, pDevIns->iInstance, GCPhysStart, cbRange, pvUser, pszWrite, pszWrite, pszRead, pszRead, pszFill, pszFill)); /* * Resolve the functions. * Not all function have to present, leave it to IOM to enforce this. */ int rc = VINF_SUCCESS; if ( pDevIns->pReg->szRCMod[0] && (pDevIns->pReg->fFlags & PDM_DEVREG_FLAGS_RC) && !HMIsEnabled(pVM)) { RTRCPTR RCPtrWrite = NIL_RTRCPTR; if (pszWrite) rc = pdmR3DevGetSymbolRCLazy(pDevIns, pszWrite, &RCPtrWrite); RTRCPTR RCPtrRead = NIL_RTRCPTR; int rc2 = VINF_SUCCESS; if (pszRead) rc2 = pdmR3DevGetSymbolRCLazy(pDevIns, pszRead, &RCPtrRead); RTRCPTR RCPtrFill = NIL_RTRCPTR; int rc3 = VINF_SUCCESS; if (pszFill) rc3 = pdmR3DevGetSymbolRCLazy(pDevIns, pszFill, &RCPtrFill); if (RT_SUCCESS(rc) && RT_SUCCESS(rc2) && RT_SUCCESS(rc3)) rc = IOMR3MmioRegisterRC(pVM, pDevIns, GCPhysStart, cbRange, pvUser, RCPtrWrite, RCPtrRead, RCPtrFill); else { AssertMsgRC(rc, ("Failed to resolve %s.%s (pszWrite)\n", pDevIns->pReg->szRCMod, pszWrite)); AssertMsgRC(rc2, ("Failed to resolve %s.%s (pszRead)\n", pDevIns->pReg->szRCMod, pszRead)); AssertMsgRC(rc3, ("Failed to resolve %s.%s (pszFill)\n", pDevIns->pReg->szRCMod, pszFill)); if (RT_FAILURE(rc2) && RT_SUCCESS(rc)) rc = rc2; if (RT_FAILURE(rc3) && RT_SUCCESS(rc)) rc = rc3; } } else if (!HMIsEnabled(pVM)) { AssertMsgFailed(("No RC module for this driver!\n")); rc = VERR_INVALID_PARAMETER; } LogFlow(("pdmR3DevHlp_MMIORegisterRC: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc)); return rc; } /** @interface_method_impl{PDMDEVHLPR3,pfnMMIORegisterR0} */ static DECLCALLBACK(int) pdmR3DevHlp_MMIORegisterR0(PPDMDEVINS pDevIns, RTGCPHYS GCPhysStart, uint32_t cbRange, RTR0PTR pvUser, const char *pszWrite, const char *pszRead, const char *pszFill) { PDMDEV_ASSERT_DEVINS(pDevIns); VM_ASSERT_EMT(pDevIns->Internal.s.pVMR3); LogFlow(("pdmR3DevHlp_MMIORegisterHC: caller='%s'/%d: GCPhysStart=%RGp cbRange=%#x pvUser=%p pszWrite=%p:{%s} pszRead=%p:{%s} pszFill=%p:{%s}\n", pDevIns->pReg->szName, pDevIns->iInstance, GCPhysStart, cbRange, pvUser, pszWrite, pszWrite, pszRead, pszRead, pszFill, pszFill)); /* * Resolve the functions. * Not all function have to present, leave it to IOM to enforce this. */ int rc = VINF_SUCCESS; if ( pDevIns->pReg->szR0Mod[0] && (pDevIns->pReg->fFlags & PDM_DEVREG_FLAGS_R0)) { R0PTRTYPE(PFNIOMMMIOWRITE) pfnR0PtrWrite = 0; if (pszWrite) rc = pdmR3DevGetSymbolR0Lazy(pDevIns, pszWrite, &pfnR0PtrWrite); R0PTRTYPE(PFNIOMMMIOREAD) pfnR0PtrRead = 0; int rc2 = VINF_SUCCESS; if (pszRead) rc2 = pdmR3DevGetSymbolR0Lazy(pDevIns, pszRead, &pfnR0PtrRead); R0PTRTYPE(PFNIOMMMIOFILL) pfnR0PtrFill = 0; int rc3 = VINF_SUCCESS; if (pszFill) rc3 = pdmR3DevGetSymbolR0Lazy(pDevIns, pszFill, &pfnR0PtrFill); if (RT_SUCCESS(rc) && RT_SUCCESS(rc2) && RT_SUCCESS(rc3)) rc = IOMR3MmioRegisterR0(pDevIns->Internal.s.pVMR3, pDevIns, GCPhysStart, cbRange, pvUser, pfnR0PtrWrite, pfnR0PtrRead, pfnR0PtrFill); else { AssertMsgRC(rc, ("Failed to resolve %s.%s (pszWrite)\n", pDevIns->pReg->szR0Mod, pszWrite)); AssertMsgRC(rc2, ("Failed to resolve %s.%s (pszRead)\n", pDevIns->pReg->szR0Mod, pszRead)); AssertMsgRC(rc3, ("Failed to resolve %s.%s (pszFill)\n", pDevIns->pReg->szR0Mod, pszFill)); if (RT_FAILURE(rc2) && RT_SUCCESS(rc)) rc = rc2; if (RT_FAILURE(rc3) && RT_SUCCESS(rc)) rc = rc3; } } else { AssertMsgFailed(("No R0 module for this driver!\n")); rc = VERR_INVALID_PARAMETER; } LogFlow(("pdmR3DevHlp_MMIORegisterR0: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc)); return rc; } /** @interface_method_impl{PDMDEVHLPR3,pfnMMIODeregister} */ static DECLCALLBACK(int) pdmR3DevHlp_MMIODeregister(PPDMDEVINS pDevIns, RTGCPHYS GCPhysStart, uint32_t cbRange) { PDMDEV_ASSERT_DEVINS(pDevIns); VM_ASSERT_EMT(pDevIns->Internal.s.pVMR3); LogFlow(("pdmR3DevHlp_MMIODeregister: caller='%s'/%d: GCPhysStart=%RGp cbRange=%#x\n", pDevIns->pReg->szName, pDevIns->iInstance, GCPhysStart, cbRange)); int rc = IOMR3MmioDeregister(pDevIns->Internal.s.pVMR3, pDevIns, GCPhysStart, cbRange); LogFlow(("pdmR3DevHlp_MMIODeregister: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc)); return rc; } /** * @copydoc PDMDEVHLPR3::pfnMMIO2Register */ static DECLCALLBACK(int) pdmR3DevHlp_MMIO2Register(PPDMDEVINS pDevIns, uint32_t iRegion, RTGCPHYS cb, uint32_t fFlags, void **ppv, const char *pszDesc) { PDMDEV_ASSERT_DEVINS(pDevIns); VM_ASSERT_EMT(pDevIns->Internal.s.pVMR3); LogFlow(("pdmR3DevHlp_MMIO2Register: caller='%s'/%d: iRegion=%#x cb=%#RGp fFlags=%RX32 ppv=%p pszDescp=%p:{%s}\n", pDevIns->pReg->szName, pDevIns->iInstance, iRegion, cb, fFlags, ppv, pszDesc, pszDesc)); /** @todo PGMR3PhysMMIO2Register mangles the description, move it here and * use a real string cache. */ int rc = PGMR3PhysMMIO2Register(pDevIns->Internal.s.pVMR3, pDevIns, iRegion, cb, fFlags, ppv, pszDesc); LogFlow(("pdmR3DevHlp_MMIO2Register: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc)); return rc; } /** * @copydoc PDMDEVHLPR3::pfnMMIO2Deregister */ static DECLCALLBACK(int) pdmR3DevHlp_MMIO2Deregister(PPDMDEVINS pDevIns, uint32_t iRegion) { PDMDEV_ASSERT_DEVINS(pDevIns); VM_ASSERT_EMT(pDevIns->Internal.s.pVMR3); LogFlow(("pdmR3DevHlp_MMIO2Deregister: caller='%s'/%d: iRegion=%#x\n", pDevIns->pReg->szName, pDevIns->iInstance, iRegion)); AssertReturn(iRegion <= UINT8_MAX || iRegion == UINT32_MAX, VERR_INVALID_PARAMETER); int rc = PGMR3PhysMMIO2Deregister(pDevIns->Internal.s.pVMR3, pDevIns, iRegion); LogFlow(("pdmR3DevHlp_MMIO2Deregister: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc)); return rc; } /** * @copydoc PDMDEVHLPR3::pfnMMIO2Map */ static DECLCALLBACK(int) pdmR3DevHlp_MMIO2Map(PPDMDEVINS pDevIns, uint32_t iRegion, RTGCPHYS GCPhys) { PDMDEV_ASSERT_DEVINS(pDevIns); VM_ASSERT_EMT(pDevIns->Internal.s.pVMR3); LogFlow(("pdmR3DevHlp_MMIO2Map: caller='%s'/%d: iRegion=%#x GCPhys=%#RGp\n", pDevIns->pReg->szName, pDevIns->iInstance, iRegion, GCPhys)); int rc = PGMR3PhysMMIO2Map(pDevIns->Internal.s.pVMR3, pDevIns, iRegion, GCPhys); LogFlow(("pdmR3DevHlp_MMIO2Map: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc)); return rc; } /** * @copydoc PDMDEVHLPR3::pfnMMIO2Unmap */ static DECLCALLBACK(int) pdmR3DevHlp_MMIO2Unmap(PPDMDEVINS pDevIns, uint32_t iRegion, RTGCPHYS GCPhys) { PDMDEV_ASSERT_DEVINS(pDevIns); VM_ASSERT_EMT(pDevIns->Internal.s.pVMR3); LogFlow(("pdmR3DevHlp_MMIO2Unmap: caller='%s'/%d: iRegion=%#x GCPhys=%#RGp\n", pDevIns->pReg->szName, pDevIns->iInstance, iRegion, GCPhys)); int rc = PGMR3PhysMMIO2Unmap(pDevIns->Internal.s.pVMR3, pDevIns, iRegion, GCPhys); LogFlow(("pdmR3DevHlp_MMIO2Unmap: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc)); return rc; } /** * @copydoc PDMDEVHLPR3::pfnMMHyperMapMMIO2 */ static DECLCALLBACK(int) pdmR3DevHlp_MMHyperMapMMIO2(PPDMDEVINS pDevIns, uint32_t iRegion, RTGCPHYS off, RTGCPHYS cb, const char *pszDesc, PRTRCPTR pRCPtr) { PDMDEV_ASSERT_DEVINS(pDevIns); PVM pVM = pDevIns->Internal.s.pVMR3; VM_ASSERT_EMT(pVM); LogFlow(("pdmR3DevHlp_MMHyperMapMMIO2: caller='%s'/%d: iRegion=%#x off=%RGp cb=%RGp pszDesc=%p:{%s} pRCPtr=%p\n", pDevIns->pReg->szName, pDevIns->iInstance, iRegion, off, cb, pszDesc, pszDesc, pRCPtr)); if (pDevIns->iInstance > 0) { char *pszDesc2 = MMR3HeapAPrintf(pVM, MM_TAG_PDM_DEVICE_DESC, "%s [%u]", pszDesc, pDevIns->iInstance); if (pszDesc2) pszDesc = pszDesc2; } int rc = MMR3HyperMapMMIO2(pVM, pDevIns, iRegion, off, cb, pszDesc, pRCPtr); LogFlow(("pdmR3DevHlp_MMHyperMapMMIO2: caller='%s'/%d: returns %Rrc *pRCPtr=%RRv\n", pDevIns->pReg->szName, pDevIns->iInstance, rc, *pRCPtr)); return rc; } /** * @copydoc PDMDEVHLPR3::pfnMMIO2MapKernel */ static DECLCALLBACK(int) pdmR3DevHlp_MMIO2MapKernel(PPDMDEVINS pDevIns, uint32_t iRegion, RTGCPHYS off, RTGCPHYS cb, const char *pszDesc, PRTR0PTR pR0Ptr) { PDMDEV_ASSERT_DEVINS(pDevIns); PVM pVM = pDevIns->Internal.s.pVMR3; VM_ASSERT_EMT(pVM); LogFlow(("pdmR3DevHlp_MMIO2MapKernel: caller='%s'/%d: iRegion=%#x off=%RGp cb=%RGp pszDesc=%p:{%s} pR0Ptr=%p\n", pDevIns->pReg->szName, pDevIns->iInstance, iRegion, off, cb, pszDesc, pszDesc, pR0Ptr)); if (pDevIns->iInstance > 0) { char *pszDesc2 = MMR3HeapAPrintf(pVM, MM_TAG_PDM_DEVICE_DESC, "%s [%u]", pszDesc, pDevIns->iInstance); if (pszDesc2) pszDesc = pszDesc2; } int rc = PGMR3PhysMMIO2MapKernel(pVM, pDevIns, iRegion, off, cb, pszDesc, pR0Ptr); LogFlow(("pdmR3DevHlp_MMIO2MapKernel: caller='%s'/%d: returns %Rrc *pR0Ptr=%RHv\n", pDevIns->pReg->szName, pDevIns->iInstance, rc, *pR0Ptr)); return rc; } /** @interface_method_impl{PDMDEVHLPR3,pfnROMRegister} */ static DECLCALLBACK(int) pdmR3DevHlp_ROMRegister(PPDMDEVINS pDevIns, RTGCPHYS GCPhysStart, uint32_t cbRange, const void *pvBinary, uint32_t cbBinary, uint32_t fFlags, const char *pszDesc) { PDMDEV_ASSERT_DEVINS(pDevIns); VM_ASSERT_EMT(pDevIns->Internal.s.pVMR3); LogFlow(("pdmR3DevHlp_ROMRegister: caller='%s'/%d: GCPhysStart=%RGp cbRange=%#x pvBinary=%p cbBinary=%#x fFlags=%#RX32 pszDesc=%p:{%s}\n", pDevIns->pReg->szName, pDevIns->iInstance, GCPhysStart, cbRange, pvBinary, cbBinary, fFlags, pszDesc, pszDesc)); /** @todo can we mangle pszDesc? */ int rc = PGMR3PhysRomRegister(pDevIns->Internal.s.pVMR3, pDevIns, GCPhysStart, cbRange, pvBinary, cbBinary, fFlags, pszDesc); LogFlow(("pdmR3DevHlp_ROMRegister: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc)); return rc; } /** @interface_method_impl{PDMDEVHLPR3,pfnROMProtectShadow} */ static DECLCALLBACK(int) pdmR3DevHlp_ROMProtectShadow(PPDMDEVINS pDevIns, RTGCPHYS GCPhysStart, uint32_t cbRange, PGMROMPROT enmProt) { PDMDEV_ASSERT_DEVINS(pDevIns); LogFlow(("pdmR3DevHlp_ROMProtectShadow: caller='%s'/%d: GCPhysStart=%RGp cbRange=%#x enmProt=%d\n", pDevIns->pReg->szName, pDevIns->iInstance, GCPhysStart, cbRange, enmProt)); int rc = PGMR3PhysRomProtect(pDevIns->Internal.s.pVMR3, GCPhysStart, cbRange, enmProt); LogFlow(("pdmR3DevHlp_ROMProtectShadow: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc)); return rc; } /** @interface_method_impl{PDMDEVHLPR3,pfnSSMRegister} */ static DECLCALLBACK(int) pdmR3DevHlp_SSMRegister(PPDMDEVINS pDevIns, uint32_t uVersion, size_t cbGuess, const char *pszBefore, PFNSSMDEVLIVEPREP pfnLivePrep, PFNSSMDEVLIVEEXEC pfnLiveExec, PFNSSMDEVLIVEVOTE pfnLiveVote, PFNSSMDEVSAVEPREP pfnSavePrep, PFNSSMDEVSAVEEXEC pfnSaveExec, PFNSSMDEVSAVEDONE pfnSaveDone, PFNSSMDEVLOADPREP pfnLoadPrep, PFNSSMDEVLOADEXEC pfnLoadExec, PFNSSMDEVLOADDONE pfnLoadDone) { PDMDEV_ASSERT_DEVINS(pDevIns); VM_ASSERT_EMT(pDevIns->Internal.s.pVMR3); LogFlow(("pdmR3DevHlp_SSMRegister: caller='%s'/%d: uVersion=#x cbGuess=%#x pszBefore=%p:{%s}\n" " pfnLivePrep=%p pfnLiveExec=%p pfnLiveVote=%p pfnSavePrep=%p pfnSaveExec=%p pfnSaveDone=%p pszLoadPrep=%p pfnLoadExec=%p pfnLoadDone=%p\n", pDevIns->pReg->szName, pDevIns->iInstance, uVersion, cbGuess, pszBefore, pszBefore, pfnLivePrep, pfnLiveExec, pfnLiveVote, pfnSavePrep, pfnSaveExec, pfnSaveDone, pfnLoadPrep, pfnLoadExec, pfnLoadDone)); int rc = SSMR3RegisterDevice(pDevIns->Internal.s.pVMR3, pDevIns, pDevIns->pReg->szName, pDevIns->iInstance, uVersion, cbGuess, pszBefore, pfnLivePrep, pfnLiveExec, pfnLiveVote, pfnSavePrep, pfnSaveExec, pfnSaveDone, pfnLoadPrep, pfnLoadExec, pfnLoadDone); LogFlow(("pdmR3DevHlp_SSMRegister: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc)); return rc; } /** @interface_method_impl{PDMDEVHLPR3,pfnTMTimerCreate} */ static DECLCALLBACK(int) pdmR3DevHlp_TMTimerCreate(PPDMDEVINS pDevIns, TMCLOCK enmClock, PFNTMTIMERDEV pfnCallback, void *pvUser, uint32_t fFlags, const char *pszDesc, PPTMTIMERR3 ppTimer) { PDMDEV_ASSERT_DEVINS(pDevIns); PVM pVM = pDevIns->Internal.s.pVMR3; VM_ASSERT_EMT(pVM); LogFlow(("pdmR3DevHlp_TMTimerCreate: caller='%s'/%d: enmClock=%d pfnCallback=%p pvUser=%p fFlags=%#x pszDesc=%p:{%s} ppTimer=%p\n", pDevIns->pReg->szName, pDevIns->iInstance, enmClock, pfnCallback, pvUser, fFlags, pszDesc, pszDesc, ppTimer)); if (pDevIns->iInstance > 0) /** @todo use a string cache here later. */ { char *pszDesc2 = MMR3HeapAPrintf(pVM, MM_TAG_PDM_DEVICE_DESC, "%s [%u]", pszDesc, pDevIns->iInstance); if (pszDesc2) pszDesc = pszDesc2; } int rc = TMR3TimerCreateDevice(pVM, pDevIns, enmClock, pfnCallback, pvUser, fFlags, pszDesc, ppTimer); LogFlow(("pdmR3DevHlp_TMTimerCreate: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc)); return rc; } /** @interface_method_impl{PDMDEVHLPR3,pfnTMUtcNow} */ static DECLCALLBACK(PRTTIMESPEC) pdmR3DevHlp_TMUtcNow(PPDMDEVINS pDevIns, PRTTIMESPEC pTime) { PDMDEV_ASSERT_DEVINS(pDevIns); LogFlow(("pdmR3DevHlp_TMUtcNow: caller='%s'/%d: pTime=%p\n", pDevIns->pReg->szName, pDevIns->iInstance, pTime)); pTime = TMR3UtcNow(pDevIns->Internal.s.pVMR3, pTime); LogFlow(("pdmR3DevHlp_TMUtcNow: caller='%s'/%d: returns %RU64\n", pDevIns->pReg->szName, pDevIns->iInstance, RTTimeSpecGetNano(pTime))); return pTime; } /** @interface_method_impl{PDMDEVHLPR3,pfnTMTimeVirtGet} */ static DECLCALLBACK(uint64_t) pdmR3DevHlp_TMTimeVirtGet(PPDMDEVINS pDevIns) { PDMDEV_ASSERT_DEVINS(pDevIns); LogFlow(("pdmR3DevHlp_TMTimeVirtGet: caller='%s'\n", pDevIns->pReg->szName, pDevIns->iInstance)); uint64_t u64Time = TMVirtualSyncGet(pDevIns->Internal.s.pVMR3); LogFlow(("pdmR3DevHlp_TMTimeVirtGet: caller='%s'/%d: returns %RU64\n", pDevIns->pReg->szName, pDevIns->iInstance, u64Time)); return u64Time; } /** @interface_method_impl{PDMDEVHLPR3,pfnTMTimeVirtGetFreq} */ static DECLCALLBACK(uint64_t) pdmR3DevHlp_TMTimeVirtGetFreq(PPDMDEVINS pDevIns) { PDMDEV_ASSERT_DEVINS(pDevIns); LogFlow(("pdmR3DevHlp_TMTimeVirtGetFreq: caller='%s'\n", pDevIns->pReg->szName, pDevIns->iInstance)); uint64_t u64Freq = TMVirtualGetFreq(pDevIns->Internal.s.pVMR3); LogFlow(("pdmR3DevHlp_TMTimeVirtGetFreq: caller='%s'/%d: returns %RU64\n", pDevIns->pReg->szName, pDevIns->iInstance, u64Freq)); return u64Freq; } /** @interface_method_impl{PDMDEVHLPR3,pfnTMTimeVirtGetNano} */ static DECLCALLBACK(uint64_t) pdmR3DevHlp_TMTimeVirtGetNano(PPDMDEVINS pDevIns) { PDMDEV_ASSERT_DEVINS(pDevIns); LogFlow(("pdmR3DevHlp_TMTimeVirtGetNano: caller='%s'\n", pDevIns->pReg->szName, pDevIns->iInstance)); uint64_t u64Time = TMVirtualGet(pDevIns->Internal.s.pVMR3); uint64_t u64Nano = TMVirtualToNano(pDevIns->Internal.s.pVMR3, u64Time); LogFlow(("pdmR3DevHlp_TMTimeVirtGetNano: caller='%s'/%d: returns %RU64\n", pDevIns->pReg->szName, pDevIns->iInstance, u64Nano)); return u64Nano; } /** @interface_method_impl{PDMDEVHLPR3,pfnGetSupDrvSession} */ static DECLCALLBACK(PSUPDRVSESSION) pdmR3DevHlp_GetSupDrvSession(PPDMDEVINS pDevIns) { PDMDEV_ASSERT_DEVINS(pDevIns); LogFlow(("pdmR3DevHlp_GetSupDrvSession: caller='%s'\n", pDevIns->pReg->szName, pDevIns->iInstance)); PSUPDRVSESSION pSession = pDevIns->Internal.s.pVMR3->pSession; LogFlow(("pdmR3DevHlp_GetSupDrvSession: caller='%s'/%d: returns %#p\n", pDevIns->pReg->szName, pDevIns->iInstance, pSession)); return pSession; } /** @interface_method_impl{PDMDEVHLPR3,pfnPhysRead} */ static DECLCALLBACK(int) pdmR3DevHlp_PhysRead(PPDMDEVINS pDevIns, RTGCPHYS GCPhys, void *pvBuf, size_t cbRead) { PDMDEV_ASSERT_DEVINS(pDevIns); PVM pVM = pDevIns->Internal.s.pVMR3; LogFlow(("pdmR3DevHlp_PhysRead: caller='%s'/%d: GCPhys=%RGp pvBuf=%p cbRead=%#x\n", pDevIns->pReg->szName, pDevIns->iInstance, GCPhys, pvBuf, cbRead)); #if defined(VBOX_STRICT) && defined(PDM_DEVHLP_DEADLOCK_DETECTION) if (!VM_IS_EMT(pVM)) { char szNames[128]; uint32_t cLocks = PDMR3CritSectCountOwned(pVM, szNames, sizeof(szNames)); AssertMsg(cLocks == 0, ("cLocks=%u %s\n", cLocks, szNames)); } #endif VBOXSTRICTRC rcStrict; if (VM_IS_EMT(pVM)) rcStrict = PGMPhysRead(pVM, GCPhys, pvBuf, cbRead, PGMACCESSORIGIN_DEVICE); else rcStrict = PGMR3PhysReadExternal(pVM, GCPhys, pvBuf, cbRead, PGMACCESSORIGIN_DEVICE); AssertMsg(rcStrict == VINF_SUCCESS, ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict))); /** @todo track down the users for this bugger. */ Log(("pdmR3DevHlp_PhysRead: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, VBOXSTRICTRC_VAL(rcStrict) )); return VBOXSTRICTRC_VAL(rcStrict); } /** @interface_method_impl{PDMDEVHLPR3,pfnPhysWrite} */ static DECLCALLBACK(int) pdmR3DevHlp_PhysWrite(PPDMDEVINS pDevIns, RTGCPHYS GCPhys, const void *pvBuf, size_t cbWrite) { PDMDEV_ASSERT_DEVINS(pDevIns); PVM pVM = pDevIns->Internal.s.pVMR3; LogFlow(("pdmR3DevHlp_PhysWrite: caller='%s'/%d: GCPhys=%RGp pvBuf=%p cbWrite=%#x\n", pDevIns->pReg->szName, pDevIns->iInstance, GCPhys, pvBuf, cbWrite)); #if defined(VBOX_STRICT) && defined(PDM_DEVHLP_DEADLOCK_DETECTION) if (!VM_IS_EMT(pVM)) { char szNames[128]; uint32_t cLocks = PDMR3CritSectCountOwned(pVM, szNames, sizeof(szNames)); AssertMsg(cLocks == 0, ("cLocks=%u %s\n", cLocks, szNames)); } #endif VBOXSTRICTRC rcStrict; if (VM_IS_EMT(pVM)) rcStrict = PGMPhysWrite(pVM, GCPhys, pvBuf, cbWrite, PGMACCESSORIGIN_DEVICE); else rcStrict = PGMR3PhysWriteExternal(pVM, GCPhys, pvBuf, cbWrite, PGMACCESSORIGIN_DEVICE); AssertMsg(rcStrict == VINF_SUCCESS, ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict))); /** @todo track down the users for this bugger. */ Log(("pdmR3DevHlp_PhysWrite: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, VBOXSTRICTRC_VAL(rcStrict) )); return VBOXSTRICTRC_VAL(rcStrict); } /** @interface_method_impl{PDMDEVHLPR3,pfnPhysGCPhys2CCPtr} */ static DECLCALLBACK(int) pdmR3DevHlp_PhysGCPhys2CCPtr(PPDMDEVINS pDevIns, RTGCPHYS GCPhys, uint32_t fFlags, void **ppv, PPGMPAGEMAPLOCK pLock) { PDMDEV_ASSERT_DEVINS(pDevIns); PVM pVM = pDevIns->Internal.s.pVMR3; LogFlow(("pdmR3DevHlp_PhysGCPhys2CCPtr: caller='%s'/%d: GCPhys=%RGp fFlags=%#x ppv=%p pLock=%p\n", pDevIns->pReg->szName, pDevIns->iInstance, GCPhys, fFlags, ppv, pLock)); AssertReturn(!fFlags, VERR_INVALID_PARAMETER); #if defined(VBOX_STRICT) && defined(PDM_DEVHLP_DEADLOCK_DETECTION) if (!VM_IS_EMT(pVM)) { char szNames[128]; uint32_t cLocks = PDMR3CritSectCountOwned(pVM, szNames, sizeof(szNames)); AssertMsg(cLocks == 0, ("cLocks=%u %s\n", cLocks, szNames)); } #endif int rc = PGMR3PhysGCPhys2CCPtrExternal(pVM, GCPhys, ppv, pLock); Log(("pdmR3DevHlp_PhysGCPhys2CCPtr: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc)); return rc; } /** @interface_method_impl{PDMDEVHLPR3,pfnPhysGCPhys2CCPtrReadOnly} */ static DECLCALLBACK(int) pdmR3DevHlp_PhysGCPhys2CCPtrReadOnly(PPDMDEVINS pDevIns, RTGCPHYS GCPhys, uint32_t fFlags, const void **ppv, PPGMPAGEMAPLOCK pLock) { PDMDEV_ASSERT_DEVINS(pDevIns); PVM pVM = pDevIns->Internal.s.pVMR3; LogFlow(("pdmR3DevHlp_PhysGCPhys2CCPtrReadOnly: caller='%s'/%d: GCPhys=%RGp fFlags=%#x ppv=%p pLock=%p\n", pDevIns->pReg->szName, pDevIns->iInstance, GCPhys, fFlags, ppv, pLock)); AssertReturn(!fFlags, VERR_INVALID_PARAMETER); #if defined(VBOX_STRICT) && defined(PDM_DEVHLP_DEADLOCK_DETECTION) if (!VM_IS_EMT(pVM)) { char szNames[128]; uint32_t cLocks = PDMR3CritSectCountOwned(pVM, szNames, sizeof(szNames)); AssertMsg(cLocks == 0, ("cLocks=%u %s\n", cLocks, szNames)); } #endif int rc = PGMR3PhysGCPhys2CCPtrReadOnlyExternal(pVM, GCPhys, ppv, pLock); Log(("pdmR3DevHlp_PhysGCPhys2CCPtrReadOnly: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc)); return rc; } /** @interface_method_impl{PDMDEVHLPR3,pfnPhysReleasePageMappingLock} */ static DECLCALLBACK(void) pdmR3DevHlp_PhysReleasePageMappingLock(PPDMDEVINS pDevIns, PPGMPAGEMAPLOCK pLock) { PDMDEV_ASSERT_DEVINS(pDevIns); PVM pVM = pDevIns->Internal.s.pVMR3; LogFlow(("pdmR3DevHlp_PhysReleasePageMappingLock: caller='%s'/%d: pLock=%p\n", pDevIns->pReg->szName, pDevIns->iInstance, pLock)); PGMPhysReleasePageMappingLock(pVM, pLock); Log(("pdmR3DevHlp_PhysReleasePageMappingLock: caller='%s'/%d: returns void\n", pDevIns->pReg->szName, pDevIns->iInstance)); } /** @interface_method_impl{PDMDEVHLPR3,pfnPhysReadGCVirt} */ static DECLCALLBACK(int) pdmR3DevHlp_PhysReadGCVirt(PPDMDEVINS pDevIns, void *pvDst, RTGCPTR GCVirtSrc, size_t cb) { PDMDEV_ASSERT_DEVINS(pDevIns); PVM pVM = pDevIns->Internal.s.pVMR3; VM_ASSERT_EMT(pVM); LogFlow(("pdmR3DevHlp_PhysReadGCVirt: caller='%s'/%d: pvDst=%p GCVirt=%RGv cb=%#x\n", pDevIns->pReg->szName, pDevIns->iInstance, pvDst, GCVirtSrc, cb)); PVMCPU pVCpu = VMMGetCpu(pVM); if (!pVCpu) return VERR_ACCESS_DENIED; #if defined(VBOX_STRICT) && defined(PDM_DEVHLP_DEADLOCK_DETECTION) /** @todo SMP. */ #endif int rc = PGMPhysSimpleReadGCPtr(pVCpu, pvDst, GCVirtSrc, cb); LogFlow(("pdmR3DevHlp_PhysReadGCVirt: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc)); return rc; } /** @interface_method_impl{PDMDEVHLPR3,pfnPhysWriteGCVirt} */ static DECLCALLBACK(int) pdmR3DevHlp_PhysWriteGCVirt(PPDMDEVINS pDevIns, RTGCPTR GCVirtDst, const void *pvSrc, size_t cb) { PDMDEV_ASSERT_DEVINS(pDevIns); PVM pVM = pDevIns->Internal.s.pVMR3; VM_ASSERT_EMT(pVM); LogFlow(("pdmR3DevHlp_PhysWriteGCVirt: caller='%s'/%d: GCVirtDst=%RGv pvSrc=%p cb=%#x\n", pDevIns->pReg->szName, pDevIns->iInstance, GCVirtDst, pvSrc, cb)); PVMCPU pVCpu = VMMGetCpu(pVM); if (!pVCpu) return VERR_ACCESS_DENIED; #if defined(VBOX_STRICT) && defined(PDM_DEVHLP_DEADLOCK_DETECTION) /** @todo SMP. */ #endif int rc = PGMPhysSimpleWriteGCPtr(pVCpu, GCVirtDst, pvSrc, cb); LogFlow(("pdmR3DevHlp_PhysWriteGCVirt: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc)); return rc; } /** @interface_method_impl{PDMDEVHLPR3,pfnPhysGCPtr2GCPhys} */ static DECLCALLBACK(int) pdmR3DevHlp_PhysGCPtr2GCPhys(PPDMDEVINS pDevIns, RTGCPTR GCPtr, PRTGCPHYS pGCPhys) { PDMDEV_ASSERT_DEVINS(pDevIns); PVM pVM = pDevIns->Internal.s.pVMR3; VM_ASSERT_EMT(pVM); LogFlow(("pdmR3DevHlp_PhysGCPtr2GCPhys: caller='%s'/%d: GCPtr=%RGv pGCPhys=%p\n", pDevIns->pReg->szName, pDevIns->iInstance, GCPtr, pGCPhys)); PVMCPU pVCpu = VMMGetCpu(pVM); if (!pVCpu) return VERR_ACCESS_DENIED; #if defined(VBOX_STRICT) && defined(PDM_DEVHLP_DEADLOCK_DETECTION) /** @todo SMP. */ #endif int rc = PGMPhysGCPtr2GCPhys(pVCpu, GCPtr, pGCPhys); LogFlow(("pdmR3DevHlp_PhysGCPtr2GCPhys: caller='%s'/%d: returns %Rrc *pGCPhys=%RGp\n", pDevIns->pReg->szName, pDevIns->iInstance, rc, *pGCPhys)); return rc; } /** @interface_method_impl{PDMDEVHLPR3,pfnMMHeapAlloc} */ static DECLCALLBACK(void *) pdmR3DevHlp_MMHeapAlloc(PPDMDEVINS pDevIns, size_t cb) { PDMDEV_ASSERT_DEVINS(pDevIns); LogFlow(("pdmR3DevHlp_MMHeapAlloc: caller='%s'/%d: cb=%#x\n", pDevIns->pReg->szName, pDevIns->iInstance, cb)); void *pv = MMR3HeapAlloc(pDevIns->Internal.s.pVMR3, MM_TAG_PDM_DEVICE_USER, cb); LogFlow(("pdmR3DevHlp_MMHeapAlloc: caller='%s'/%d: returns %p\n", pDevIns->pReg->szName, pDevIns->iInstance, pv)); return pv; } /** @interface_method_impl{PDMDEVHLPR3,pfnMMHeapAllocZ} */ static DECLCALLBACK(void *) pdmR3DevHlp_MMHeapAllocZ(PPDMDEVINS pDevIns, size_t cb) { PDMDEV_ASSERT_DEVINS(pDevIns); LogFlow(("pdmR3DevHlp_MMHeapAllocZ: caller='%s'/%d: cb=%#x\n", pDevIns->pReg->szName, pDevIns->iInstance, cb)); void *pv = MMR3HeapAllocZ(pDevIns->Internal.s.pVMR3, MM_TAG_PDM_DEVICE_USER, cb); LogFlow(("pdmR3DevHlp_MMHeapAllocZ: caller='%s'/%d: returns %p\n", pDevIns->pReg->szName, pDevIns->iInstance, pv)); return pv; } /** @interface_method_impl{PDMDEVHLPR3,pfnMMHeapFree} */ static DECLCALLBACK(void) pdmR3DevHlp_MMHeapFree(PPDMDEVINS pDevIns, void *pv) { PDMDEV_ASSERT_DEVINS(pDevIns); LogFlow(("pdmR3DevHlp_MMHeapFree: caller='%s'/%d: pv=%p\n", pDevIns->pReg->szName, pDevIns->iInstance, pv)); MMR3HeapFree(pv); LogFlow(("pdmR3DevHlp_MMHeapAlloc: caller='%s'/%d: returns void\n", pDevIns->pReg->szName, pDevIns->iInstance)); } /** @interface_method_impl{PDMDEVHLPR3,pfnVMState} */ static DECLCALLBACK(VMSTATE) pdmR3DevHlp_VMState(PPDMDEVINS pDevIns) { PDMDEV_ASSERT_DEVINS(pDevIns); VMSTATE enmVMState = VMR3GetState(pDevIns->Internal.s.pVMR3); LogFlow(("pdmR3DevHlp_VMState: caller='%s'/%d: returns %d (%s)\n", pDevIns->pReg->szName, pDevIns->iInstance, enmVMState, VMR3GetStateName(enmVMState))); return enmVMState; } /** @interface_method_impl{PDMDEVHLPR3,pfnVMTeleportedAndNotFullyResumedYet} */ static DECLCALLBACK(bool) pdmR3DevHlp_VMTeleportedAndNotFullyResumedYet(PPDMDEVINS pDevIns) { PDMDEV_ASSERT_DEVINS(pDevIns); bool fRc = VMR3TeleportedAndNotFullyResumedYet(pDevIns->Internal.s.pVMR3); LogFlow(("pdmR3DevHlp_VMState: caller='%s'/%d: returns %RTbool\n", pDevIns->pReg->szName, pDevIns->iInstance, fRc)); return fRc; } /** @interface_method_impl{PDMDEVHLPR3,pfnVMSetError} */ static DECLCALLBACK(int) pdmR3DevHlp_VMSetError(PPDMDEVINS pDevIns, int rc, RT_SRC_POS_DECL, const char *pszFormat, ...) { PDMDEV_ASSERT_DEVINS(pDevIns); va_list args; va_start(args, pszFormat); int rc2 = VMSetErrorV(pDevIns->Internal.s.pVMR3, rc, RT_SRC_POS_ARGS, pszFormat, args); Assert(rc2 == rc); NOREF(rc2); va_end(args); return rc; } /** @interface_method_impl{PDMDEVHLPR3,pfnVMSetErrorV} */ static DECLCALLBACK(int) pdmR3DevHlp_VMSetErrorV(PPDMDEVINS pDevIns, int rc, RT_SRC_POS_DECL, const char *pszFormat, va_list va) { PDMDEV_ASSERT_DEVINS(pDevIns); int rc2 = VMSetErrorV(pDevIns->Internal.s.pVMR3, rc, RT_SRC_POS_ARGS, pszFormat, va); Assert(rc2 == rc); NOREF(rc2); return rc; } /** @interface_method_impl{PDMDEVHLPR3,pfnVMSetRuntimeError} */ static DECLCALLBACK(int) pdmR3DevHlp_VMSetRuntimeError(PPDMDEVINS pDevIns, uint32_t fFlags, const char *pszErrorId, const char *pszFormat, ...) { PDMDEV_ASSERT_DEVINS(pDevIns); va_list args; va_start(args, pszFormat); int rc = VMSetRuntimeErrorV(pDevIns->Internal.s.pVMR3, fFlags, pszErrorId, pszFormat, args); va_end(args); return rc; } /** @interface_method_impl{PDMDEVHLPR3,pfnVMSetRuntimeErrorV} */ static DECLCALLBACK(int) pdmR3DevHlp_VMSetRuntimeErrorV(PPDMDEVINS pDevIns, uint32_t fFlags, const char *pszErrorId, const char *pszFormat, va_list va) { PDMDEV_ASSERT_DEVINS(pDevIns); int rc = VMSetRuntimeErrorV(pDevIns->Internal.s.pVMR3, fFlags, pszErrorId, pszFormat, va); return rc; } /** @interface_method_impl{PDMDEVHLPR3,pfnDBGFStopV} */ static DECLCALLBACK(int) pdmR3DevHlp_DBGFStopV(PPDMDEVINS pDevIns, const char *pszFile, unsigned iLine, const char *pszFunction, const char *pszFormat, va_list args) { PDMDEV_ASSERT_DEVINS(pDevIns); #ifdef LOG_ENABLED va_list va2; va_copy(va2, args); LogFlow(("pdmR3DevHlp_DBGFStopV: caller='%s'/%d: pszFile=%p:{%s} iLine=%d pszFunction=%p:{%s} pszFormat=%p:{%s} (%N)\n", pDevIns->pReg->szName, pDevIns->iInstance, pszFile, pszFile, iLine, pszFunction, pszFunction, pszFormat, pszFormat, pszFormat, &va2)); va_end(va2); #endif PVM pVM = pDevIns->Internal.s.pVMR3; VM_ASSERT_EMT(pVM); int rc = DBGFR3EventSrcV(pVM, DBGFEVENT_DEV_STOP, pszFile, iLine, pszFunction, pszFormat, args); if (rc == VERR_DBGF_NOT_ATTACHED) rc = VINF_SUCCESS; LogFlow(("pdmR3DevHlp_DBGFStopV: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc)); return rc; } /** @interface_method_impl{PDMDEVHLPR3,pfnDBGFInfoRegister} */ static DECLCALLBACK(int) pdmR3DevHlp_DBGFInfoRegister(PPDMDEVINS pDevIns, const char *pszName, const char *pszDesc, PFNDBGFHANDLERDEV pfnHandler) { PDMDEV_ASSERT_DEVINS(pDevIns); LogFlow(("pdmR3DevHlp_DBGFInfoRegister: caller='%s'/%d: pszName=%p:{%s} pszDesc=%p:{%s} pfnHandler=%p\n", pDevIns->pReg->szName, pDevIns->iInstance, pszName, pszName, pszDesc, pszDesc, pfnHandler)); PVM pVM = pDevIns->Internal.s.pVMR3; VM_ASSERT_EMT(pVM); int rc = DBGFR3InfoRegisterDevice(pVM, pszName, pszDesc, pfnHandler, pDevIns); LogFlow(("pdmR3DevHlp_DBGFInfoRegister: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc)); return rc; } /** @interface_method_impl{PDMDEVHLPR3,pfnDBGFRegRegister} */ static DECLCALLBACK(int) pdmR3DevHlp_DBGFRegRegister(PPDMDEVINS pDevIns, PCDBGFREGDESC paRegisters) { PDMDEV_ASSERT_DEVINS(pDevIns); LogFlow(("pdmR3DevHlp_DBGFRegRegister: caller='%s'/%d: paRegisters=%p\n", pDevIns->pReg->szName, pDevIns->iInstance, paRegisters)); PVM pVM = pDevIns->Internal.s.pVMR3; VM_ASSERT_EMT(pVM); int rc = DBGFR3RegRegisterDevice(pVM, paRegisters, pDevIns, pDevIns->pReg->szName, pDevIns->iInstance); LogFlow(("pdmR3DevHlp_DBGFRegRegister: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc)); return rc; } /** @interface_method_impl{PDMDEVHLPR3,pfnDBGFTraceBuf} */ static DECLCALLBACK(RTTRACEBUF) pdmR3DevHlp_DBGFTraceBuf(PPDMDEVINS pDevIns) { PDMDEV_ASSERT_DEVINS(pDevIns); RTTRACEBUF hTraceBuf = pDevIns->Internal.s.pVMR3->hTraceBufR3; LogFlow(("pdmR3DevHlp_DBGFTraceBuf: caller='%s'/%d: returns %p\n", pDevIns->pReg->szName, pDevIns->iInstance, hTraceBuf)); return hTraceBuf; } /** @interface_method_impl{PDMDEVHLPR3,pfnSTAMRegister} */ static DECLCALLBACK(void) pdmR3DevHlp_STAMRegister(PPDMDEVINS pDevIns, void *pvSample, STAMTYPE enmType, const char *pszName, STAMUNIT enmUnit, const char *pszDesc) { PDMDEV_ASSERT_DEVINS(pDevIns); PVM pVM = pDevIns->Internal.s.pVMR3; VM_ASSERT_EMT(pVM); STAM_REG(pVM, pvSample, enmType, pszName, enmUnit, pszDesc); NOREF(pVM); } /** @interface_method_impl{PDMDEVHLPR3,pfnSTAMRegisterF} */ static DECLCALLBACK(void) pdmR3DevHlp_STAMRegisterF(PPDMDEVINS pDevIns, void *pvSample, STAMTYPE enmType, STAMVISIBILITY enmVisibility, STAMUNIT enmUnit, const char *pszDesc, const char *pszName, ...) { PDMDEV_ASSERT_DEVINS(pDevIns); PVM pVM = pDevIns->Internal.s.pVMR3; VM_ASSERT_EMT(pVM); va_list args; va_start(args, pszName); int rc = STAMR3RegisterV(pVM, pvSample, enmType, enmVisibility, enmUnit, pszDesc, pszName, args); va_end(args); AssertRC(rc); NOREF(pVM); } /** @interface_method_impl{PDMDEVHLPR3,pfnSTAMRegisterV} */ static DECLCALLBACK(void) pdmR3DevHlp_STAMRegisterV(PPDMDEVINS pDevIns, void *pvSample, STAMTYPE enmType, STAMVISIBILITY enmVisibility, STAMUNIT enmUnit, const char *pszDesc, const char *pszName, va_list args) { PDMDEV_ASSERT_DEVINS(pDevIns); PVM pVM = pDevIns->Internal.s.pVMR3; VM_ASSERT_EMT(pVM); int rc = STAMR3RegisterV(pVM, pvSample, enmType, enmVisibility, enmUnit, pszDesc, pszName, args); AssertRC(rc); NOREF(pVM); } /** @interface_method_impl{PDMDEVHLPR3,pfnPCIRegister} */ static DECLCALLBACK(int) pdmR3DevHlp_PCIRegister(PPDMDEVINS pDevIns, PPCIDEVICE pPciDev) { PDMDEV_ASSERT_DEVINS(pDevIns); PVM pVM = pDevIns->Internal.s.pVMR3; VM_ASSERT_EMT(pVM); LogFlow(("pdmR3DevHlp_PCIRegister: caller='%s'/%d: pPciDev=%p:{.config={%#.256Rhxs}\n", pDevIns->pReg->szName, pDevIns->iInstance, pPciDev, pPciDev->config)); /* * Validate input. */ if (!pPciDev) { Assert(pPciDev); LogFlow(("pdmR3DevHlp_PCIRegister: caller='%s'/%d: returns %Rrc (pPciDev)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER)); return VERR_INVALID_PARAMETER; } if (!pPciDev->config[0] && !pPciDev->config[1]) { Assert(pPciDev->config[0] || pPciDev->config[1]); LogFlow(("pdmR3DevHlp_PCIRegister: caller='%s'/%d: returns %Rrc (vendor)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER)); return VERR_INVALID_PARAMETER; } if (pDevIns->Internal.s.pPciDeviceR3) { /** @todo the PCI device vs. PDM device designed is a bit flawed if we have to * support a PDM device with multiple PCI devices. This might become a problem * when upgrading the chipset for instance because of multiple functions in some * devices... */ AssertMsgFailed(("Only one PCI device per device is currently implemented!\n")); return VERR_PDM_ONE_PCI_FUNCTION_PER_DEVICE; } /* * Choose the PCI bus for the device. * * This is simple. If the device was configured for a particular bus, the PCIBusNo * configuration value will be set. If not the default bus is 0. */ int rc; PPDMPCIBUS pBus = pDevIns->Internal.s.pPciBusR3; if (!pBus) { uint8_t u8Bus; rc = CFGMR3QueryU8Def(pDevIns->Internal.s.pCfgHandle, "PCIBusNo", &u8Bus, 0); AssertLogRelMsgRCReturn(rc, ("Configuration error: PCIBusNo query failed with rc=%Rrc (%s/%d)\n", rc, pDevIns->pReg->szName, pDevIns->iInstance), rc); AssertLogRelMsgReturn(u8Bus < RT_ELEMENTS(pVM->pdm.s.aPciBuses), ("Configuration error: PCIBusNo=%d, max is %d. (%s/%d)\n", u8Bus, RT_ELEMENTS(pVM->pdm.s.aPciBuses), pDevIns->pReg->szName, pDevIns->iInstance), VERR_PDM_NO_PCI_BUS); pBus = pDevIns->Internal.s.pPciBusR3 = &pVM->pdm.s.aPciBuses[u8Bus]; } if (pBus->pDevInsR3) { if (pDevIns->pReg->fFlags & PDM_DEVREG_FLAGS_R0) pDevIns->Internal.s.pPciBusR0 = MMHyperR3ToR0(pVM, pDevIns->Internal.s.pPciBusR3); else pDevIns->Internal.s.pPciBusR0 = NIL_RTR0PTR; if (pDevIns->pReg->fFlags & PDM_DEVREG_FLAGS_RC) pDevIns->Internal.s.pPciBusRC = MMHyperR3ToRC(pVM, pDevIns->Internal.s.pPciBusR3); else pDevIns->Internal.s.pPciBusRC = NIL_RTRCPTR; /* * Check the configuration for PCI device and function assignment. */ int iDev = -1; uint8_t u8Device; rc = CFGMR3QueryU8(pDevIns->Internal.s.pCfgHandle, "PCIDeviceNo", &u8Device); if (RT_SUCCESS(rc)) { AssertMsgReturn(u8Device <= 31, ("Configuration error: PCIDeviceNo=%d, max is 31. (%s/%d)\n", u8Device, pDevIns->pReg->szName, pDevIns->iInstance), VERR_PDM_BAD_PCI_CONFIG); uint8_t u8Function; rc = CFGMR3QueryU8(pDevIns->Internal.s.pCfgHandle, "PCIFunctionNo", &u8Function); AssertMsgRCReturn(rc, ("Configuration error: PCIDeviceNo, but PCIFunctionNo query failed with rc=%Rrc (%s/%d)\n", rc, pDevIns->pReg->szName, pDevIns->iInstance), rc); AssertMsgReturn(u8Function <= 7, ("Configuration error: PCIFunctionNo=%d, max is 7. (%s/%d)\n", u8Function, pDevIns->pReg->szName, pDevIns->iInstance), VERR_PDM_BAD_PCI_CONFIG); iDev = (u8Device << 3) | u8Function; } else if (rc != VERR_CFGM_VALUE_NOT_FOUND) { AssertMsgFailed(("Configuration error: PCIDeviceNo query failed with rc=%Rrc (%s/%d)\n", rc, pDevIns->pReg->szName, pDevIns->iInstance)); return rc; } /* * Call the pci bus device to do the actual registration. */ pdmLock(pVM); rc = pBus->pfnRegisterR3(pBus->pDevInsR3, pPciDev, pDevIns->pReg->szName, iDev); pdmUnlock(pVM); if (RT_SUCCESS(rc)) { pPciDev->pDevIns = pDevIns; pDevIns->Internal.s.pPciDeviceR3 = pPciDev; if (pDevIns->pReg->fFlags & PDM_DEVREG_FLAGS_R0) pDevIns->Internal.s.pPciDeviceR0 = MMHyperR3ToR0(pVM, pPciDev); else pDevIns->Internal.s.pPciDeviceR0 = NIL_RTR0PTR; if (pDevIns->pReg->fFlags & PDM_DEVREG_FLAGS_RC) pDevIns->Internal.s.pPciDeviceRC = MMHyperR3ToRC(pVM, pPciDev); else pDevIns->Internal.s.pPciDeviceRC = NIL_RTRCPTR; Log(("PDM: Registered device '%s'/%d as PCI device %d on bus %d\n", pDevIns->pReg->szName, pDevIns->iInstance, pPciDev->devfn, pDevIns->Internal.s.pPciBusR3->iBus)); } } else { AssertLogRelMsgFailed(("Configuration error: No PCI bus available. This could be related to init order too!\n")); rc = VERR_PDM_NO_PCI_BUS; } LogFlow(("pdmR3DevHlp_PCIRegister: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc)); return rc; } /** @interface_method_impl{PDMDEVHLPR3,pfnPCIIORegionRegister} */ static DECLCALLBACK(int) pdmR3DevHlp_PCIIORegionRegister(PPDMDEVINS pDevIns, int iRegion, uint32_t cbRegion, PCIADDRESSSPACE enmType, PFNPCIIOREGIONMAP pfnCallback) { PDMDEV_ASSERT_DEVINS(pDevIns); PVM pVM = pDevIns->Internal.s.pVMR3; VM_ASSERT_EMT(pVM); LogFlow(("pdmR3DevHlp_PCIIORegionRegister: caller='%s'/%d: iRegion=%d cbRegion=%#x enmType=%d pfnCallback=%p\n", pDevIns->pReg->szName, pDevIns->iInstance, iRegion, cbRegion, enmType, pfnCallback)); /* * Validate input. */ if (iRegion < 0 || iRegion >= PCI_NUM_REGIONS) { Assert(iRegion >= 0 && iRegion < PCI_NUM_REGIONS); LogFlow(("pdmR3DevHlp_PCIIORegionRegister: caller='%s'/%d: returns %Rrc (iRegion)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER)); return VERR_INVALID_PARAMETER; } switch ((int)enmType) { case PCI_ADDRESS_SPACE_IO: /* * Sanity check: don't allow to register more than 32K of the PCI I/O space. */ AssertMsgReturn(cbRegion <= _32K, ("caller='%s'/%d: %#x\n", pDevIns->pReg->szName, pDevIns->iInstance, cbRegion), VERR_INVALID_PARAMETER); break; case PCI_ADDRESS_SPACE_MEM: case PCI_ADDRESS_SPACE_MEM_PREFETCH: case PCI_ADDRESS_SPACE_MEM | PCI_ADDRESS_SPACE_BAR64: case PCI_ADDRESS_SPACE_MEM_PREFETCH | PCI_ADDRESS_SPACE_BAR64: /* * Sanity check: don't allow to register more than 512MB of the PCI MMIO space for * now. If this limit is increased beyond 2GB, adapt the aligned check below as well! */ AssertMsgReturn(cbRegion <= 512 * _1M, ("caller='%s'/%d: %#x\n", pDevIns->pReg->szName, pDevIns->iInstance, cbRegion), VERR_INVALID_PARAMETER); break; default: AssertMsgFailed(("enmType=%#x is unknown\n", enmType)); LogFlow(("pdmR3DevHlp_PCIIORegionRegister: caller='%s'/%d: returns %Rrc (enmType)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER)); return VERR_INVALID_PARAMETER; } if (!pfnCallback) { Assert(pfnCallback); LogFlow(("pdmR3DevHlp_PCIIORegionRegister: caller='%s'/%d: returns %Rrc (callback)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER)); return VERR_INVALID_PARAMETER; } AssertRelease(VMR3GetState(pVM) != VMSTATE_RUNNING); /* * Must have a PCI device registered! */ int rc; PPCIDEVICE pPciDev = pDevIns->Internal.s.pPciDeviceR3; if (pPciDev) { /* * We're currently restricted to page aligned MMIO regions. */ if ( ((enmType & ~(PCI_ADDRESS_SPACE_BAR64 | PCI_ADDRESS_SPACE_MEM_PREFETCH)) == PCI_ADDRESS_SPACE_MEM) && cbRegion != RT_ALIGN_32(cbRegion, PAGE_SIZE)) { Log(("pdmR3DevHlp_PCIIORegionRegister: caller='%s'/%d: aligning cbRegion %#x -> %#x\n", pDevIns->pReg->szName, pDevIns->iInstance, cbRegion, RT_ALIGN_32(cbRegion, PAGE_SIZE))); cbRegion = RT_ALIGN_32(cbRegion, PAGE_SIZE); } /* * For registering PCI MMIO memory or PCI I/O memory, the size of the region must be a power of 2! */ int iLastSet = ASMBitLastSetU32(cbRegion); Assert(iLastSet > 0); uint32_t cbRegionAligned = RT_BIT_32(iLastSet - 1); if (cbRegion > cbRegionAligned) cbRegion = cbRegionAligned * 2; /* round up */ PPDMPCIBUS pBus = pDevIns->Internal.s.pPciBusR3; Assert(pBus); pdmLock(pVM); rc = pBus->pfnIORegionRegisterR3(pBus->pDevInsR3, pPciDev, iRegion, cbRegion, enmType, pfnCallback); pdmUnlock(pVM); } else { AssertMsgFailed(("No PCI device registered!\n")); rc = VERR_PDM_NOT_PCI_DEVICE; } LogFlow(("pdmR3DevHlp_PCIIORegionRegister: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc)); return rc; } /** @interface_method_impl{PDMDEVHLPR3,pfnPCISetConfigCallbacks} */ static DECLCALLBACK(void) pdmR3DevHlp_PCISetConfigCallbacks(PPDMDEVINS pDevIns, PPCIDEVICE pPciDev, PFNPCICONFIGREAD pfnRead, PPFNPCICONFIGREAD ppfnReadOld, PFNPCICONFIGWRITE pfnWrite, PPFNPCICONFIGWRITE ppfnWriteOld) { PDMDEV_ASSERT_DEVINS(pDevIns); PVM pVM = pDevIns->Internal.s.pVMR3; VM_ASSERT_EMT(pVM); LogFlow(("pdmR3DevHlp_PCISetConfigCallbacks: caller='%s'/%d: pPciDev=%p pfnRead=%p ppfnReadOld=%p pfnWrite=%p ppfnWriteOld=%p\n", pDevIns->pReg->szName, pDevIns->iInstance, pPciDev, pfnRead, ppfnReadOld, pfnWrite, ppfnWriteOld)); /* * Validate input and resolve defaults. */ AssertPtr(pfnRead); AssertPtr(pfnWrite); AssertPtrNull(ppfnReadOld); AssertPtrNull(ppfnWriteOld); AssertPtrNull(pPciDev); if (!pPciDev) pPciDev = pDevIns->Internal.s.pPciDeviceR3; AssertReleaseMsg(pPciDev, ("You must register your device first!\n")); PPDMPCIBUS pBus = pDevIns->Internal.s.pPciBusR3; AssertRelease(pBus); AssertRelease(VMR3GetState(pVM) != VMSTATE_RUNNING); /* * Do the job. */ pdmLock(pVM); pBus->pfnSetConfigCallbacksR3(pBus->pDevInsR3, pPciDev, pfnRead, ppfnReadOld, pfnWrite, ppfnWriteOld); pdmUnlock(pVM); LogFlow(("pdmR3DevHlp_PCISetConfigCallbacks: caller='%s'/%d: returns void\n", pDevIns->pReg->szName, pDevIns->iInstance)); } /** @interface_method_impl{PDMDEVHLPR3,pfnPCIPhysRead} */ static DECLCALLBACK(int) pdmR3DevHlp_PCIPhysRead(PPDMDEVINS pDevIns, RTGCPHYS GCPhys, void *pvBuf, size_t cbRead) { PDMDEV_ASSERT_DEVINS(pDevIns); #ifndef PDM_DO_NOT_RESPECT_PCI_BM_BIT /* * Just check the busmaster setting here and forward the request to the generic read helper. */ PPCIDEVICE pPciDev = pDevIns->Internal.s.pPciDeviceR3; AssertReleaseMsg(pPciDev, ("No PCI device registered!\n")); if (!PCIDevIsBusmaster(pPciDev)) { Log(("pdmR3DevHlp_PCIPhysRead: caller='%s'/%d: returns %Rrc - Not bus master! GCPhys=%RGp cbRead=%#zx\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_PDM_NOT_PCI_BUS_MASTER, GCPhys, cbRead)); return VERR_PDM_NOT_PCI_BUS_MASTER; } #endif return pDevIns->pHlpR3->pfnPhysRead(pDevIns, GCPhys, pvBuf, cbRead); } /** @interface_method_impl{PDMDEVHLPR3,pfnPCIPhysRead} */ static DECLCALLBACK(int) pdmR3DevHlp_PCIPhysWrite(PPDMDEVINS pDevIns, RTGCPHYS GCPhys, const void *pvBuf, size_t cbWrite) { PDMDEV_ASSERT_DEVINS(pDevIns); #ifndef PDM_DO_NOT_RESPECT_PCI_BM_BIT /* * Just check the busmaster setting here and forward the request to the generic read helper. */ PPCIDEVICE pPciDev = pDevIns->Internal.s.pPciDeviceR3; AssertReleaseMsg(pPciDev, ("No PCI device registered!\n")); if (!PCIDevIsBusmaster(pPciDev)) { Log(("pdmR3DevHlp_PCIPhysWrite: caller='%s'/%d: returns %Rrc - Not bus master! GCPhys=%RGp cbWrite=%#zx\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_PDM_NOT_PCI_BUS_MASTER, GCPhys, cbWrite)); return VERR_PDM_NOT_PCI_BUS_MASTER; } #endif return pDevIns->pHlpR3->pfnPhysWrite(pDevIns, GCPhys, pvBuf, cbWrite); } /** @interface_method_impl{PDMDEVHLPR3,pfnPCISetIrq} */ static DECLCALLBACK(void) pdmR3DevHlp_PCISetIrq(PPDMDEVINS pDevIns, int iIrq, int iLevel) { PDMDEV_ASSERT_DEVINS(pDevIns); LogFlow(("pdmR3DevHlp_PCISetIrq: caller='%s'/%d: iIrq=%d iLevel=%d\n", pDevIns->pReg->szName, pDevIns->iInstance, iIrq, iLevel)); /* * Validate input. */ Assert(iIrq == 0); Assert((uint32_t)iLevel <= PDM_IRQ_LEVEL_FLIP_FLOP); /* * Must have a PCI device registered! */ PPCIDEVICE pPciDev = pDevIns->Internal.s.pPciDeviceR3; if (pPciDev) { PPDMPCIBUS pBus = pDevIns->Internal.s.pPciBusR3; /** @todo the bus should be associated with the PCI device not the PDM device. */ Assert(pBus); PVM pVM = pDevIns->Internal.s.pVMR3; pdmLock(pVM); uint32_t uTagSrc; if (iLevel & PDM_IRQ_LEVEL_HIGH) { pDevIns->Internal.s.uLastIrqTag = uTagSrc = pdmCalcIrqTag(pVM, pDevIns->idTracing); if (iLevel == PDM_IRQ_LEVEL_HIGH) VBOXVMM_PDM_IRQ_HIGH(VMMGetCpu(pVM), RT_LOWORD(uTagSrc), RT_HIWORD(uTagSrc)); else VBOXVMM_PDM_IRQ_HILO(VMMGetCpu(pVM), RT_LOWORD(uTagSrc), RT_HIWORD(uTagSrc)); } else uTagSrc = pDevIns->Internal.s.uLastIrqTag; pBus->pfnSetIrqR3(pBus->pDevInsR3, pPciDev, iIrq, iLevel, uTagSrc); if (iLevel == PDM_IRQ_LEVEL_LOW) VBOXVMM_PDM_IRQ_LOW(VMMGetCpu(pVM), RT_LOWORD(uTagSrc), RT_HIWORD(uTagSrc)); pdmUnlock(pVM); } else AssertReleaseMsgFailed(("No PCI device registered!\n")); LogFlow(("pdmR3DevHlp_PCISetIrq: caller='%s'/%d: returns void\n", pDevIns->pReg->szName, pDevIns->iInstance)); } /** @interface_method_impl{PDMDEVHLPR3,pfnPCISetIrqNoWait} */ static DECLCALLBACK(void) pdmR3DevHlp_PCISetIrqNoWait(PPDMDEVINS pDevIns, int iIrq, int iLevel) { pdmR3DevHlp_PCISetIrq(pDevIns, iIrq, iLevel); } /** @interface_method_impl{PDMDEVHLPR3,pfnPCIRegisterMsi} */ static DECLCALLBACK(int) pdmR3DevHlp_PCIRegisterMsi(PPDMDEVINS pDevIns, PPDMMSIREG pMsiReg) { PDMDEV_ASSERT_DEVINS(pDevIns); LogFlow(("pdmR3DevHlp_PCIRegisterMsi: caller='%s'/%d: %d MSI vectors %d MSI-X vectors\n", pDevIns->pReg->szName, pDevIns->iInstance, pMsiReg->cMsiVectors,pMsiReg->cMsixVectors )); int rc = VINF_SUCCESS; /* * Must have a PCI device registered! */ PPCIDEVICE pPciDev = pDevIns->Internal.s.pPciDeviceR3; if (pPciDev) { PPDMPCIBUS pBus = pDevIns->Internal.s.pPciBusR3; /** @todo the bus should be associated with the PCI device not the PDM device. */ Assert(pBus); PVM pVM = pDevIns->Internal.s.pVMR3; pdmLock(pVM); if (pBus->pfnRegisterMsiR3) rc = pBus->pfnRegisterMsiR3(pBus->pDevInsR3, pPciDev, pMsiReg); else rc = VERR_NOT_IMPLEMENTED; pdmUnlock(pVM); } else AssertReleaseMsgFailed(("No PCI device registered!\n")); LogFlow(("pdmR3DevHlp_PCISetIrq: caller='%s'/%d: returns void\n", pDevIns->pReg->szName, pDevIns->iInstance)); return rc; } /** @interface_method_impl{PDMDEVHLPR3,pfnISASetIrq} */ static DECLCALLBACK(void) pdmR3DevHlp_ISASetIrq(PPDMDEVINS pDevIns, int iIrq, int iLevel) { PDMDEV_ASSERT_DEVINS(pDevIns); LogFlow(("pdmR3DevHlp_ISASetIrq: caller='%s'/%d: iIrq=%d iLevel=%d\n", pDevIns->pReg->szName, pDevIns->iInstance, iIrq, iLevel)); /* * Validate input. */ Assert(iIrq < 16); Assert((uint32_t)iLevel <= PDM_IRQ_LEVEL_FLIP_FLOP); PVM pVM = pDevIns->Internal.s.pVMR3; /* * Do the job. */ pdmLock(pVM); uint32_t uTagSrc; if (iLevel & PDM_IRQ_LEVEL_HIGH) { pDevIns->Internal.s.uLastIrqTag = uTagSrc = pdmCalcIrqTag(pVM, pDevIns->idTracing); if (iLevel == PDM_IRQ_LEVEL_HIGH) VBOXVMM_PDM_IRQ_HIGH(VMMGetCpu(pVM), RT_LOWORD(uTagSrc), RT_HIWORD(uTagSrc)); else VBOXVMM_PDM_IRQ_HILO(VMMGetCpu(pVM), RT_LOWORD(uTagSrc), RT_HIWORD(uTagSrc)); } else uTagSrc = pDevIns->Internal.s.uLastIrqTag; PDMIsaSetIrq(pVM, iIrq, iLevel, uTagSrc); /* (The API takes the lock recursively.) */ if (iLevel == PDM_IRQ_LEVEL_LOW) VBOXVMM_PDM_IRQ_LOW(VMMGetCpu(pVM), RT_LOWORD(uTagSrc), RT_HIWORD(uTagSrc)); pdmUnlock(pVM); LogFlow(("pdmR3DevHlp_ISASetIrq: caller='%s'/%d: returns void\n", pDevIns->pReg->szName, pDevIns->iInstance)); } /** @interface_method_impl{PDMDEVHLPR3,pfnISASetIrqNoWait} */ static DECLCALLBACK(void) pdmR3DevHlp_ISASetIrqNoWait(PPDMDEVINS pDevIns, int iIrq, int iLevel) { pdmR3DevHlp_ISASetIrq(pDevIns, iIrq, iLevel); } /** @interface_method_impl{PDMDEVHLPR3,pfnDriverAttach} */ static DECLCALLBACK(int) pdmR3DevHlp_DriverAttach(PPDMDEVINS pDevIns, uint32_t iLun, PPDMIBASE pBaseInterface, PPDMIBASE *ppBaseInterface, const char *pszDesc) { PDMDEV_ASSERT_DEVINS(pDevIns); PVM pVM = pDevIns->Internal.s.pVMR3; VM_ASSERT_EMT(pVM); LogFlow(("pdmR3DevHlp_DriverAttach: caller='%s'/%d: iLun=%d pBaseInterface=%p ppBaseInterface=%p pszDesc=%p:{%s}\n", pDevIns->pReg->szName, pDevIns->iInstance, iLun, pBaseInterface, ppBaseInterface, pszDesc, pszDesc)); /* * Lookup the LUN, it might already be registered. */ PPDMLUN pLunPrev = NULL; PPDMLUN pLun = pDevIns->Internal.s.pLunsR3; for (; pLun; pLunPrev = pLun, pLun = pLun->pNext) if (pLun->iLun == iLun) break; /* * Create the LUN if if wasn't found, else check if driver is already attached to it. */ if (!pLun) { if ( !pBaseInterface || !pszDesc || !*pszDesc) { Assert(pBaseInterface); Assert(pszDesc || *pszDesc); return VERR_INVALID_PARAMETER; } pLun = (PPDMLUN)MMR3HeapAlloc(pVM, MM_TAG_PDM_LUN, sizeof(*pLun)); if (!pLun) return VERR_NO_MEMORY; pLun->iLun = iLun; pLun->pNext = pLunPrev ? pLunPrev->pNext : NULL; pLun->pTop = NULL; pLun->pBottom = NULL; pLun->pDevIns = pDevIns; pLun->pUsbIns = NULL; pLun->pszDesc = pszDesc; pLun->pBase = pBaseInterface; if (!pLunPrev) pDevIns->Internal.s.pLunsR3 = pLun; else pLunPrev->pNext = pLun; Log(("pdmR3DevHlp_DriverAttach: Registered LUN#%d '%s' with device '%s'/%d.\n", iLun, pszDesc, pDevIns->pReg->szName, pDevIns->iInstance)); } else if (pLun->pTop) { AssertMsgFailed(("Already attached! The device should keep track of such things!\n")); LogFlow(("pdmR3DevHlp_DriverAttach: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_PDM_DRIVER_ALREADY_ATTACHED)); return VERR_PDM_DRIVER_ALREADY_ATTACHED; } Assert(pLun->pBase == pBaseInterface); /* * Get the attached driver configuration. */ int rc; PCFGMNODE pNode = CFGMR3GetChildF(pDevIns->Internal.s.pCfgHandle, "LUN#%u", iLun); if (pNode) rc = pdmR3DrvInstantiate(pVM, pNode, pBaseInterface, NULL /*pDrvAbove*/, pLun, ppBaseInterface); else rc = VERR_PDM_NO_ATTACHED_DRIVER; LogFlow(("pdmR3DevHlp_DriverAttach: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc)); return rc; } /** @interface_method_impl{PDMDEVHLPR3,pfnQueueCreate} */ static DECLCALLBACK(int) pdmR3DevHlp_QueueCreate(PPDMDEVINS pDevIns, size_t cbItem, uint32_t cItems, uint32_t cMilliesInterval, PFNPDMQUEUEDEV pfnCallback, bool fGCEnabled, const char *pszName, PPDMQUEUE *ppQueue) { PDMDEV_ASSERT_DEVINS(pDevIns); LogFlow(("pdmR3DevHlp_QueueCreate: caller='%s'/%d: cbItem=%#x cItems=%#x cMilliesInterval=%u pfnCallback=%p fGCEnabled=%RTbool pszName=%p:{%s} ppQueue=%p\n", pDevIns->pReg->szName, pDevIns->iInstance, cbItem, cItems, cMilliesInterval, pfnCallback, fGCEnabled, pszName, pszName, ppQueue)); PVM pVM = pDevIns->Internal.s.pVMR3; VM_ASSERT_EMT(pVM); if (pDevIns->iInstance > 0) { pszName = MMR3HeapAPrintf(pVM, MM_TAG_PDM_DEVICE_DESC, "%s_%u", pszName, pDevIns->iInstance); AssertLogRelReturn(pszName, VERR_NO_MEMORY); } int rc = PDMR3QueueCreateDevice(pVM, pDevIns, cbItem, cItems, cMilliesInterval, pfnCallback, fGCEnabled, pszName, ppQueue); LogFlow(("pdmR3DevHlp_QueueCreate: caller='%s'/%d: returns %Rrc *ppQueue=%p\n", pDevIns->pReg->szName, pDevIns->iInstance, rc, *ppQueue)); return rc; } /** @interface_method_impl{PDMDEVHLPR3,pfnCritSectInit} */ static DECLCALLBACK(int) pdmR3DevHlp_CritSectInit(PPDMDEVINS pDevIns, PPDMCRITSECT pCritSect, RT_SRC_POS_DECL, const char *pszNameFmt, va_list va) { PDMDEV_ASSERT_DEVINS(pDevIns); LogFlow(("pdmR3DevHlp_CritSectInit: caller='%s'/%d: pCritSect=%p pszNameFmt=%p:{%s}\n", pDevIns->pReg->szName, pDevIns->iInstance, pCritSect, pszNameFmt, pszNameFmt)); PVM pVM = pDevIns->Internal.s.pVMR3; VM_ASSERT_EMT(pVM); int rc = pdmR3CritSectInitDevice(pVM, pDevIns, pCritSect, RT_SRC_POS_ARGS, pszNameFmt, va); LogFlow(("pdmR3DevHlp_CritSectInit: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc)); return rc; } /** @interface_method_impl{PDMDEVHLPR3,pfnCritSectGetNop} */ static DECLCALLBACK(PPDMCRITSECT) pdmR3DevHlp_CritSectGetNop(PPDMDEVINS pDevIns) { PDMDEV_ASSERT_DEVINS(pDevIns); PVM pVM = pDevIns->Internal.s.pVMR3; VM_ASSERT_EMT(pVM); PPDMCRITSECT pCritSect = PDMR3CritSectGetNop(pVM); LogFlow(("pdmR3DevHlp_CritSectGetNop: caller='%s'/%d: return %p\n", pDevIns->pReg->szName, pDevIns->iInstance, pCritSect)); return pCritSect; } /** @interface_method_impl{PDMDEVHLPR3,pfnCritSectGetNopR0} */ static DECLCALLBACK(R0PTRTYPE(PPDMCRITSECT)) pdmR3DevHlp_CritSectGetNopR0(PPDMDEVINS pDevIns) { PDMDEV_ASSERT_DEVINS(pDevIns); PVM pVM = pDevIns->Internal.s.pVMR3; VM_ASSERT_EMT(pVM); R0PTRTYPE(PPDMCRITSECT) pCritSect = PDMR3CritSectGetNopR0(pVM); LogFlow(("pdmR3DevHlp_CritSectGetNopR0: caller='%s'/%d: return %RHv\n", pDevIns->pReg->szName, pDevIns->iInstance, pCritSect)); return pCritSect; } /** @interface_method_impl{PDMDEVHLPR3,pfnCritSectGetNopRC} */ static DECLCALLBACK(RCPTRTYPE(PPDMCRITSECT)) pdmR3DevHlp_CritSectGetNopRC(PPDMDEVINS pDevIns) { PDMDEV_ASSERT_DEVINS(pDevIns); PVM pVM = pDevIns->Internal.s.pVMR3; VM_ASSERT_EMT(pVM); RCPTRTYPE(PPDMCRITSECT) pCritSect = PDMR3CritSectGetNopRC(pVM); LogFlow(("pdmR3DevHlp_CritSectGetNopRC: caller='%s'/%d: return %RRv\n", pDevIns->pReg->szName, pDevIns->iInstance, pCritSect)); return pCritSect; } /** @interface_method_impl{PDMDEVHLPR3,pfnSetDeviceCritSect} */ static DECLCALLBACK(int) pdmR3DevHlp_SetDeviceCritSect(PPDMDEVINS pDevIns, PPDMCRITSECT pCritSect) { /* * Validate input. * * Note! We only allow the automatically created default critical section * to be replaced by this API. */ PDMDEV_ASSERT_DEVINS(pDevIns); AssertPtrReturn(pCritSect, VERR_INVALID_POINTER); LogFlow(("pdmR3DevHlp_SetDeviceCritSect: caller='%s'/%d: pCritSect=%p (%s)\n", pDevIns->pReg->szName, pDevIns->iInstance, pCritSect, pCritSect->s.pszName)); AssertReturn(PDMCritSectIsInitialized(pCritSect), VERR_INVALID_PARAMETER); PVM pVM = pDevIns->Internal.s.pVMR3; AssertReturn(pCritSect->s.pVMR3 == pVM, VERR_INVALID_PARAMETER); VM_ASSERT_EMT(pVM); VM_ASSERT_STATE_RETURN(pVM, VMSTATE_CREATING, VERR_WRONG_ORDER); AssertReturn(pDevIns->pCritSectRoR3, VERR_PDM_DEV_IPE_1); AssertReturn(pDevIns->pCritSectRoR3->s.fAutomaticDefaultCritsect, VERR_WRONG_ORDER); AssertReturn(!pDevIns->pCritSectRoR3->s.fUsedByTimerOrSimilar, VERR_WRONG_ORDER); AssertReturn(pDevIns->pCritSectRoR3 != pCritSect, VERR_INVALID_PARAMETER); /* * Replace the critical section and destroy the automatic default section. */ PPDMCRITSECT pOldCritSect = pDevIns->pCritSectRoR3; pDevIns->pCritSectRoR3 = pCritSect; if (pDevIns->pReg->fFlags & PDM_DEVREG_FLAGS_R0) pDevIns->pCritSectRoR0 = MMHyperCCToR0(pVM, pDevIns->pCritSectRoR3); else Assert(pDevIns->pCritSectRoR0 == NIL_RTRCPTR); if (pDevIns->pReg->fFlags & PDM_DEVREG_FLAGS_RC) pDevIns->pCritSectRoRC = MMHyperCCToRC(pVM, pDevIns->pCritSectRoR3); else Assert(pDevIns->pCritSectRoRC == NIL_RTRCPTR); PDMR3CritSectDelete(pOldCritSect); if (pDevIns->pReg->fFlags & (PDM_DEVREG_FLAGS_RC | PDM_DEVREG_FLAGS_R0)) MMHyperFree(pVM, pOldCritSect); else MMR3HeapFree(pOldCritSect); LogFlow(("pdmR3DevHlp_SetDeviceCritSect: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, VINF_SUCCESS)); return VINF_SUCCESS; } /** @interface_method_impl{PDMDEVHLPR3,pfnThreadCreate} */ static DECLCALLBACK(int) pdmR3DevHlp_ThreadCreate(PPDMDEVINS pDevIns, PPPDMTHREAD ppThread, void *pvUser, PFNPDMTHREADDEV pfnThread, PFNPDMTHREADWAKEUPDEV pfnWakeup, size_t cbStack, RTTHREADTYPE enmType, const char *pszName) { PDMDEV_ASSERT_DEVINS(pDevIns); VM_ASSERT_EMT(pDevIns->Internal.s.pVMR3); LogFlow(("pdmR3DevHlp_ThreadCreate: caller='%s'/%d: ppThread=%p pvUser=%p pfnThread=%p pfnWakeup=%p cbStack=%#zx enmType=%d pszName=%p:{%s}\n", pDevIns->pReg->szName, pDevIns->iInstance, ppThread, pvUser, pfnThread, pfnWakeup, cbStack, enmType, pszName, pszName)); int rc = pdmR3ThreadCreateDevice(pDevIns->Internal.s.pVMR3, pDevIns, ppThread, pvUser, pfnThread, pfnWakeup, cbStack, enmType, pszName); LogFlow(("pdmR3DevHlp_ThreadCreate: caller='%s'/%d: returns %Rrc *ppThread=%RTthrd\n", pDevIns->pReg->szName, pDevIns->iInstance, rc, *ppThread)); return rc; } /** @interface_method_impl{PDMDEVHLPR3,pfnSetAsyncNotification} */ static DECLCALLBACK(int) pdmR3DevHlp_SetAsyncNotification(PPDMDEVINS pDevIns, PFNPDMDEVASYNCNOTIFY pfnAsyncNotify) { PDMDEV_ASSERT_DEVINS(pDevIns); VM_ASSERT_EMT0(pDevIns->Internal.s.pVMR3); LogFlow(("pdmR3DevHlp_SetAsyncNotification: caller='%s'/%d: pfnAsyncNotify=%p\n", pDevIns->pReg->szName, pDevIns->iInstance, pfnAsyncNotify)); int rc = VINF_SUCCESS; AssertStmt(pfnAsyncNotify, rc = VERR_INVALID_PARAMETER); AssertStmt(!pDevIns->Internal.s.pfnAsyncNotify, rc = VERR_WRONG_ORDER); AssertStmt(pDevIns->Internal.s.fIntFlags & (PDMDEVINSINT_FLAGS_SUSPENDED | PDMDEVINSINT_FLAGS_RESET), rc = VERR_WRONG_ORDER); VMSTATE enmVMState = VMR3GetState(pDevIns->Internal.s.pVMR3); AssertStmt( enmVMState == VMSTATE_SUSPENDING || enmVMState == VMSTATE_SUSPENDING_EXT_LS || enmVMState == VMSTATE_SUSPENDING_LS || enmVMState == VMSTATE_RESETTING || enmVMState == VMSTATE_RESETTING_LS || enmVMState == VMSTATE_POWERING_OFF || enmVMState == VMSTATE_POWERING_OFF_LS, rc = VERR_INVALID_STATE); if (RT_SUCCESS(rc)) pDevIns->Internal.s.pfnAsyncNotify = pfnAsyncNotify; LogFlow(("pdmR3DevHlp_SetAsyncNotification: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc)); return rc; } /** @interface_method_impl{PDMDEVHLPR3,pfnAsyncNotificationCompleted} */ static DECLCALLBACK(void) pdmR3DevHlp_AsyncNotificationCompleted(PPDMDEVINS pDevIns) { PDMDEV_ASSERT_DEVINS(pDevIns); PVM pVM = pDevIns->Internal.s.pVMR3; VMSTATE enmVMState = VMR3GetState(pVM); if ( enmVMState == VMSTATE_SUSPENDING || enmVMState == VMSTATE_SUSPENDING_EXT_LS || enmVMState == VMSTATE_SUSPENDING_LS || enmVMState == VMSTATE_RESETTING || enmVMState == VMSTATE_RESETTING_LS || enmVMState == VMSTATE_POWERING_OFF || enmVMState == VMSTATE_POWERING_OFF_LS) { LogFlow(("pdmR3DevHlp_AsyncNotificationCompleted: caller='%s'/%d:\n", pDevIns->pReg->szName, pDevIns->iInstance)); VMR3AsyncPdmNotificationWakeupU(pVM->pUVM); } else LogFlow(("pdmR3DevHlp_AsyncNotificationCompleted: caller='%s'/%d: enmVMState=%d\n", pDevIns->pReg->szName, pDevIns->iInstance, enmVMState)); } /** @interface_method_impl{PDMDEVHLPR3,pfnRTCRegister} */ static DECLCALLBACK(int) pdmR3DevHlp_RTCRegister(PPDMDEVINS pDevIns, PCPDMRTCREG pRtcReg, PCPDMRTCHLP *ppRtcHlp) { PDMDEV_ASSERT_DEVINS(pDevIns); VM_ASSERT_EMT(pDevIns->Internal.s.pVMR3); LogFlow(("pdmR3DevHlp_RTCRegister: caller='%s'/%d: pRtcReg=%p:{.u32Version=%#x, .pfnWrite=%p, .pfnRead=%p} ppRtcHlp=%p\n", pDevIns->pReg->szName, pDevIns->iInstance, pRtcReg, pRtcReg->u32Version, pRtcReg->pfnWrite, pRtcReg->pfnWrite, ppRtcHlp)); /* * Validate input. */ if (pRtcReg->u32Version != PDM_RTCREG_VERSION) { AssertMsgFailed(("u32Version=%#x expected %#x\n", pRtcReg->u32Version, PDM_RTCREG_VERSION)); LogFlow(("pdmR3DevHlp_RTCRegister: caller='%s'/%d: returns %Rrc (version)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER)); return VERR_INVALID_PARAMETER; } if ( !pRtcReg->pfnWrite || !pRtcReg->pfnRead) { Assert(pRtcReg->pfnWrite); Assert(pRtcReg->pfnRead); LogFlow(("pdmR3DevHlp_RTCRegister: caller='%s'/%d: returns %Rrc (callbacks)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER)); return VERR_INVALID_PARAMETER; } if (!ppRtcHlp) { Assert(ppRtcHlp); LogFlow(("pdmR3DevHlp_RTCRegister: caller='%s'/%d: returns %Rrc (ppRtcHlp)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER)); return VERR_INVALID_PARAMETER; } /* * Only one DMA device. */ PVM pVM = pDevIns->Internal.s.pVMR3; if (pVM->pdm.s.pRtc) { AssertMsgFailed(("Only one RTC device is supported!\n")); LogFlow(("pdmR3DevHlp_RTCRegister: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER)); return VERR_INVALID_PARAMETER; } /* * Allocate and initialize pci bus structure. */ int rc = VINF_SUCCESS; PPDMRTC pRtc = (PPDMRTC)MMR3HeapAlloc(pDevIns->Internal.s.pVMR3, MM_TAG_PDM_DEVICE, sizeof(*pRtc)); if (pRtc) { pRtc->pDevIns = pDevIns; pRtc->Reg = *pRtcReg; pVM->pdm.s.pRtc = pRtc; /* set the helper pointer. */ *ppRtcHlp = &g_pdmR3DevRtcHlp; Log(("PDM: Registered RTC device '%s'/%d pDevIns=%p\n", pDevIns->pReg->szName, pDevIns->iInstance, pDevIns)); } else rc = VERR_NO_MEMORY; LogFlow(("pdmR3DevHlp_RTCRegister: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc)); return rc; } /** @interface_method_impl{PDMDEVHLPR3,pfnDMARegister} */ static DECLCALLBACK(int) pdmR3DevHlp_DMARegister(PPDMDEVINS pDevIns, unsigned uChannel, PFNDMATRANSFERHANDLER pfnTransferHandler, void *pvUser) { PDMDEV_ASSERT_DEVINS(pDevIns); PVM pVM = pDevIns->Internal.s.pVMR3; VM_ASSERT_EMT(pVM); LogFlow(("pdmR3DevHlp_DMARegister: caller='%s'/%d: uChannel=%d pfnTransferHandler=%p pvUser=%p\n", pDevIns->pReg->szName, pDevIns->iInstance, uChannel, pfnTransferHandler, pvUser)); int rc = VINF_SUCCESS; if (pVM->pdm.s.pDmac) pVM->pdm.s.pDmac->Reg.pfnRegister(pVM->pdm.s.pDmac->pDevIns, uChannel, pfnTransferHandler, pvUser); else { AssertMsgFailed(("Configuration error: No DMAC controller available. This could be related to init order too!\n")); rc = VERR_PDM_NO_DMAC_INSTANCE; } LogFlow(("pdmR3DevHlp_DMARegister: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc)); return rc; } /** @interface_method_impl{PDMDEVHLPR3,pfnDMAReadMemory} */ static DECLCALLBACK(int) pdmR3DevHlp_DMAReadMemory(PPDMDEVINS pDevIns, unsigned uChannel, void *pvBuffer, uint32_t off, uint32_t cbBlock, uint32_t *pcbRead) { PDMDEV_ASSERT_DEVINS(pDevIns); PVM pVM = pDevIns->Internal.s.pVMR3; VM_ASSERT_EMT(pVM); LogFlow(("pdmR3DevHlp_DMAReadMemory: caller='%s'/%d: uChannel=%d pvBuffer=%p off=%#x cbBlock=%#x pcbRead=%p\n", pDevIns->pReg->szName, pDevIns->iInstance, uChannel, pvBuffer, off, cbBlock, pcbRead)); int rc = VINF_SUCCESS; if (pVM->pdm.s.pDmac) { uint32_t cb = pVM->pdm.s.pDmac->Reg.pfnReadMemory(pVM->pdm.s.pDmac->pDevIns, uChannel, pvBuffer, off, cbBlock); if (pcbRead) *pcbRead = cb; } else { AssertMsgFailed(("Configuration error: No DMAC controller available. This could be related to init order too!\n")); rc = VERR_PDM_NO_DMAC_INSTANCE; } LogFlow(("pdmR3DevHlp_DMAReadMemory: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc)); return rc; } /** @interface_method_impl{PDMDEVHLPR3,pfnDMAWriteMemory} */ static DECLCALLBACK(int) pdmR3DevHlp_DMAWriteMemory(PPDMDEVINS pDevIns, unsigned uChannel, const void *pvBuffer, uint32_t off, uint32_t cbBlock, uint32_t *pcbWritten) { PDMDEV_ASSERT_DEVINS(pDevIns); PVM pVM = pDevIns->Internal.s.pVMR3; VM_ASSERT_EMT(pVM); LogFlow(("pdmR3DevHlp_DMAWriteMemory: caller='%s'/%d: uChannel=%d pvBuffer=%p off=%#x cbBlock=%#x pcbWritten=%p\n", pDevIns->pReg->szName, pDevIns->iInstance, uChannel, pvBuffer, off, cbBlock, pcbWritten)); int rc = VINF_SUCCESS; if (pVM->pdm.s.pDmac) { uint32_t cb = pVM->pdm.s.pDmac->Reg.pfnWriteMemory(pVM->pdm.s.pDmac->pDevIns, uChannel, pvBuffer, off, cbBlock); if (pcbWritten) *pcbWritten = cb; } else { AssertMsgFailed(("Configuration error: No DMAC controller available. This could be related to init order too!\n")); rc = VERR_PDM_NO_DMAC_INSTANCE; } LogFlow(("pdmR3DevHlp_DMAWriteMemory: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc)); return rc; } /** @interface_method_impl{PDMDEVHLPR3,pfnDMASetDREQ} */ static DECLCALLBACK(int) pdmR3DevHlp_DMASetDREQ(PPDMDEVINS pDevIns, unsigned uChannel, unsigned uLevel) { PDMDEV_ASSERT_DEVINS(pDevIns); PVM pVM = pDevIns->Internal.s.pVMR3; VM_ASSERT_EMT(pVM); LogFlow(("pdmR3DevHlp_DMASetDREQ: caller='%s'/%d: uChannel=%d uLevel=%d\n", pDevIns->pReg->szName, pDevIns->iInstance, uChannel, uLevel)); int rc = VINF_SUCCESS; if (pVM->pdm.s.pDmac) pVM->pdm.s.pDmac->Reg.pfnSetDREQ(pVM->pdm.s.pDmac->pDevIns, uChannel, uLevel); else { AssertMsgFailed(("Configuration error: No DMAC controller available. This could be related to init order too!\n")); rc = VERR_PDM_NO_DMAC_INSTANCE; } LogFlow(("pdmR3DevHlp_DMASetDREQ: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc)); return rc; } /** @interface_method_impl{PDMDEVHLPR3,pfnDMAGetChannelMode} */ static DECLCALLBACK(uint8_t) pdmR3DevHlp_DMAGetChannelMode(PPDMDEVINS pDevIns, unsigned uChannel) { PDMDEV_ASSERT_DEVINS(pDevIns); PVM pVM = pDevIns->Internal.s.pVMR3; VM_ASSERT_EMT(pVM); LogFlow(("pdmR3DevHlp_DMAGetChannelMode: caller='%s'/%d: uChannel=%d\n", pDevIns->pReg->szName, pDevIns->iInstance, uChannel)); uint8_t u8Mode; if (pVM->pdm.s.pDmac) u8Mode = pVM->pdm.s.pDmac->Reg.pfnGetChannelMode(pVM->pdm.s.pDmac->pDevIns, uChannel); else { AssertMsgFailed(("Configuration error: No DMAC controller available. This could be related to init order too!\n")); u8Mode = 3 << 2 /* illegal mode type */; } LogFlow(("pdmR3DevHlp_DMAGetChannelMode: caller='%s'/%d: returns %#04x\n", pDevIns->pReg->szName, pDevIns->iInstance, u8Mode)); return u8Mode; } /** @interface_method_impl{PDMDEVHLPR3,pfnDMASchedule} */ static DECLCALLBACK(void) pdmR3DevHlp_DMASchedule(PPDMDEVINS pDevIns) { PDMDEV_ASSERT_DEVINS(pDevIns); PVM pVM = pDevIns->Internal.s.pVMR3; VM_ASSERT_EMT(pVM); LogFlow(("pdmR3DevHlp_DMASchedule: caller='%s'/%d: VM_FF_PDM_DMA %d -> 1\n", pDevIns->pReg->szName, pDevIns->iInstance, VM_FF_IS_SET(pVM, VM_FF_PDM_DMA))); AssertMsg(pVM->pdm.s.pDmac, ("Configuration error: No DMAC controller available. This could be related to init order too!\n")); VM_FF_SET(pVM, VM_FF_PDM_DMA); #ifdef VBOX_WITH_REM REMR3NotifyDmaPending(pVM); #endif VMR3NotifyGlobalFFU(pVM->pUVM, VMNOTIFYFF_FLAGS_DONE_REM); } /** @interface_method_impl{PDMDEVHLPR3,pfnCMOSWrite} */ static DECLCALLBACK(int) pdmR3DevHlp_CMOSWrite(PPDMDEVINS pDevIns, unsigned iReg, uint8_t u8Value) { PDMDEV_ASSERT_DEVINS(pDevIns); PVM pVM = pDevIns->Internal.s.pVMR3; VM_ASSERT_EMT(pVM); LogFlow(("pdmR3DevHlp_CMOSWrite: caller='%s'/%d: iReg=%#04x u8Value=%#04x\n", pDevIns->pReg->szName, pDevIns->iInstance, iReg, u8Value)); int rc; if (pVM->pdm.s.pRtc) { PPDMDEVINS pDevInsRtc = pVM->pdm.s.pRtc->pDevIns; rc = PDMCritSectEnter(pDevInsRtc->pCritSectRoR3, VERR_IGNORED); if (RT_SUCCESS(rc)) { rc = pVM->pdm.s.pRtc->Reg.pfnWrite(pDevInsRtc, iReg, u8Value); PDMCritSectLeave(pDevInsRtc->pCritSectRoR3); } } else rc = VERR_PDM_NO_RTC_INSTANCE; LogFlow(("pdmR3DevHlp_CMOSWrite: caller='%s'/%d: return %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc)); return rc; } /** @interface_method_impl{PDMDEVHLPR3,pfnCMOSRead} */ static DECLCALLBACK(int) pdmR3DevHlp_CMOSRead(PPDMDEVINS pDevIns, unsigned iReg, uint8_t *pu8Value) { PDMDEV_ASSERT_DEVINS(pDevIns); PVM pVM = pDevIns->Internal.s.pVMR3; VM_ASSERT_EMT(pVM); LogFlow(("pdmR3DevHlp_CMOSWrite: caller='%s'/%d: iReg=%#04x pu8Value=%p\n", pDevIns->pReg->szName, pDevIns->iInstance, iReg, pu8Value)); int rc; if (pVM->pdm.s.pRtc) { PPDMDEVINS pDevInsRtc = pVM->pdm.s.pRtc->pDevIns; rc = PDMCritSectEnter(pDevInsRtc->pCritSectRoR3, VERR_IGNORED); if (RT_SUCCESS(rc)) { rc = pVM->pdm.s.pRtc->Reg.pfnRead(pDevInsRtc, iReg, pu8Value); PDMCritSectLeave(pDevInsRtc->pCritSectRoR3); } } else rc = VERR_PDM_NO_RTC_INSTANCE; LogFlow(("pdmR3DevHlp_CMOSWrite: caller='%s'/%d: return %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc)); return rc; } /** @interface_method_impl{PDMDEVHLPR3,pfnAssertEMT} */ static DECLCALLBACK(bool) pdmR3DevHlp_AssertEMT(PPDMDEVINS pDevIns, const char *pszFile, unsigned iLine, const char *pszFunction) { PDMDEV_ASSERT_DEVINS(pDevIns); if (VM_IS_EMT(pDevIns->Internal.s.pVMR3)) return true; char szMsg[100]; RTStrPrintf(szMsg, sizeof(szMsg), "AssertEMT '%s'/%d\n", pDevIns->pReg->szName, pDevIns->iInstance); RTAssertMsg1Weak(szMsg, iLine, pszFile, pszFunction); AssertBreakpoint(); return false; } /** @interface_method_impl{PDMDEVHLPR3,pfnAssertOther} */ static DECLCALLBACK(bool) pdmR3DevHlp_AssertOther(PPDMDEVINS pDevIns, const char *pszFile, unsigned iLine, const char *pszFunction) { PDMDEV_ASSERT_DEVINS(pDevIns); if (!VM_IS_EMT(pDevIns->Internal.s.pVMR3)) return true; char szMsg[100]; RTStrPrintf(szMsg, sizeof(szMsg), "AssertOther '%s'/%d\n", pDevIns->pReg->szName, pDevIns->iInstance); RTAssertMsg1Weak(szMsg, iLine, pszFile, pszFunction); AssertBreakpoint(); return false; } /** @interface_method_impl{PDMDEVHLP,pfnLdrGetRCInterfaceSymbols} */ static DECLCALLBACK(int) pdmR3DevHlp_LdrGetRCInterfaceSymbols(PPDMDEVINS pDevIns, void *pvInterface, size_t cbInterface, const char *pszSymPrefix, const char *pszSymList) { PDMDEV_ASSERT_DEVINS(pDevIns); VM_ASSERT_EMT(pDevIns->Internal.s.pVMR3); LogFlow(("pdmR3DevHlp_PDMLdrGetRCInterfaceSymbols: caller='%s'/%d: pvInterface=%p cbInterface=%zu pszSymPrefix=%p:{%s} pszSymList=%p:{%s}\n", pDevIns->pReg->szName, pDevIns->iInstance, pvInterface, cbInterface, pszSymPrefix, pszSymPrefix, pszSymList, pszSymList)); int rc; if ( strncmp(pszSymPrefix, "dev", 3) == 0 && RTStrIStr(pszSymPrefix + 3, pDevIns->pReg->szName) != NULL) { if (pDevIns->pReg->fFlags & PDM_DEVREG_FLAGS_RC) rc = PDMR3LdrGetInterfaceSymbols(pDevIns->Internal.s.pVMR3, pvInterface, cbInterface, pDevIns->pReg->szRCMod, pDevIns->Internal.s.pDevR3->pszRCSearchPath, pszSymPrefix, pszSymList, false /*fRing0OrRC*/); else { AssertMsgFailed(("Not a raw-mode enabled driver\n")); rc = VERR_PERMISSION_DENIED; } } else { AssertMsgFailed(("Invalid prefix '%s' for '%s'; must start with 'dev' and contain the driver name!\n", pszSymPrefix, pDevIns->pReg->szName)); rc = VERR_INVALID_NAME; } LogFlow(("pdmR3DevHlp_PDMLdrGetRCInterfaceSymbols: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc)); return rc; } /** @interface_method_impl{PDMDEVHLP,pfnLdrGetR0InterfaceSymbols} */ static DECLCALLBACK(int) pdmR3DevHlp_LdrGetR0InterfaceSymbols(PPDMDEVINS pDevIns, void *pvInterface, size_t cbInterface, const char *pszSymPrefix, const char *pszSymList) { PDMDEV_ASSERT_DEVINS(pDevIns); VM_ASSERT_EMT(pDevIns->Internal.s.pVMR3); LogFlow(("pdmR3DevHlp_PDMLdrGetR0InterfaceSymbols: caller='%s'/%d: pvInterface=%p cbInterface=%zu pszSymPrefix=%p:{%s} pszSymList=%p:{%s}\n", pDevIns->pReg->szName, pDevIns->iInstance, pvInterface, cbInterface, pszSymPrefix, pszSymPrefix, pszSymList, pszSymList)); int rc; if ( strncmp(pszSymPrefix, "dev", 3) == 0 && RTStrIStr(pszSymPrefix + 3, pDevIns->pReg->szName) != NULL) { if (pDevIns->pReg->fFlags & PDM_DEVREG_FLAGS_R0) rc = PDMR3LdrGetInterfaceSymbols(pDevIns->Internal.s.pVMR3, pvInterface, cbInterface, pDevIns->pReg->szR0Mod, pDevIns->Internal.s.pDevR3->pszR0SearchPath, pszSymPrefix, pszSymList, true /*fRing0OrRC*/); else { AssertMsgFailed(("Not a ring-0 enabled driver\n")); rc = VERR_PERMISSION_DENIED; } } else { AssertMsgFailed(("Invalid prefix '%s' for '%s'; must start with 'dev' and contain the driver name!\n", pszSymPrefix, pDevIns->pReg->szName)); rc = VERR_INVALID_NAME; } LogFlow(("pdmR3DevHlp_PDMLdrGetR0InterfaceSymbols: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc)); return rc; } /** @interface_method_impl{PDMDEVHLP,pfnCallR0} */ static DECLCALLBACK(int) pdmR3DevHlp_CallR0(PPDMDEVINS pDevIns, uint32_t uOperation, uint64_t u64Arg) { PDMDEV_ASSERT_DEVINS(pDevIns); PVM pVM = pDevIns->Internal.s.pVMR3; VM_ASSERT_EMT(pVM); LogFlow(("pdmR3DevHlp_CallR0: caller='%s'/%d: uOperation=%#x u64Arg=%#RX64\n", pDevIns->pReg->szName, pDevIns->iInstance, uOperation, u64Arg)); /* * Resolve the ring-0 entry point. There is not need to remember this like * we do for drivers since this is mainly for construction time hacks and * other things that aren't performance critical. */ int rc; if (pDevIns->pReg->fFlags & PDM_DEVREG_FLAGS_R0) { char szSymbol[ sizeof("devR0") + sizeof(pDevIns->pReg->szName) + sizeof("ReqHandler")]; strcat(strcat(strcpy(szSymbol, "devR0"), pDevIns->pReg->szName), "ReqHandler"); szSymbol[sizeof("devR0") - 1] = RT_C_TO_UPPER(szSymbol[sizeof("devR0") - 1]); PFNPDMDRVREQHANDLERR0 pfnReqHandlerR0; rc = pdmR3DevGetSymbolR0Lazy(pDevIns, szSymbol, &pfnReqHandlerR0); if (RT_SUCCESS(rc)) { /* * Make the ring-0 call. */ PDMDEVICECALLREQHANDLERREQ Req; Req.Hdr.u32Magic = SUPVMMR0REQHDR_MAGIC; Req.Hdr.cbReq = sizeof(Req); Req.pDevInsR0 = PDMDEVINS_2_R0PTR(pDevIns); Req.pfnReqHandlerR0 = pfnReqHandlerR0; Req.uOperation = uOperation; Req.u32Alignment = 0; Req.u64Arg = u64Arg; rc = SUPR3CallVMMR0Ex(pVM->pVMR0, NIL_VMCPUID, VMMR0_DO_PDM_DEVICE_CALL_REQ_HANDLER, 0, &Req.Hdr); } else pfnReqHandlerR0 = NIL_RTR0PTR; } else rc = VERR_ACCESS_DENIED; LogFlow(("pdmR3DevHlp_CallR0: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc)); return rc; } /** @interface_method_impl{PDMDEVHLP,pfnVMGetSuspendReason} */ static DECLCALLBACK(VMSUSPENDREASON) pdmR3DevHlp_VMGetSuspendReason(PPDMDEVINS pDevIns) { PDMDEV_ASSERT_DEVINS(pDevIns); PVM pVM = pDevIns->Internal.s.pVMR3; VM_ASSERT_EMT(pVM); VMSUSPENDREASON enmReason = VMR3GetSuspendReason(pVM->pUVM); LogFlow(("pdmR3DevHlp_VMGetSuspendReason: caller='%s'/%d: returns %d\n", pDevIns->pReg->szName, pDevIns->iInstance, enmReason)); return enmReason; } /** @interface_method_impl{PDMDEVHLP,pfnVMGetResumeReason} */ static DECLCALLBACK(VMRESUMEREASON) pdmR3DevHlp_VMGetResumeReason(PPDMDEVINS pDevIns) { PDMDEV_ASSERT_DEVINS(pDevIns); PVM pVM = pDevIns->Internal.s.pVMR3; VM_ASSERT_EMT(pVM); VMRESUMEREASON enmReason = VMR3GetResumeReason(pVM->pUVM); LogFlow(("pdmR3DevHlp_VMGetResumeReason: caller='%s'/%d: returns %d\n", pDevIns->pReg->szName, pDevIns->iInstance, enmReason)); return enmReason; } /** @interface_method_impl{PDMDEVHLPR3,pfnGetUVM} */ static DECLCALLBACK(PUVM) pdmR3DevHlp_GetUVM(PPDMDEVINS pDevIns) { PDMDEV_ASSERT_DEVINS(pDevIns); LogFlow(("pdmR3DevHlp_GetUVM: caller='%s'/%d: returns %p\n", pDevIns->pReg->szName, pDevIns->iInstance, pDevIns->Internal.s.pVMR3)); return pDevIns->Internal.s.pVMR3->pUVM; } /** @interface_method_impl{PDMDEVHLPR3,pfnGetVM} */ static DECLCALLBACK(PVM) pdmR3DevHlp_GetVM(PPDMDEVINS pDevIns) { PDMDEV_ASSERT_DEVINS(pDevIns); LogFlow(("pdmR3DevHlp_GetVM: caller='%s'/%d: returns %p\n", pDevIns->pReg->szName, pDevIns->iInstance, pDevIns->Internal.s.pVMR3)); return pDevIns->Internal.s.pVMR3; } /** @interface_method_impl{PDMDEVHLPR3,pfnGetVMCPU} */ static DECLCALLBACK(PVMCPU) pdmR3DevHlp_GetVMCPU(PPDMDEVINS pDevIns) { PDMDEV_ASSERT_DEVINS(pDevIns); VM_ASSERT_EMT(pDevIns->Internal.s.pVMR3); LogFlow(("pdmR3DevHlp_GetVMCPU: caller='%s'/%d for CPU %u\n", pDevIns->pReg->szName, pDevIns->iInstance, VMMGetCpuId(pDevIns->Internal.s.pVMR3))); return VMMGetCpu(pDevIns->Internal.s.pVMR3); } /** @interface_method_impl{PDMDEVHLPR3,pfnGetCurrentCpuId} */ static DECLCALLBACK(VMCPUID) pdmR3DevHlp_GetCurrentCpuId(PPDMDEVINS pDevIns) { PDMDEV_ASSERT_DEVINS(pDevIns); VMCPUID idCpu = VMMGetCpuId(pDevIns->Internal.s.pVMR3); LogFlow(("pdmR3DevHlp_GetCurrentCpuId: caller='%s'/%d for CPU %u\n", pDevIns->pReg->szName, pDevIns->iInstance, idCpu)); return idCpu; } /** @interface_method_impl{PDMDEVHLPR3,pfnPCIBusRegister} */ static DECLCALLBACK(int) pdmR3DevHlp_PCIBusRegister(PPDMDEVINS pDevIns, PPDMPCIBUSREG pPciBusReg, PCPDMPCIHLPR3 *ppPciHlpR3) { PDMDEV_ASSERT_DEVINS(pDevIns); PVM pVM = pDevIns->Internal.s.pVMR3; VM_ASSERT_EMT(pVM); LogFlow(("pdmR3DevHlp_PCIBusRegister: caller='%s'/%d: pPciBusReg=%p:{.u32Version=%#x, .pfnRegisterR3=%p, .pfnIORegionRegisterR3=%p, " ".pfnSetIrqR3=%p, .pfnFakePCIBIOSR3=%p, .pszSetIrqRC=%p:{%s}, .pszSetIrqR0=%p:{%s}} ppPciHlpR3=%p\n", pDevIns->pReg->szName, pDevIns->iInstance, pPciBusReg, pPciBusReg->u32Version, pPciBusReg->pfnRegisterR3, pPciBusReg->pfnIORegionRegisterR3, pPciBusReg->pfnSetIrqR3, pPciBusReg->pfnFakePCIBIOSR3, pPciBusReg->pszSetIrqRC, pPciBusReg->pszSetIrqRC, pPciBusReg->pszSetIrqR0, pPciBusReg->pszSetIrqR0, ppPciHlpR3)); /* * Validate the structure. */ if (pPciBusReg->u32Version != PDM_PCIBUSREG_VERSION) { AssertMsgFailed(("u32Version=%#x expected %#x\n", pPciBusReg->u32Version, PDM_PCIBUSREG_VERSION)); LogFlow(("pdmR3DevHlp_PCIRegister: caller='%s'/%d: returns %Rrc (version)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER)); return VERR_INVALID_PARAMETER; } if ( !pPciBusReg->pfnRegisterR3 || !pPciBusReg->pfnIORegionRegisterR3 || !pPciBusReg->pfnSetIrqR3 || (!pPciBusReg->pfnFakePCIBIOSR3 && !pVM->pdm.s.aPciBuses[0].pDevInsR3)) /* Only the first bus needs to do the BIOS work. */ { Assert(pPciBusReg->pfnRegisterR3); Assert(pPciBusReg->pfnIORegionRegisterR3); Assert(pPciBusReg->pfnSetIrqR3); Assert(pPciBusReg->pfnFakePCIBIOSR3); LogFlow(("pdmR3DevHlp_PCIBusRegister: caller='%s'/%d: returns %Rrc (R3 callbacks)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER)); return VERR_INVALID_PARAMETER; } if ( pPciBusReg->pszSetIrqRC && !VALID_PTR(pPciBusReg->pszSetIrqRC)) { Assert(VALID_PTR(pPciBusReg->pszSetIrqRC)); LogFlow(("pdmR3DevHlp_PCIBusRegister: caller='%s'/%d: returns %Rrc (GC callbacks)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER)); return VERR_INVALID_PARAMETER; } if ( pPciBusReg->pszSetIrqR0 && !VALID_PTR(pPciBusReg->pszSetIrqR0)) { Assert(VALID_PTR(pPciBusReg->pszSetIrqR0)); LogFlow(("pdmR3DevHlp_PCIBusRegister: caller='%s'/%d: returns %Rrc (GC callbacks)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER)); return VERR_INVALID_PARAMETER; } if (!ppPciHlpR3) { Assert(ppPciHlpR3); LogFlow(("pdmR3DevHlp_PCIBusRegister: caller='%s'/%d: returns %Rrc (ppPciHlpR3)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER)); return VERR_INVALID_PARAMETER; } /* * Find free PCI bus entry. */ unsigned iBus = 0; for (iBus = 0; iBus < RT_ELEMENTS(pVM->pdm.s.aPciBuses); iBus++) if (!pVM->pdm.s.aPciBuses[iBus].pDevInsR3) break; if (iBus >= RT_ELEMENTS(pVM->pdm.s.aPciBuses)) { AssertMsgFailed(("Too many PCI buses. Max=%u\n", RT_ELEMENTS(pVM->pdm.s.aPciBuses))); LogFlow(("pdmR3DevHlp_PCIBusRegister: caller='%s'/%d: returns %Rrc (pci bus)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER)); return VERR_INVALID_PARAMETER; } PPDMPCIBUS pPciBus = &pVM->pdm.s.aPciBuses[iBus]; /* * Resolve and init the RC bits. */ if (pPciBusReg->pszSetIrqRC) { int rc = pdmR3DevGetSymbolRCLazy(pDevIns, pPciBusReg->pszSetIrqRC, &pPciBus->pfnSetIrqRC); AssertMsgRC(rc, ("%s::%s rc=%Rrc\n", pDevIns->pReg->szRCMod, pPciBusReg->pszSetIrqRC, rc)); if (RT_FAILURE(rc)) { LogFlow(("pdmR3DevHlp_PCIRegister: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc)); return rc; } pPciBus->pDevInsRC = PDMDEVINS_2_RCPTR(pDevIns); } else { pPciBus->pfnSetIrqRC = 0; pPciBus->pDevInsRC = 0; } /* * Resolve and init the R0 bits. */ if (pPciBusReg->pszSetIrqR0) { int rc = pdmR3DevGetSymbolR0Lazy(pDevIns, pPciBusReg->pszSetIrqR0, &pPciBus->pfnSetIrqR0); AssertMsgRC(rc, ("%s::%s rc=%Rrc\n", pDevIns->pReg->szR0Mod, pPciBusReg->pszSetIrqR0, rc)); if (RT_FAILURE(rc)) { LogFlow(("pdmR3DevHlp_PCIRegister: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc)); return rc; } pPciBus->pDevInsR0 = PDMDEVINS_2_R0PTR(pDevIns); } else { pPciBus->pfnSetIrqR0 = 0; pPciBus->pDevInsR0 = 0; } /* * Init the R3 bits. */ pPciBus->iBus = iBus; pPciBus->pDevInsR3 = pDevIns; pPciBus->pfnRegisterR3 = pPciBusReg->pfnRegisterR3; pPciBus->pfnRegisterMsiR3 = pPciBusReg->pfnRegisterMsiR3; pPciBus->pfnIORegionRegisterR3 = pPciBusReg->pfnIORegionRegisterR3; pPciBus->pfnSetConfigCallbacksR3 = pPciBusReg->pfnSetConfigCallbacksR3; pPciBus->pfnSetIrqR3 = pPciBusReg->pfnSetIrqR3; pPciBus->pfnFakePCIBIOSR3 = pPciBusReg->pfnFakePCIBIOSR3; Log(("PDM: Registered PCI bus device '%s'/%d pDevIns=%p\n", pDevIns->pReg->szName, pDevIns->iInstance, pDevIns)); /* set the helper pointer and return. */ *ppPciHlpR3 = &g_pdmR3DevPciHlp; LogFlow(("pdmR3DevHlp_PCIBusRegister: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, VINF_SUCCESS)); return VINF_SUCCESS; } /** @interface_method_impl{PDMDEVHLPR3,pfnPICRegister} */ static DECLCALLBACK(int) pdmR3DevHlp_PICRegister(PPDMDEVINS pDevIns, PPDMPICREG pPicReg, PCPDMPICHLPR3 *ppPicHlpR3) { PDMDEV_ASSERT_DEVINS(pDevIns); VM_ASSERT_EMT(pDevIns->Internal.s.pVMR3); LogFlow(("pdmR3DevHlp_PICRegister: caller='%s'/%d: pPicReg=%p:{.u32Version=%#x, .pfnSetIrqR3=%p, .pfnGetInterruptR3=%p, .pszGetIrqRC=%p:{%s}, .pszGetInterruptRC=%p:{%s}, .pszGetIrqR0=%p:{%s}, .pszGetInterruptR0=%p:{%s} } ppPicHlpR3=%p\n", pDevIns->pReg->szName, pDevIns->iInstance, pPicReg, pPicReg->u32Version, pPicReg->pfnSetIrqR3, pPicReg->pfnGetInterruptR3, pPicReg->pszSetIrqRC, pPicReg->pszSetIrqRC, pPicReg->pszGetInterruptRC, pPicReg->pszGetInterruptRC, pPicReg->pszSetIrqR0, pPicReg->pszSetIrqR0, pPicReg->pszGetInterruptR0, pPicReg->pszGetInterruptR0, ppPicHlpR3)); /* * Validate input. */ if (pPicReg->u32Version != PDM_PICREG_VERSION) { AssertMsgFailed(("u32Version=%#x expected %#x\n", pPicReg->u32Version, PDM_PICREG_VERSION)); LogFlow(("pdmR3DevHlp_PICRegister: caller='%s'/%d: returns %Rrc (version)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER)); return VERR_INVALID_PARAMETER; } if ( !pPicReg->pfnSetIrqR3 || !pPicReg->pfnGetInterruptR3) { Assert(pPicReg->pfnSetIrqR3); Assert(pPicReg->pfnGetInterruptR3); LogFlow(("pdmR3DevHlp_PICRegister: caller='%s'/%d: returns %Rrc (R3 callbacks)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER)); return VERR_INVALID_PARAMETER; } if ( ( pPicReg->pszSetIrqRC || pPicReg->pszGetInterruptRC) && ( !VALID_PTR(pPicReg->pszSetIrqRC) || !VALID_PTR(pPicReg->pszGetInterruptRC)) ) { Assert(VALID_PTR(pPicReg->pszSetIrqRC)); Assert(VALID_PTR(pPicReg->pszGetInterruptRC)); LogFlow(("pdmR3DevHlp_PICRegister: caller='%s'/%d: returns %Rrc (RC callbacks)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER)); return VERR_INVALID_PARAMETER; } if ( pPicReg->pszSetIrqRC && !(pDevIns->pReg->fFlags & PDM_DEVREG_FLAGS_RC)) { Assert(pDevIns->pReg->fFlags & PDM_DEVREG_FLAGS_RC); LogFlow(("pdmR3DevHlp_PICRegister: caller='%s'/%d: returns %Rrc (RC flag)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER)); return VERR_INVALID_PARAMETER; } if ( pPicReg->pszSetIrqR0 && !(pDevIns->pReg->fFlags & PDM_DEVREG_FLAGS_R0)) { Assert(pDevIns->pReg->fFlags & PDM_DEVREG_FLAGS_R0); LogFlow(("pdmR3DevHlp_PICRegister: caller='%s'/%d: returns %Rrc (R0 flag)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER)); return VERR_INVALID_PARAMETER; } if (!ppPicHlpR3) { Assert(ppPicHlpR3); LogFlow(("pdmR3DevHlp_PICRegister: caller='%s'/%d: returns %Rrc (ppPicHlpR3)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER)); return VERR_INVALID_PARAMETER; } /* * Only one PIC device. */ PVM pVM = pDevIns->Internal.s.pVMR3; if (pVM->pdm.s.Pic.pDevInsR3) { AssertMsgFailed(("Only one pic device is supported!\n")); LogFlow(("pdmR3DevHlp_PICRegister: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER)); return VERR_INVALID_PARAMETER; } /* * RC stuff. */ if (pPicReg->pszSetIrqRC) { int rc = pdmR3DevGetSymbolRCLazy(pDevIns, pPicReg->pszSetIrqRC, &pVM->pdm.s.Pic.pfnSetIrqRC); AssertMsgRC(rc, ("%s::%s rc=%Rrc\n", pDevIns->pReg->szRCMod, pPicReg->pszSetIrqRC, rc)); if (RT_SUCCESS(rc)) { rc = pdmR3DevGetSymbolRCLazy(pDevIns, pPicReg->pszGetInterruptRC, &pVM->pdm.s.Pic.pfnGetInterruptRC); AssertMsgRC(rc, ("%s::%s rc=%Rrc\n", pDevIns->pReg->szRCMod, pPicReg->pszGetInterruptRC, rc)); } if (RT_FAILURE(rc)) { LogFlow(("pdmR3DevHlp_PICRegister: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc)); return rc; } pVM->pdm.s.Pic.pDevInsRC = PDMDEVINS_2_RCPTR(pDevIns); } else { pVM->pdm.s.Pic.pDevInsRC = 0; pVM->pdm.s.Pic.pfnSetIrqRC = 0; pVM->pdm.s.Pic.pfnGetInterruptRC = 0; } /* * R0 stuff. */ if (pPicReg->pszSetIrqR0) { int rc = pdmR3DevGetSymbolR0Lazy(pDevIns, pPicReg->pszSetIrqR0, &pVM->pdm.s.Pic.pfnSetIrqR0); AssertMsgRC(rc, ("%s::%s rc=%Rrc\n", pDevIns->pReg->szR0Mod, pPicReg->pszSetIrqR0, rc)); if (RT_SUCCESS(rc)) { rc = pdmR3DevGetSymbolR0Lazy(pDevIns, pPicReg->pszGetInterruptR0, &pVM->pdm.s.Pic.pfnGetInterruptR0); AssertMsgRC(rc, ("%s::%s rc=%Rrc\n", pDevIns->pReg->szR0Mod, pPicReg->pszGetInterruptR0, rc)); } if (RT_FAILURE(rc)) { LogFlow(("pdmR3DevHlp_PICRegister: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc)); return rc; } pVM->pdm.s.Pic.pDevInsR0 = PDMDEVINS_2_R0PTR(pDevIns); Assert(pVM->pdm.s.Pic.pDevInsR0); } else { pVM->pdm.s.Pic.pfnSetIrqR0 = 0; pVM->pdm.s.Pic.pfnGetInterruptR0 = 0; pVM->pdm.s.Pic.pDevInsR0 = 0; } /* * R3 stuff. */ pVM->pdm.s.Pic.pDevInsR3 = pDevIns; pVM->pdm.s.Pic.pfnSetIrqR3 = pPicReg->pfnSetIrqR3; pVM->pdm.s.Pic.pfnGetInterruptR3 = pPicReg->pfnGetInterruptR3; Log(("PDM: Registered PIC device '%s'/%d pDevIns=%p\n", pDevIns->pReg->szName, pDevIns->iInstance, pDevIns)); /* set the helper pointer and return. */ *ppPicHlpR3 = &g_pdmR3DevPicHlp; LogFlow(("pdmR3DevHlp_PICRegister: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, VINF_SUCCESS)); return VINF_SUCCESS; } /** @interface_method_impl{PDMDEVHLPR3,pfnAPICRegister} */ static DECLCALLBACK(int) pdmR3DevHlp_APICRegister(PPDMDEVINS pDevIns, PPDMAPICREG pApicReg, PCPDMAPICHLPR3 *ppApicHlpR3) { PDMDEV_ASSERT_DEVINS(pDevIns); VM_ASSERT_EMT(pDevIns->Internal.s.pVMR3); LogFlow(("pdmR3DevHlp_APICRegister: caller='%s'/%d: pApicReg=%p:{.u32Version=%#x, .pfnGetInterruptR3=%p, .pfnSetBaseR3=%p, .pfnGetBaseR3=%p, " ".pfnSetTPRR3=%p, .pfnGetTPRR3=%p, .pfnWriteMSR3=%p, .pfnReadMSR3=%p, .pfnBusDeliverR3=%p, .pfnLocalInterruptR3=%p .pfnGetTimerFreqR3=%p, pszGetInterruptRC=%p:{%s}, pszSetBaseRC=%p:{%s}, pszGetBaseRC=%p:{%s}, " ".pszSetTPRRC=%p:{%s}, .pszGetTPRRC=%p:{%s}, .pszWriteMSRRC=%p:{%s}, .pszReadMSRRC=%p:{%s}, .pszBusDeliverRC=%p:{%s}, .pszLocalInterruptRC=%p:{%s}, .pszGetTimerFreqRC=%p:{%s}} ppApicHlpR3=%p\n", pDevIns->pReg->szName, pDevIns->iInstance, pApicReg, pApicReg->u32Version, pApicReg->pfnGetInterruptR3, pApicReg->pfnSetBaseR3, pApicReg->pfnGetBaseR3, pApicReg->pfnSetTPRR3, pApicReg->pfnGetTPRR3, pApicReg->pfnWriteMSRR3, pApicReg->pfnReadMSRR3, pApicReg->pfnBusDeliverR3, pApicReg->pfnLocalInterruptR3, pApicReg->pfnGetTimerFreqR3, pApicReg->pszGetInterruptRC, pApicReg->pszGetInterruptRC, pApicReg->pszSetBaseRC, pApicReg->pszSetBaseRC, pApicReg->pszGetBaseRC, pApicReg->pszGetBaseRC, pApicReg->pszSetTPRRC, pApicReg->pszSetTPRRC, pApicReg->pszGetTPRRC, pApicReg->pszGetTPRRC, pApicReg->pszWriteMSRRC, pApicReg->pszWriteMSRRC, pApicReg->pszReadMSRRC, pApicReg->pszReadMSRRC, pApicReg->pszBusDeliverRC, pApicReg->pszBusDeliverRC, pApicReg->pszLocalInterruptRC, pApicReg->pszLocalInterruptRC, pApicReg->pszGetTimerFreqRC, pApicReg->pszGetTimerFreqRC, ppApicHlpR3)); /* * Validate input. */ if (pApicReg->u32Version != PDM_APICREG_VERSION) { AssertMsgFailed(("u32Version=%#x expected %#x\n", pApicReg->u32Version, PDM_APICREG_VERSION)); LogFlow(("pdmR3DevHlp_APICRegister: caller='%s'/%d: returns %Rrc (version)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER)); return VERR_INVALID_PARAMETER; } if ( !pApicReg->pfnGetInterruptR3 || !pApicReg->pfnHasPendingIrqR3 || !pApicReg->pfnSetBaseR3 || !pApicReg->pfnGetBaseR3 || !pApicReg->pfnSetTPRR3 || !pApicReg->pfnGetTPRR3 || !pApicReg->pfnWriteMSRR3 || !pApicReg->pfnReadMSRR3 || !pApicReg->pfnBusDeliverR3 || !pApicReg->pfnLocalInterruptR3 || !pApicReg->pfnGetTimerFreqR3) { Assert(pApicReg->pfnGetInterruptR3); Assert(pApicReg->pfnHasPendingIrqR3); Assert(pApicReg->pfnSetBaseR3); Assert(pApicReg->pfnGetBaseR3); Assert(pApicReg->pfnSetTPRR3); Assert(pApicReg->pfnGetTPRR3); Assert(pApicReg->pfnWriteMSRR3); Assert(pApicReg->pfnReadMSRR3); Assert(pApicReg->pfnBusDeliverR3); Assert(pApicReg->pfnLocalInterruptR3); Assert(pApicReg->pfnGetTimerFreqR3); LogFlow(("pdmR3DevHlp_APICRegister: caller='%s'/%d: returns %Rrc (R3 callbacks)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER)); return VERR_INVALID_PARAMETER; } if ( ( pApicReg->pszGetInterruptRC || pApicReg->pszHasPendingIrqRC || pApicReg->pszSetBaseRC || pApicReg->pszGetBaseRC || pApicReg->pszSetTPRRC || pApicReg->pszGetTPRRC || pApicReg->pszWriteMSRRC || pApicReg->pszReadMSRRC || pApicReg->pszBusDeliverRC || pApicReg->pszLocalInterruptRC || pApicReg->pszGetTimerFreqRC) && ( !VALID_PTR(pApicReg->pszGetInterruptRC) || !VALID_PTR(pApicReg->pszHasPendingIrqRC) || !VALID_PTR(pApicReg->pszSetBaseRC) || !VALID_PTR(pApicReg->pszGetBaseRC) || !VALID_PTR(pApicReg->pszSetTPRRC) || !VALID_PTR(pApicReg->pszGetTPRRC) || !VALID_PTR(pApicReg->pszWriteMSRRC) || !VALID_PTR(pApicReg->pszReadMSRRC) || !VALID_PTR(pApicReg->pszBusDeliverRC) || !VALID_PTR(pApicReg->pszLocalInterruptRC) || !VALID_PTR(pApicReg->pszGetTimerFreqRC)) ) { Assert(VALID_PTR(pApicReg->pszGetInterruptRC)); Assert(VALID_PTR(pApicReg->pszHasPendingIrqRC)); Assert(VALID_PTR(pApicReg->pszSetBaseRC)); Assert(VALID_PTR(pApicReg->pszGetBaseRC)); Assert(VALID_PTR(pApicReg->pszSetTPRRC)); Assert(VALID_PTR(pApicReg->pszGetTPRRC)); Assert(VALID_PTR(pApicReg->pszReadMSRRC)); Assert(VALID_PTR(pApicReg->pszWriteMSRRC)); Assert(VALID_PTR(pApicReg->pszBusDeliverRC)); Assert(VALID_PTR(pApicReg->pszLocalInterruptRC)); Assert(VALID_PTR(pApicReg->pszGetTimerFreqRC)); LogFlow(("pdmR3DevHlp_APICRegister: caller='%s'/%d: returns %Rrc (RC callbacks)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER)); return VERR_INVALID_PARAMETER; } if ( ( pApicReg->pszGetInterruptR0 || pApicReg->pszHasPendingIrqR0 || pApicReg->pszSetBaseR0 || pApicReg->pszGetBaseR0 || pApicReg->pszSetTPRR0 || pApicReg->pszGetTPRR0 || pApicReg->pszWriteMSRR0 || pApicReg->pszReadMSRR0 || pApicReg->pszBusDeliverR0 || pApicReg->pszLocalInterruptR0 || pApicReg->pszGetTimerFreqR0) && ( !VALID_PTR(pApicReg->pszGetInterruptR0) || !VALID_PTR(pApicReg->pszHasPendingIrqR0) || !VALID_PTR(pApicReg->pszSetBaseR0) || !VALID_PTR(pApicReg->pszGetBaseR0) || !VALID_PTR(pApicReg->pszSetTPRR0) || !VALID_PTR(pApicReg->pszGetTPRR0) || !VALID_PTR(pApicReg->pszReadMSRR0) || !VALID_PTR(pApicReg->pszWriteMSRR0) || !VALID_PTR(pApicReg->pszBusDeliverR0) || !VALID_PTR(pApicReg->pszLocalInterruptR0) || !VALID_PTR(pApicReg->pszGetTimerFreqR0)) ) { Assert(VALID_PTR(pApicReg->pszGetInterruptR0)); Assert(VALID_PTR(pApicReg->pszHasPendingIrqR0)); Assert(VALID_PTR(pApicReg->pszSetBaseR0)); Assert(VALID_PTR(pApicReg->pszGetBaseR0)); Assert(VALID_PTR(pApicReg->pszSetTPRR0)); Assert(VALID_PTR(pApicReg->pszGetTPRR0)); Assert(VALID_PTR(pApicReg->pszReadMSRR0)); Assert(VALID_PTR(pApicReg->pszWriteMSRR0)); Assert(VALID_PTR(pApicReg->pszBusDeliverR0)); Assert(VALID_PTR(pApicReg->pszLocalInterruptR0)); Assert(VALID_PTR(pApicReg->pszGetTimerFreqR0)); LogFlow(("pdmR3DevHlp_APICRegister: caller='%s'/%d: returns %Rrc (R0 callbacks)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER)); return VERR_INVALID_PARAMETER; } if (!ppApicHlpR3) { Assert(ppApicHlpR3); LogFlow(("pdmR3DevHlp_APICRegister: caller='%s'/%d: returns %Rrc (ppApicHlpR3)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER)); return VERR_INVALID_PARAMETER; } /* * Only one APIC device. On SMP we have single logical device covering all LAPICs, * as they need to communicate and share state easily. */ PVM pVM = pDevIns->Internal.s.pVMR3; if (pVM->pdm.s.Apic.pDevInsR3) { AssertMsgFailed(("Only one apic device is supported!\n")); LogFlow(("pdmR3DevHlp_APICRegister: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER)); return VERR_INVALID_PARAMETER; } /* * Resolve & initialize the RC bits. */ if (pApicReg->pszGetInterruptRC) { int rc = pdmR3DevGetSymbolRCLazy(pDevIns, pApicReg->pszGetInterruptRC, &pVM->pdm.s.Apic.pfnGetInterruptRC); AssertMsgRC(rc, ("%s::%s rc=%Rrc\n", pDevIns->pReg->szRCMod, pApicReg->pszGetInterruptRC, rc)); if (RT_SUCCESS(rc)) { rc = pdmR3DevGetSymbolRCLazy(pDevIns, pApicReg->pszHasPendingIrqRC, &pVM->pdm.s.Apic.pfnHasPendingIrqRC); AssertMsgRC(rc, ("%s::%s rc=%Rrc\n", pDevIns->pReg->szRCMod, pApicReg->pszHasPendingIrqRC, rc)); } if (RT_SUCCESS(rc)) { rc = pdmR3DevGetSymbolRCLazy(pDevIns, pApicReg->pszSetBaseRC, &pVM->pdm.s.Apic.pfnSetBaseRC); AssertMsgRC(rc, ("%s::%s rc=%Rrc\n", pDevIns->pReg->szRCMod, pApicReg->pszSetBaseRC, rc)); } if (RT_SUCCESS(rc)) { rc = pdmR3DevGetSymbolRCLazy(pDevIns, pApicReg->pszGetBaseRC, &pVM->pdm.s.Apic.pfnGetBaseRC); AssertMsgRC(rc, ("%s::%s rc=%Rrc\n", pDevIns->pReg->szRCMod, pApicReg->pszGetBaseRC, rc)); } if (RT_SUCCESS(rc)) { rc = pdmR3DevGetSymbolRCLazy(pDevIns, pApicReg->pszSetTPRRC, &pVM->pdm.s.Apic.pfnSetTPRRC); AssertMsgRC(rc, ("%s::%s rc=%Rrc\n", pDevIns->pReg->szRCMod, pApicReg->pszSetTPRRC, rc)); } if (RT_SUCCESS(rc)) { rc = pdmR3DevGetSymbolRCLazy(pDevIns, pApicReg->pszGetTPRRC, &pVM->pdm.s.Apic.pfnGetTPRRC); AssertMsgRC(rc, ("%s::%s rc=%Rrc\n", pDevIns->pReg->szRCMod, pApicReg->pszGetTPRRC, rc)); } if (RT_SUCCESS(rc)) { rc = pdmR3DevGetSymbolRCLazy(pDevIns, pApicReg->pszWriteMSRRC, &pVM->pdm.s.Apic.pfnWriteMSRRC); AssertMsgRC(rc, ("%s::%s rc=%Rrc\n", pDevIns->pReg->szRCMod, pApicReg->pszWriteMSRRC, rc)); } if (RT_SUCCESS(rc)) { rc = pdmR3DevGetSymbolRCLazy(pDevIns, pApicReg->pszReadMSRRC, &pVM->pdm.s.Apic.pfnReadMSRRC); AssertMsgRC(rc, ("%s::%s rc=%Rrc\n", pDevIns->pReg->szRCMod, pApicReg->pszReadMSRRC, rc)); } if (RT_SUCCESS(rc)) { rc = pdmR3DevGetSymbolRCLazy(pDevIns, pApicReg->pszBusDeliverRC, &pVM->pdm.s.Apic.pfnBusDeliverRC); AssertMsgRC(rc, ("%s::%s rc=%Rrc\n", pDevIns->pReg->szRCMod, pApicReg->pszBusDeliverRC, rc)); } if (RT_SUCCESS(rc)) { rc = pdmR3DevGetSymbolRCLazy(pDevIns, pApicReg->pszLocalInterruptRC, &pVM->pdm.s.Apic.pfnLocalInterruptRC); AssertMsgRC(rc, ("%s::%s rc=%Rrc\n", pDevIns->pReg->szRCMod, pApicReg->pszLocalInterruptRC, rc)); } if (RT_SUCCESS(rc)) { rc = pdmR3DevGetSymbolRCLazy(pDevIns, pApicReg->pszGetTimerFreqRC, &pVM->pdm.s.Apic.pfnGetTimerFreqRC); AssertMsgRC(rc, ("%s::%s rc=%Rrc\n", pDevIns->pReg->szRCMod, pApicReg->pszGetTimerFreqRC, rc)); } if (RT_FAILURE(rc)) { LogFlow(("pdmR3DevHlp_APICRegister: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc)); return rc; } pVM->pdm.s.Apic.pDevInsRC = PDMDEVINS_2_RCPTR(pDevIns); } else { pVM->pdm.s.Apic.pDevInsRC = 0; pVM->pdm.s.Apic.pfnGetInterruptRC = 0; pVM->pdm.s.Apic.pfnHasPendingIrqRC = 0; pVM->pdm.s.Apic.pfnSetBaseRC = 0; pVM->pdm.s.Apic.pfnGetBaseRC = 0; pVM->pdm.s.Apic.pfnSetTPRRC = 0; pVM->pdm.s.Apic.pfnGetTPRRC = 0; pVM->pdm.s.Apic.pfnWriteMSRRC = 0; pVM->pdm.s.Apic.pfnReadMSRRC = 0; pVM->pdm.s.Apic.pfnBusDeliverRC = 0; pVM->pdm.s.Apic.pfnLocalInterruptRC = 0; pVM->pdm.s.Apic.pfnGetTimerFreqRC = 0; } /* * Resolve & initialize the R0 bits. */ if (pApicReg->pszGetInterruptR0) { int rc = pdmR3DevGetSymbolR0Lazy(pDevIns, pApicReg->pszGetInterruptR0, &pVM->pdm.s.Apic.pfnGetInterruptR0); AssertMsgRC(rc, ("%s::%s rc=%Rrc\n", pDevIns->pReg->szR0Mod, pApicReg->pszGetInterruptR0, rc)); if (RT_SUCCESS(rc)) { rc = pdmR3DevGetSymbolR0Lazy(pDevIns, pApicReg->pszHasPendingIrqR0, &pVM->pdm.s.Apic.pfnHasPendingIrqR0); AssertMsgRC(rc, ("%s::%s rc=%Rrc\n", pDevIns->pReg->szR0Mod, pApicReg->pszHasPendingIrqR0, rc)); } if (RT_SUCCESS(rc)) { rc = pdmR3DevGetSymbolR0Lazy(pDevIns, pApicReg->pszSetBaseR0, &pVM->pdm.s.Apic.pfnSetBaseR0); AssertMsgRC(rc, ("%s::%s rc=%Rrc\n", pDevIns->pReg->szR0Mod, pApicReg->pszSetBaseR0, rc)); } if (RT_SUCCESS(rc)) { rc = pdmR3DevGetSymbolR0Lazy(pDevIns, pApicReg->pszGetBaseR0, &pVM->pdm.s.Apic.pfnGetBaseR0); AssertMsgRC(rc, ("%s::%s rc=%Rrc\n", pDevIns->pReg->szR0Mod, pApicReg->pszGetBaseR0, rc)); } if (RT_SUCCESS(rc)) { rc = pdmR3DevGetSymbolR0Lazy(pDevIns, pApicReg->pszSetTPRR0, &pVM->pdm.s.Apic.pfnSetTPRR0); AssertMsgRC(rc, ("%s::%s rc=%Rrc\n", pDevIns->pReg->szR0Mod, pApicReg->pszSetTPRR0, rc)); } if (RT_SUCCESS(rc)) { rc = pdmR3DevGetSymbolR0Lazy(pDevIns, pApicReg->pszGetTPRR0, &pVM->pdm.s.Apic.pfnGetTPRR0); AssertMsgRC(rc, ("%s::%s rc=%Rrc\n", pDevIns->pReg->szR0Mod, pApicReg->pszGetTPRR0, rc)); } if (RT_SUCCESS(rc)) { rc = pdmR3DevGetSymbolR0Lazy(pDevIns, pApicReg->pszWriteMSRR0, &pVM->pdm.s.Apic.pfnWriteMSRR0); AssertMsgRC(rc, ("%s::%s rc=%Rrc\n", pDevIns->pReg->szR0Mod, pApicReg->pszWriteMSRR0, rc)); } if (RT_SUCCESS(rc)) { rc = pdmR3DevGetSymbolR0Lazy(pDevIns, pApicReg->pszReadMSRR0, &pVM->pdm.s.Apic.pfnReadMSRR0); AssertMsgRC(rc, ("%s::%s rc=%Rrc\n", pDevIns->pReg->szR0Mod, pApicReg->pszReadMSRR0, rc)); } if (RT_SUCCESS(rc)) { rc = pdmR3DevGetSymbolR0Lazy(pDevIns, pApicReg->pszBusDeliverR0, &pVM->pdm.s.Apic.pfnBusDeliverR0); AssertMsgRC(rc, ("%s::%s rc=%Rrc\n", pDevIns->pReg->szR0Mod, pApicReg->pszBusDeliverR0, rc)); } if (RT_SUCCESS(rc)) { rc = pdmR3DevGetSymbolR0Lazy(pDevIns, pApicReg->pszLocalInterruptR0, &pVM->pdm.s.Apic.pfnLocalInterruptR0); AssertMsgRC(rc, ("%s::%s rc=%Rrc\n", pDevIns->pReg->szR0Mod, pApicReg->pszLocalInterruptR0, rc)); } if (RT_SUCCESS(rc)) { rc = pdmR3DevGetSymbolR0Lazy(pDevIns, pApicReg->pszGetTimerFreqR0, &pVM->pdm.s.Apic.pfnGetTimerFreqR0); AssertMsgRC(rc, ("%s::%s rc=%Rrc\n", pDevIns->pReg->szR0Mod, pApicReg->pszGetTimerFreqR0, rc)); } if (RT_FAILURE(rc)) { LogFlow(("pdmR3DevHlp_APICRegister: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc)); return rc; } pVM->pdm.s.Apic.pDevInsR0 = PDMDEVINS_2_R0PTR(pDevIns); Assert(pVM->pdm.s.Apic.pDevInsR0); } else { pVM->pdm.s.Apic.pfnGetInterruptR0 = 0; pVM->pdm.s.Apic.pfnHasPendingIrqR0 = 0; pVM->pdm.s.Apic.pfnSetBaseR0 = 0; pVM->pdm.s.Apic.pfnGetBaseR0 = 0; pVM->pdm.s.Apic.pfnSetTPRR0 = 0; pVM->pdm.s.Apic.pfnGetTPRR0 = 0; pVM->pdm.s.Apic.pfnWriteMSRR0 = 0; pVM->pdm.s.Apic.pfnReadMSRR0 = 0; pVM->pdm.s.Apic.pfnBusDeliverR0 = 0; pVM->pdm.s.Apic.pfnLocalInterruptR0 = 0; pVM->pdm.s.Apic.pfnGetTimerFreqR0 = 0; pVM->pdm.s.Apic.pDevInsR0 = 0; } /* * Initialize the HC bits. */ pVM->pdm.s.Apic.pDevInsR3 = pDevIns; pVM->pdm.s.Apic.pfnGetInterruptR3 = pApicReg->pfnGetInterruptR3; pVM->pdm.s.Apic.pfnHasPendingIrqR3 = pApicReg->pfnHasPendingIrqR3; pVM->pdm.s.Apic.pfnSetBaseR3 = pApicReg->pfnSetBaseR3; pVM->pdm.s.Apic.pfnGetBaseR3 = pApicReg->pfnGetBaseR3; pVM->pdm.s.Apic.pfnSetTPRR3 = pApicReg->pfnSetTPRR3; pVM->pdm.s.Apic.pfnGetTPRR3 = pApicReg->pfnGetTPRR3; pVM->pdm.s.Apic.pfnWriteMSRR3 = pApicReg->pfnWriteMSRR3; pVM->pdm.s.Apic.pfnReadMSRR3 = pApicReg->pfnReadMSRR3; pVM->pdm.s.Apic.pfnBusDeliverR3 = pApicReg->pfnBusDeliverR3; pVM->pdm.s.Apic.pfnLocalInterruptR3 = pApicReg->pfnLocalInterruptR3; pVM->pdm.s.Apic.pfnGetTimerFreqR3 = pApicReg->pfnGetTimerFreqR3; Log(("PDM: Registered APIC device '%s'/%d pDevIns=%p\n", pDevIns->pReg->szName, pDevIns->iInstance, pDevIns)); /* set the helper pointer and return. */ *ppApicHlpR3 = &g_pdmR3DevApicHlp; LogFlow(("pdmR3DevHlp_APICRegister: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, VINF_SUCCESS)); return VINF_SUCCESS; } /** @interface_method_impl{PDMDEVHLPR3,pfnIOAPICRegister} */ static DECLCALLBACK(int) pdmR3DevHlp_IOAPICRegister(PPDMDEVINS pDevIns, PPDMIOAPICREG pIoApicReg, PCPDMIOAPICHLPR3 *ppIoApicHlpR3) { PDMDEV_ASSERT_DEVINS(pDevIns); VM_ASSERT_EMT(pDevIns->Internal.s.pVMR3); LogFlow(("pdmR3DevHlp_IOAPICRegister: caller='%s'/%d: pIoApicReg=%p:{.u32Version=%#x, .pfnSetIrqR3=%p, .pszSetIrqRC=%p:{%s}, .pszSetIrqR0=%p:{%s}} ppIoApicHlpR3=%p\n", pDevIns->pReg->szName, pDevIns->iInstance, pIoApicReg, pIoApicReg->u32Version, pIoApicReg->pfnSetIrqR3, pIoApicReg->pszSetIrqRC, pIoApicReg->pszSetIrqRC, pIoApicReg->pszSetIrqR0, pIoApicReg->pszSetIrqR0, ppIoApicHlpR3)); /* * Validate input. */ if (pIoApicReg->u32Version != PDM_IOAPICREG_VERSION) { AssertMsgFailed(("u32Version=%#x expected %#x\n", pIoApicReg->u32Version, PDM_IOAPICREG_VERSION)); LogFlow(("pdmR3DevHlp_IOAPICRegister: caller='%s'/%d: returns %Rrc (version)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER)); return VERR_INVALID_PARAMETER; } if (!pIoApicReg->pfnSetIrqR3 || !pIoApicReg->pfnSendMsiR3) { Assert(pIoApicReg->pfnSetIrqR3); LogFlow(("pdmR3DevHlp_IOAPICRegister: caller='%s'/%d: returns %Rrc (R3 callbacks)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER)); return VERR_INVALID_PARAMETER; } if ( pIoApicReg->pszSetIrqRC && !VALID_PTR(pIoApicReg->pszSetIrqRC)) { Assert(VALID_PTR(pIoApicReg->pszSetIrqRC)); LogFlow(("pdmR3DevHlp_IOAPICRegister: caller='%s'/%d: returns %Rrc (GC callbacks)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER)); return VERR_INVALID_PARAMETER; } if ( pIoApicReg->pszSendMsiRC && !VALID_PTR(pIoApicReg->pszSendMsiRC)) { Assert(VALID_PTR(pIoApicReg->pszSendMsiRC)); LogFlow(("pdmR3DevHlp_IOAPICRegister: caller='%s'/%d: returns %Rrc (GC callbacks)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER)); return VERR_INVALID_PARAMETER; } if ( pIoApicReg->pszSetIrqR0 && !VALID_PTR(pIoApicReg->pszSetIrqR0)) { Assert(VALID_PTR(pIoApicReg->pszSetIrqR0)); LogFlow(("pdmR3DevHlp_IOAPICRegister: caller='%s'/%d: returns %Rrc (GC callbacks)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER)); return VERR_INVALID_PARAMETER; } if ( pIoApicReg->pszSendMsiR0 && !VALID_PTR(pIoApicReg->pszSendMsiR0)) { Assert(VALID_PTR(pIoApicReg->pszSendMsiR0)); LogFlow(("pdmR3DevHlp_IOAPICRegister: caller='%s'/%d: returns %Rrc (GC callbacks)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER)); return VERR_INVALID_PARAMETER; } if (!ppIoApicHlpR3) { Assert(ppIoApicHlpR3); LogFlow(("pdmR3DevHlp_IOAPICRegister: caller='%s'/%d: returns %Rrc (ppApicHlp)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER)); return VERR_INVALID_PARAMETER; } /* * The I/O APIC requires the APIC to be present (hacks++). * If the I/O APIC does GC stuff so must the APIC. */ PVM pVM = pDevIns->Internal.s.pVMR3; if (!pVM->pdm.s.Apic.pDevInsR3) { AssertMsgFailed(("Configuration error / Init order error! No APIC!\n")); LogFlow(("pdmR3DevHlp_IOAPICRegister: caller='%s'/%d: returns %Rrc (no APIC)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER)); return VERR_INVALID_PARAMETER; } if ( pIoApicReg->pszSetIrqRC && !pVM->pdm.s.Apic.pDevInsRC) { AssertMsgFailed(("Configuration error! APIC doesn't do GC, I/O APIC does!\n")); LogFlow(("pdmR3DevHlp_IOAPICRegister: caller='%s'/%d: returns %Rrc (no GC APIC)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER)); return VERR_INVALID_PARAMETER; } /* * Only one I/O APIC device. */ if (pVM->pdm.s.IoApic.pDevInsR3) { AssertMsgFailed(("Only one ioapic device is supported!\n")); LogFlow(("pdmR3DevHlp_IOAPICRegister: caller='%s'/%d: returns %Rrc (only one)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER)); return VERR_INVALID_PARAMETER; } /* * Resolve & initialize the GC bits. */ if (pIoApicReg->pszSetIrqRC) { int rc = pdmR3DevGetSymbolRCLazy(pDevIns, pIoApicReg->pszSetIrqRC, &pVM->pdm.s.IoApic.pfnSetIrqRC); AssertMsgRC(rc, ("%s::%s rc=%Rrc\n", pDevIns->pReg->szRCMod, pIoApicReg->pszSetIrqRC, rc)); if (RT_FAILURE(rc)) { LogFlow(("pdmR3DevHlp_IOAPICRegister: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc)); return rc; } pVM->pdm.s.IoApic.pDevInsRC = PDMDEVINS_2_RCPTR(pDevIns); } else { pVM->pdm.s.IoApic.pDevInsRC = 0; pVM->pdm.s.IoApic.pfnSetIrqRC = 0; } if (pIoApicReg->pszSendMsiRC) { int rc = pdmR3DevGetSymbolRCLazy(pDevIns, pIoApicReg->pszSetIrqRC, &pVM->pdm.s.IoApic.pfnSendMsiRC); AssertMsgRC(rc, ("%s::%s rc=%Rrc\n", pDevIns->pReg->szRCMod, pIoApicReg->pszSendMsiRC, rc)); if (RT_FAILURE(rc)) { LogFlow(("pdmR3DevHlp_IOAPICRegister: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc)); return rc; } } else { pVM->pdm.s.IoApic.pfnSendMsiRC = 0; } /* * Resolve & initialize the R0 bits. */ if (pIoApicReg->pszSetIrqR0) { int rc = pdmR3DevGetSymbolR0Lazy(pDevIns, pIoApicReg->pszSetIrqR0, &pVM->pdm.s.IoApic.pfnSetIrqR0); AssertMsgRC(rc, ("%s::%s rc=%Rrc\n", pDevIns->pReg->szR0Mod, pIoApicReg->pszSetIrqR0, rc)); if (RT_FAILURE(rc)) { LogFlow(("pdmR3DevHlp_IOAPICRegister: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc)); return rc; } pVM->pdm.s.IoApic.pDevInsR0 = PDMDEVINS_2_R0PTR(pDevIns); Assert(pVM->pdm.s.IoApic.pDevInsR0); } else { pVM->pdm.s.IoApic.pfnSetIrqR0 = 0; pVM->pdm.s.IoApic.pDevInsR0 = 0; } if (pIoApicReg->pszSendMsiR0) { int rc = pdmR3DevGetSymbolR0Lazy(pDevIns, pIoApicReg->pszSendMsiR0, &pVM->pdm.s.IoApic.pfnSendMsiR0); AssertMsgRC(rc, ("%s::%s rc=%Rrc\n", pDevIns->pReg->szR0Mod, pIoApicReg->pszSendMsiR0, rc)); if (RT_FAILURE(rc)) { LogFlow(("pdmR3DevHlp_IOAPICRegister: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc)); return rc; } } else { pVM->pdm.s.IoApic.pfnSendMsiR0 = 0; } /* * Initialize the R3 bits. */ pVM->pdm.s.IoApic.pDevInsR3 = pDevIns; pVM->pdm.s.IoApic.pfnSetIrqR3 = pIoApicReg->pfnSetIrqR3; pVM->pdm.s.IoApic.pfnSendMsiR3 = pIoApicReg->pfnSendMsiR3; Log(("PDM: Registered I/O APIC device '%s'/%d pDevIns=%p\n", pDevIns->pReg->szName, pDevIns->iInstance, pDevIns)); /* set the helper pointer and return. */ *ppIoApicHlpR3 = &g_pdmR3DevIoApicHlp; LogFlow(("pdmR3DevHlp_IOAPICRegister: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, VINF_SUCCESS)); return VINF_SUCCESS; } /** @interface_method_impl{PDMDEVHLPR3,pfnHPETRegister} */ static DECLCALLBACK(int) pdmR3DevHlp_HPETRegister(PPDMDEVINS pDevIns, PPDMHPETREG pHpetReg, PCPDMHPETHLPR3 *ppHpetHlpR3) { PDMDEV_ASSERT_DEVINS(pDevIns); VM_ASSERT_EMT(pDevIns->Internal.s.pVMR3); LogFlow(("pdmR3DevHlp_HPETRegister: caller='%s'/%d:\n")); /* * Validate input. */ if (pHpetReg->u32Version != PDM_HPETREG_VERSION) { AssertMsgFailed(("u32Version=%#x expected %#x\n", pHpetReg->u32Version, PDM_HPETREG_VERSION)); LogFlow(("pdmR3DevHlp_HPETRegister: caller='%s'/%d: returns %Rrc (version)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER)); return VERR_INVALID_PARAMETER; } if (!ppHpetHlpR3) { Assert(ppHpetHlpR3); LogFlow(("pdmR3DevHlp_HPETRegister: caller='%s'/%d: returns %Rrc (ppApicHlpR3)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER)); return VERR_INVALID_PARAMETER; } /* set the helper pointer and return. */ *ppHpetHlpR3 = &g_pdmR3DevHpetHlp; LogFlow(("pdmR3DevHlp_HPETRegister: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, VINF_SUCCESS)); return VINF_SUCCESS; } /** @interface_method_impl{PDMDEVHLPR3,pfnPciRawRegister} */ static DECLCALLBACK(int) pdmR3DevHlp_PciRawRegister(PPDMDEVINS pDevIns, PPDMPCIRAWREG pPciRawReg, PCPDMPCIRAWHLPR3 *ppPciRawHlpR3) { PDMDEV_ASSERT_DEVINS(pDevIns); VM_ASSERT_EMT(pDevIns->Internal.s.pVMR3); LogFlow(("pdmR3DevHlp_PciRawRegister: caller='%s'/%d:\n")); /* * Validate input. */ if (pPciRawReg->u32Version != PDM_PCIRAWREG_VERSION) { AssertMsgFailed(("u32Version=%#x expected %#x\n", pPciRawReg->u32Version, PDM_PCIRAWREG_VERSION)); LogFlow(("pdmR3DevHlp_PciRawRegister: caller='%s'/%d: returns %Rrc (version)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER)); return VERR_INVALID_PARAMETER; } if (!ppPciRawHlpR3) { Assert(ppPciRawHlpR3); LogFlow(("pdmR3DevHlp_PciRawRegister: caller='%s'/%d: returns %Rrc (ppApicHlpR3)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER)); return VERR_INVALID_PARAMETER; } /* set the helper pointer and return. */ *ppPciRawHlpR3 = &g_pdmR3DevPciRawHlp; LogFlow(("pdmR3DevHlp_PciRawRegister: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, VINF_SUCCESS)); return VINF_SUCCESS; } /** @interface_method_impl{PDMDEVHLPR3,pfnDMACRegister} */ static DECLCALLBACK(int) pdmR3DevHlp_DMACRegister(PPDMDEVINS pDevIns, PPDMDMACREG pDmacReg, PCPDMDMACHLP *ppDmacHlp) { PDMDEV_ASSERT_DEVINS(pDevIns); VM_ASSERT_EMT(pDevIns->Internal.s.pVMR3); LogFlow(("pdmR3DevHlp_DMACRegister: caller='%s'/%d: pDmacReg=%p:{.u32Version=%#x, .pfnRun=%p, .pfnRegister=%p, .pfnReadMemory=%p, .pfnWriteMemory=%p, .pfnSetDREQ=%p, .pfnGetChannelMode=%p} ppDmacHlp=%p\n", pDevIns->pReg->szName, pDevIns->iInstance, pDmacReg, pDmacReg->u32Version, pDmacReg->pfnRun, pDmacReg->pfnRegister, pDmacReg->pfnReadMemory, pDmacReg->pfnWriteMemory, pDmacReg->pfnSetDREQ, pDmacReg->pfnGetChannelMode, ppDmacHlp)); /* * Validate input. */ if (pDmacReg->u32Version != PDM_DMACREG_VERSION) { AssertMsgFailed(("u32Version=%#x expected %#x\n", pDmacReg->u32Version, PDM_DMACREG_VERSION)); LogFlow(("pdmR3DevHlp_DMACRegister: caller='%s'/%d: returns %Rrc (version)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER)); return VERR_INVALID_PARAMETER; } if ( !pDmacReg->pfnRun || !pDmacReg->pfnRegister || !pDmacReg->pfnReadMemory || !pDmacReg->pfnWriteMemory || !pDmacReg->pfnSetDREQ || !pDmacReg->pfnGetChannelMode) { Assert(pDmacReg->pfnRun); Assert(pDmacReg->pfnRegister); Assert(pDmacReg->pfnReadMemory); Assert(pDmacReg->pfnWriteMemory); Assert(pDmacReg->pfnSetDREQ); Assert(pDmacReg->pfnGetChannelMode); LogFlow(("pdmR3DevHlp_DMACRegister: caller='%s'/%d: returns %Rrc (callbacks)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER)); return VERR_INVALID_PARAMETER; } if (!ppDmacHlp) { Assert(ppDmacHlp); LogFlow(("pdmR3DevHlp_DMACRegister: caller='%s'/%d: returns %Rrc (ppDmacHlp)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER)); return VERR_INVALID_PARAMETER; } /* * Only one DMA device. */ PVM pVM = pDevIns->Internal.s.pVMR3; if (pVM->pdm.s.pDmac) { AssertMsgFailed(("Only one DMA device is supported!\n")); LogFlow(("pdmR3DevHlp_DMACRegister: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER)); return VERR_INVALID_PARAMETER; } /* * Allocate and initialize pci bus structure. */ int rc = VINF_SUCCESS; PPDMDMAC pDmac = (PPDMDMAC)MMR3HeapAlloc(pDevIns->Internal.s.pVMR3, MM_TAG_PDM_DEVICE, sizeof(*pDmac)); if (pDmac) { pDmac->pDevIns = pDevIns; pDmac->Reg = *pDmacReg; pVM->pdm.s.pDmac = pDmac; /* set the helper pointer. */ *ppDmacHlp = &g_pdmR3DevDmacHlp; Log(("PDM: Registered DMAC device '%s'/%d pDevIns=%p\n", pDevIns->pReg->szName, pDevIns->iInstance, pDevIns)); } else rc = VERR_NO_MEMORY; LogFlow(("pdmR3DevHlp_DMACRegister: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc)); return rc; } /** * @copydoc PDMDEVHLPR3::pfnRegisterVMMDevHeap */ static DECLCALLBACK(int) pdmR3DevHlp_RegisterVMMDevHeap(PPDMDEVINS pDevIns, RTGCPHYS GCPhys, RTR3PTR pvHeap, unsigned cbSize) { PDMDEV_ASSERT_DEVINS(pDevIns); VM_ASSERT_EMT(pDevIns->Internal.s.pVMR3); int rc = PDMR3VmmDevHeapRegister(pDevIns->Internal.s.pVMR3, GCPhys, pvHeap, cbSize); return rc; } /** * @copydoc PDMDEVHLPR3::pfnUnregisterVMMDevHeap */ static DECLCALLBACK(int) pdmR3DevHlp_UnregisterVMMDevHeap(PPDMDEVINS pDevIns, RTGCPHYS GCPhys) { PDMDEV_ASSERT_DEVINS(pDevIns); VM_ASSERT_EMT(pDevIns->Internal.s.pVMR3); int rc = PDMR3VmmDevHeapUnregister(pDevIns->Internal.s.pVMR3, GCPhys); return rc; } /** @interface_method_impl{PDMDEVHLPR3,pfnVMReset} */ static DECLCALLBACK(int) pdmR3DevHlp_VMReset(PPDMDEVINS pDevIns) { PDMDEV_ASSERT_DEVINS(pDevIns); PVM pVM = pDevIns->Internal.s.pVMR3; VM_ASSERT_EMT(pVM); LogFlow(("pdmR3DevHlp_VMReset: caller='%s'/%d: VM_FF_RESET %d -> 1\n", pDevIns->pReg->szName, pDevIns->iInstance, VM_FF_IS_SET(pVM, VM_FF_RESET))); /* * We postpone this operation because we're likely to be inside a I/O instruction * and the EIP will be updated when we return. * We still return VINF_EM_RESET to break out of any execution loops and force FF evaluation. */ bool fHaltOnReset; int rc = CFGMR3QueryBool(CFGMR3GetChild(CFGMR3GetRoot(pVM), "PDM"), "HaltOnReset", &fHaltOnReset); if (RT_SUCCESS(rc) && fHaltOnReset) { Log(("pdmR3DevHlp_VMReset: Halt On Reset!\n")); rc = VINF_EM_HALT; } else { VM_FF_SET(pVM, VM_FF_RESET); rc = VINF_EM_RESET; } LogFlow(("pdmR3DevHlp_VMReset: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc)); return rc; } /** @interface_method_impl{PDMDEVHLPR3,pfnVMSuspend} */ static DECLCALLBACK(int) pdmR3DevHlp_VMSuspend(PPDMDEVINS pDevIns) { int rc; PDMDEV_ASSERT_DEVINS(pDevIns); PVM pVM = pDevIns->Internal.s.pVMR3; VM_ASSERT_EMT(pVM); LogFlow(("pdmR3DevHlp_VMSuspend: caller='%s'/%d:\n", pDevIns->pReg->szName, pDevIns->iInstance)); /** @todo Always take the SMP path - fewer code paths. */ if (pVM->cCpus > 1) { /* We own the IOM lock here and could cause a deadlock by waiting for a VCPU that is blocking on the IOM lock. */ rc = VMR3ReqCallNoWait(pVM, VMCPUID_ANY_QUEUE, (PFNRT)VMR3Suspend, 2, pVM->pUVM, VMSUSPENDREASON_VM); AssertRC(rc); rc = VINF_EM_SUSPEND; } else rc = VMR3Suspend(pVM->pUVM, VMSUSPENDREASON_VM); LogFlow(("pdmR3DevHlp_VMSuspend: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc)); return rc; } /** * Worker for pdmR3DevHlp_VMSuspendSaveAndPowerOff that is invoked via a queued * EMT request to avoid deadlocks. * * @returns VBox status code fit for scheduling. * @param pVM Pointer to the VM. * @param pDevIns The device that triggered this action. */ static DECLCALLBACK(int) pdmR3DevHlp_VMSuspendSaveAndPowerOffWorker(PVM pVM, PPDMDEVINS pDevIns) { /* * Suspend the VM first then do the saving. */ int rc = VMR3Suspend(pVM->pUVM, VMSUSPENDREASON_VM); if (RT_SUCCESS(rc)) { PUVM pUVM = pVM->pUVM; rc = pUVM->pVmm2UserMethods->pfnSaveState(pVM->pUVM->pVmm2UserMethods, pUVM); /* * On success, power off the VM, on failure we'll leave it suspended. */ if (RT_SUCCESS(rc)) { rc = VMR3PowerOff(pVM->pUVM); if (RT_FAILURE(rc)) LogRel(("%s/SSP: VMR3PowerOff failed: %Rrc\n", pDevIns->pReg->szName, rc)); } else LogRel(("%s/SSP: pfnSaveState failed: %Rrc\n", pDevIns->pReg->szName, rc)); } else LogRel(("%s/SSP: Suspend failed: %Rrc\n", pDevIns->pReg->szName, rc)); return rc; } /** @interface_method_impl{PDMDEVHLPR3,pfnVMSuspendSaveAndPowerOff} */ static DECLCALLBACK(int) pdmR3DevHlp_VMSuspendSaveAndPowerOff(PPDMDEVINS pDevIns) { PDMDEV_ASSERT_DEVINS(pDevIns); PVM pVM = pDevIns->Internal.s.pVMR3; VM_ASSERT_EMT(pVM); LogFlow(("pdmR3DevHlp_VMSuspendSaveAndPowerOff: caller='%s'/%d:\n", pDevIns->pReg->szName, pDevIns->iInstance)); int rc; if ( pVM->pUVM->pVmm2UserMethods && pVM->pUVM->pVmm2UserMethods->pfnSaveState) { rc = VMR3ReqCallNoWait(pVM, VMCPUID_ANY_QUEUE, (PFNRT)pdmR3DevHlp_VMSuspendSaveAndPowerOffWorker, 2, pVM, pDevIns); if (RT_SUCCESS(rc)) { LogRel(("%s: Suspending, Saving and Powering Off the VM\n", pDevIns->pReg->szName)); rc = VINF_EM_SUSPEND; } } else rc = VERR_NOT_SUPPORTED; LogFlow(("pdmR3DevHlp_VMSuspendSaveAndPowerOff: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc)); return rc; } /** @interface_method_impl{PDMDEVHLPR3,pfnVMPowerOff} */ static DECLCALLBACK(int) pdmR3DevHlp_VMPowerOff(PPDMDEVINS pDevIns) { int rc; PDMDEV_ASSERT_DEVINS(pDevIns); PVM pVM = pDevIns->Internal.s.pVMR3; VM_ASSERT_EMT(pVM); LogFlow(("pdmR3DevHlp_VMPowerOff: caller='%s'/%d:\n", pDevIns->pReg->szName, pDevIns->iInstance)); /** @todo Always take the SMP path - fewer code paths. */ if (pVM->cCpus > 1) { /* We might be holding locks here and could cause a deadlock since VMR3PowerOff rendezvous with the other CPUs. */ rc = VMR3ReqCallNoWait(pVM, VMCPUID_ANY_QUEUE, (PFNRT)VMR3PowerOff, 1, pVM->pUVM); AssertRC(rc); /* Set the VCPU state to stopped here as well to make sure no inconsistency with the EM state occurs. */ VMCPU_SET_STATE(VMMGetCpu(pVM), VMCPUSTATE_STOPPED); rc = VINF_EM_OFF; } else rc = VMR3PowerOff(pVM->pUVM); LogFlow(("pdmR3DevHlp_VMPowerOff: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc)); return rc; } /** @interface_method_impl{PDMDEVHLPR3,pfnA20IsEnabled} */ static DECLCALLBACK(bool) pdmR3DevHlp_A20IsEnabled(PPDMDEVINS pDevIns) { PDMDEV_ASSERT_DEVINS(pDevIns); VM_ASSERT_EMT(pDevIns->Internal.s.pVMR3); bool fRc = PGMPhysIsA20Enabled(VMMGetCpu(pDevIns->Internal.s.pVMR3)); LogFlow(("pdmR3DevHlp_A20IsEnabled: caller='%s'/%d: returns %d\n", pDevIns->pReg->szName, pDevIns->iInstance, fRc)); return fRc; } /** @interface_method_impl{PDMDEVHLPR3,pfnA20Set} */ static DECLCALLBACK(void) pdmR3DevHlp_A20Set(PPDMDEVINS pDevIns, bool fEnable) { PDMDEV_ASSERT_DEVINS(pDevIns); VM_ASSERT_EMT(pDevIns->Internal.s.pVMR3); LogFlow(("pdmR3DevHlp_A20Set: caller='%s'/%d: fEnable=%d\n", pDevIns->pReg->szName, pDevIns->iInstance, fEnable)); PGMR3PhysSetA20(VMMGetCpu(pDevIns->Internal.s.pVMR3), fEnable); } /** @interface_method_impl{PDMDEVHLPR3,pfnGetCpuId} */ static DECLCALLBACK(void) pdmR3DevHlp_GetCpuId(PPDMDEVINS pDevIns, uint32_t iLeaf, uint32_t *pEax, uint32_t *pEbx, uint32_t *pEcx, uint32_t *pEdx) { PDMDEV_ASSERT_DEVINS(pDevIns); VM_ASSERT_EMT(pDevIns->Internal.s.pVMR3); LogFlow(("pdmR3DevHlp_GetCpuId: caller='%s'/%d: iLeaf=%d pEax=%p pEbx=%p pEcx=%p pEdx=%p\n", pDevIns->pReg->szName, pDevIns->iInstance, iLeaf, pEax, pEbx, pEcx, pEdx)); AssertPtr(pEax); AssertPtr(pEbx); AssertPtr(pEcx); AssertPtr(pEdx); CPUMGetGuestCpuId(VMMGetCpu(pDevIns->Internal.s.pVMR3), iLeaf, 0 /*iSubLeaf*/, pEax, pEbx, pEcx, pEdx); LogFlow(("pdmR3DevHlp_GetCpuId: caller='%s'/%d: returns void - *pEax=%#x *pEbx=%#x *pEcx=%#x *pEdx=%#x\n", pDevIns->pReg->szName, pDevIns->iInstance, *pEax, *pEbx, *pEcx, *pEdx)); } /** * The device helper structure for trusted devices. */ const PDMDEVHLPR3 g_pdmR3DevHlpTrusted = { PDM_DEVHLPR3_VERSION, pdmR3DevHlp_IOPortRegister, pdmR3DevHlp_IOPortRegisterRC, pdmR3DevHlp_IOPortRegisterR0, pdmR3DevHlp_IOPortDeregister, pdmR3DevHlp_MMIORegister, pdmR3DevHlp_MMIORegisterRC, pdmR3DevHlp_MMIORegisterR0, pdmR3DevHlp_MMIODeregister, pdmR3DevHlp_MMIO2Register, pdmR3DevHlp_MMIO2Deregister, pdmR3DevHlp_MMIO2Map, pdmR3DevHlp_MMIO2Unmap, pdmR3DevHlp_MMHyperMapMMIO2, pdmR3DevHlp_MMIO2MapKernel, pdmR3DevHlp_ROMRegister, pdmR3DevHlp_ROMProtectShadow, pdmR3DevHlp_SSMRegister, pdmR3DevHlp_TMTimerCreate, pdmR3DevHlp_TMUtcNow, pdmR3DevHlp_PhysRead, pdmR3DevHlp_PhysWrite, pdmR3DevHlp_PhysGCPhys2CCPtr, pdmR3DevHlp_PhysGCPhys2CCPtrReadOnly, pdmR3DevHlp_PhysReleasePageMappingLock, pdmR3DevHlp_PhysReadGCVirt, pdmR3DevHlp_PhysWriteGCVirt, pdmR3DevHlp_PhysGCPtr2GCPhys, pdmR3DevHlp_MMHeapAlloc, pdmR3DevHlp_MMHeapAllocZ, pdmR3DevHlp_MMHeapFree, pdmR3DevHlp_VMState, pdmR3DevHlp_VMTeleportedAndNotFullyResumedYet, pdmR3DevHlp_VMSetError, pdmR3DevHlp_VMSetErrorV, pdmR3DevHlp_VMSetRuntimeError, pdmR3DevHlp_VMSetRuntimeErrorV, pdmR3DevHlp_DBGFStopV, pdmR3DevHlp_DBGFInfoRegister, pdmR3DevHlp_DBGFRegRegister, pdmR3DevHlp_DBGFTraceBuf, pdmR3DevHlp_STAMRegister, pdmR3DevHlp_STAMRegisterF, pdmR3DevHlp_STAMRegisterV, pdmR3DevHlp_PCIRegister, pdmR3DevHlp_PCIRegisterMsi, pdmR3DevHlp_PCIIORegionRegister, pdmR3DevHlp_PCISetConfigCallbacks, pdmR3DevHlp_PCIPhysRead, pdmR3DevHlp_PCIPhysWrite, pdmR3DevHlp_PCISetIrq, pdmR3DevHlp_PCISetIrqNoWait, pdmR3DevHlp_ISASetIrq, pdmR3DevHlp_ISASetIrqNoWait, pdmR3DevHlp_DriverAttach, pdmR3DevHlp_QueueCreate, pdmR3DevHlp_CritSectInit, pdmR3DevHlp_CritSectGetNop, pdmR3DevHlp_CritSectGetNopR0, pdmR3DevHlp_CritSectGetNopRC, pdmR3DevHlp_SetDeviceCritSect, pdmR3DevHlp_ThreadCreate, pdmR3DevHlp_SetAsyncNotification, pdmR3DevHlp_AsyncNotificationCompleted, pdmR3DevHlp_RTCRegister, pdmR3DevHlp_PCIBusRegister, pdmR3DevHlp_PICRegister, pdmR3DevHlp_APICRegister, pdmR3DevHlp_IOAPICRegister, pdmR3DevHlp_HPETRegister, pdmR3DevHlp_PciRawRegister, pdmR3DevHlp_DMACRegister, pdmR3DevHlp_DMARegister, pdmR3DevHlp_DMAReadMemory, pdmR3DevHlp_DMAWriteMemory, pdmR3DevHlp_DMASetDREQ, pdmR3DevHlp_DMAGetChannelMode, pdmR3DevHlp_DMASchedule, pdmR3DevHlp_CMOSWrite, pdmR3DevHlp_CMOSRead, pdmR3DevHlp_AssertEMT, pdmR3DevHlp_AssertOther, pdmR3DevHlp_LdrGetRCInterfaceSymbols, pdmR3DevHlp_LdrGetR0InterfaceSymbols, pdmR3DevHlp_CallR0, pdmR3DevHlp_VMGetSuspendReason, pdmR3DevHlp_VMGetResumeReason, 0, 0, 0, 0, 0, 0, 0, pdmR3DevHlp_GetUVM, pdmR3DevHlp_GetVM, pdmR3DevHlp_GetVMCPU, pdmR3DevHlp_GetCurrentCpuId, pdmR3DevHlp_RegisterVMMDevHeap, pdmR3DevHlp_UnregisterVMMDevHeap, pdmR3DevHlp_VMReset, pdmR3DevHlp_VMSuspend, pdmR3DevHlp_VMSuspendSaveAndPowerOff, pdmR3DevHlp_VMPowerOff, pdmR3DevHlp_A20IsEnabled, pdmR3DevHlp_A20Set, pdmR3DevHlp_GetCpuId, pdmR3DevHlp_TMTimeVirtGet, pdmR3DevHlp_TMTimeVirtGetFreq, pdmR3DevHlp_TMTimeVirtGetNano, pdmR3DevHlp_GetSupDrvSession, PDM_DEVHLPR3_VERSION /* the end */ }; /** @interface_method_impl{PDMDEVHLPR3,pfnGetUVM} */ static DECLCALLBACK(PUVM) pdmR3DevHlp_Untrusted_GetUVM(PPDMDEVINS pDevIns) { PDMDEV_ASSERT_DEVINS(pDevIns); AssertReleaseMsgFailed(("Untrusted device called trusted helper! '%s'/%d\n", pDevIns->pReg->szName, pDevIns->iInstance)); return NULL; } /** @interface_method_impl{PDMDEVHLPR3,pfnGetVM} */ static DECLCALLBACK(PVM) pdmR3DevHlp_Untrusted_GetVM(PPDMDEVINS pDevIns) { PDMDEV_ASSERT_DEVINS(pDevIns); AssertReleaseMsgFailed(("Untrusted device called trusted helper! '%s'/%d\n", pDevIns->pReg->szName, pDevIns->iInstance)); return NULL; } /** @interface_method_impl{PDMDEVHLPR3,pfnGetVMCPU} */ static DECLCALLBACK(PVMCPU) pdmR3DevHlp_Untrusted_GetVMCPU(PPDMDEVINS pDevIns) { PDMDEV_ASSERT_DEVINS(pDevIns); AssertReleaseMsgFailed(("Untrusted device called trusted helper! '%s'/%d\n", pDevIns->pReg->szName, pDevIns->iInstance)); return NULL; } /** @interface_method_impl{PDMDEVHLPR3,pfnGetCurrentCpuId} */ static DECLCALLBACK(VMCPUID) pdmR3DevHlp_Untrusted_GetCurrentCpuId(PPDMDEVINS pDevIns) { PDMDEV_ASSERT_DEVINS(pDevIns); AssertReleaseMsgFailed(("Untrusted device called trusted helper! '%s'/%d\n", pDevIns->pReg->szName, pDevIns->iInstance)); return NIL_VMCPUID; } /** @interface_method_impl{PDMDEVHLPR3,pfnRegisterVMMDevHeap} */ static DECLCALLBACK(int) pdmR3DevHlp_Untrusted_RegisterVMMDevHeap(PPDMDEVINS pDevIns, RTGCPHYS GCPhys, RTR3PTR pvHeap, unsigned cbSize) { PDMDEV_ASSERT_DEVINS(pDevIns); NOREF(GCPhys); NOREF(pvHeap); NOREF(cbSize); AssertReleaseMsgFailed(("Untrusted device called trusted helper! '%s'/%d\n", pDevIns->pReg->szName, pDevIns->iInstance)); return VERR_ACCESS_DENIED; } /** @interface_method_impl{PDMDEVHLPR3,pfnUnregisterVMMDevHeap} */ static DECLCALLBACK(int) pdmR3DevHlp_Untrusted_UnregisterVMMDevHeap(PPDMDEVINS pDevIns, RTGCPHYS GCPhys) { PDMDEV_ASSERT_DEVINS(pDevIns); NOREF(GCPhys); AssertReleaseMsgFailed(("Untrusted device called trusted helper! '%s'/%d\n", pDevIns->pReg->szName, pDevIns->iInstance)); return VERR_ACCESS_DENIED; } /** @interface_method_impl{PDMDEVHLPR3,pfnVMReset} */ static DECLCALLBACK(int) pdmR3DevHlp_Untrusted_VMReset(PPDMDEVINS pDevIns) { PDMDEV_ASSERT_DEVINS(pDevIns); AssertReleaseMsgFailed(("Untrusted device called trusted helper! '%s'/%d\n", pDevIns->pReg->szName, pDevIns->iInstance)); return VERR_ACCESS_DENIED; } /** @interface_method_impl{PDMDEVHLPR3,pfnVMSuspend} */ static DECLCALLBACK(int) pdmR3DevHlp_Untrusted_VMSuspend(PPDMDEVINS pDevIns) { PDMDEV_ASSERT_DEVINS(pDevIns); AssertReleaseMsgFailed(("Untrusted device called trusted helper! '%s'/%d\n", pDevIns->pReg->szName, pDevIns->iInstance)); return VERR_ACCESS_DENIED; } /** @interface_method_impl{PDMDEVHLPR3,pfnVMSuspendSaveAndPowerOff} */ static DECLCALLBACK(int) pdmR3DevHlp_Untrusted_VMSuspendSaveAndPowerOff(PPDMDEVINS pDevIns) { PDMDEV_ASSERT_DEVINS(pDevIns); AssertReleaseMsgFailed(("Untrusted device called trusted helper! '%s'/%d\n", pDevIns->pReg->szName, pDevIns->iInstance)); return VERR_ACCESS_DENIED; } /** @interface_method_impl{PDMDEVHLPR3,pfnVMPowerOff} */ static DECLCALLBACK(int) pdmR3DevHlp_Untrusted_VMPowerOff(PPDMDEVINS pDevIns) { PDMDEV_ASSERT_DEVINS(pDevIns); AssertReleaseMsgFailed(("Untrusted device called trusted helper! '%s'/%d\n", pDevIns->pReg->szName, pDevIns->iInstance)); return VERR_ACCESS_DENIED; } /** @interface_method_impl{PDMDEVHLPR3,pfnA20IsEnabled} */ static DECLCALLBACK(bool) pdmR3DevHlp_Untrusted_A20IsEnabled(PPDMDEVINS pDevIns) { PDMDEV_ASSERT_DEVINS(pDevIns); AssertReleaseMsgFailed(("Untrusted device called trusted helper! '%s'/%d\n", pDevIns->pReg->szName, pDevIns->iInstance)); return false; } /** @interface_method_impl{PDMDEVHLPR3,pfnA20Set} */ static DECLCALLBACK(void) pdmR3DevHlp_Untrusted_A20Set(PPDMDEVINS pDevIns, bool fEnable) { PDMDEV_ASSERT_DEVINS(pDevIns); AssertReleaseMsgFailed(("Untrusted device called trusted helper! '%s'/%d\n", pDevIns->pReg->szName, pDevIns->iInstance)); NOREF(fEnable); } /** @interface_method_impl{PDMDEVHLPR3,pfnGetCpuId} */ static DECLCALLBACK(void) pdmR3DevHlp_Untrusted_GetCpuId(PPDMDEVINS pDevIns, uint32_t iLeaf, uint32_t *pEax, uint32_t *pEbx, uint32_t *pEcx, uint32_t *pEdx) { PDMDEV_ASSERT_DEVINS(pDevIns); NOREF(iLeaf); NOREF(pEax); NOREF(pEbx); NOREF(pEcx); NOREF(pEdx); AssertReleaseMsgFailed(("Untrusted device called trusted helper! '%s'/%d\n", pDevIns->pReg->szName, pDevIns->iInstance)); } /** @interface_method_impl{PDMDEVHLPR3,pfnGetSupDrvSession} */ static DECLCALLBACK(PSUPDRVSESSION) pdmR3DevHlp_Untrusted_GetSupDrvSession(PPDMDEVINS pDevIns) { PDMDEV_ASSERT_DEVINS(pDevIns); AssertReleaseMsgFailed(("Untrusted device called trusted helper! '%s'/%d\n", pDevIns->pReg->szName, pDevIns->iInstance)); return (PSUPDRVSESSION)0; } /** * The device helper structure for non-trusted devices. */ const PDMDEVHLPR3 g_pdmR3DevHlpUnTrusted = { PDM_DEVHLPR3_VERSION, pdmR3DevHlp_IOPortRegister, pdmR3DevHlp_IOPortRegisterRC, pdmR3DevHlp_IOPortRegisterR0, pdmR3DevHlp_IOPortDeregister, pdmR3DevHlp_MMIORegister, pdmR3DevHlp_MMIORegisterRC, pdmR3DevHlp_MMIORegisterR0, pdmR3DevHlp_MMIODeregister, pdmR3DevHlp_MMIO2Register, pdmR3DevHlp_MMIO2Deregister, pdmR3DevHlp_MMIO2Map, pdmR3DevHlp_MMIO2Unmap, pdmR3DevHlp_MMHyperMapMMIO2, pdmR3DevHlp_MMIO2MapKernel, pdmR3DevHlp_ROMRegister, pdmR3DevHlp_ROMProtectShadow, pdmR3DevHlp_SSMRegister, pdmR3DevHlp_TMTimerCreate, pdmR3DevHlp_TMUtcNow, pdmR3DevHlp_PhysRead, pdmR3DevHlp_PhysWrite, pdmR3DevHlp_PhysGCPhys2CCPtr, pdmR3DevHlp_PhysGCPhys2CCPtrReadOnly, pdmR3DevHlp_PhysReleasePageMappingLock, pdmR3DevHlp_PhysReadGCVirt, pdmR3DevHlp_PhysWriteGCVirt, pdmR3DevHlp_PhysGCPtr2GCPhys, pdmR3DevHlp_MMHeapAlloc, pdmR3DevHlp_MMHeapAllocZ, pdmR3DevHlp_MMHeapFree, pdmR3DevHlp_VMState, pdmR3DevHlp_VMTeleportedAndNotFullyResumedYet, pdmR3DevHlp_VMSetError, pdmR3DevHlp_VMSetErrorV, pdmR3DevHlp_VMSetRuntimeError, pdmR3DevHlp_VMSetRuntimeErrorV, pdmR3DevHlp_DBGFStopV, pdmR3DevHlp_DBGFInfoRegister, pdmR3DevHlp_DBGFRegRegister, pdmR3DevHlp_DBGFTraceBuf, pdmR3DevHlp_STAMRegister, pdmR3DevHlp_STAMRegisterF, pdmR3DevHlp_STAMRegisterV, pdmR3DevHlp_PCIRegister, pdmR3DevHlp_PCIRegisterMsi, pdmR3DevHlp_PCIIORegionRegister, pdmR3DevHlp_PCISetConfigCallbacks, pdmR3DevHlp_PCIPhysRead, pdmR3DevHlp_PCIPhysWrite, pdmR3DevHlp_PCISetIrq, pdmR3DevHlp_PCISetIrqNoWait, pdmR3DevHlp_ISASetIrq, pdmR3DevHlp_ISASetIrqNoWait, pdmR3DevHlp_DriverAttach, pdmR3DevHlp_QueueCreate, pdmR3DevHlp_CritSectInit, pdmR3DevHlp_CritSectGetNop, pdmR3DevHlp_CritSectGetNopR0, pdmR3DevHlp_CritSectGetNopRC, pdmR3DevHlp_SetDeviceCritSect, pdmR3DevHlp_ThreadCreate, pdmR3DevHlp_SetAsyncNotification, pdmR3DevHlp_AsyncNotificationCompleted, pdmR3DevHlp_RTCRegister, pdmR3DevHlp_PCIBusRegister, pdmR3DevHlp_PICRegister, pdmR3DevHlp_APICRegister, pdmR3DevHlp_IOAPICRegister, pdmR3DevHlp_HPETRegister, pdmR3DevHlp_PciRawRegister, pdmR3DevHlp_DMACRegister, pdmR3DevHlp_DMARegister, pdmR3DevHlp_DMAReadMemory, pdmR3DevHlp_DMAWriteMemory, pdmR3DevHlp_DMASetDREQ, pdmR3DevHlp_DMAGetChannelMode, pdmR3DevHlp_DMASchedule, pdmR3DevHlp_CMOSWrite, pdmR3DevHlp_CMOSRead, pdmR3DevHlp_AssertEMT, pdmR3DevHlp_AssertOther, pdmR3DevHlp_LdrGetRCInterfaceSymbols, pdmR3DevHlp_LdrGetR0InterfaceSymbols, pdmR3DevHlp_CallR0, pdmR3DevHlp_VMGetSuspendReason, pdmR3DevHlp_VMGetResumeReason, 0, 0, 0, 0, 0, 0, 0, pdmR3DevHlp_Untrusted_GetUVM, pdmR3DevHlp_Untrusted_GetVM, pdmR3DevHlp_Untrusted_GetVMCPU, pdmR3DevHlp_Untrusted_GetCurrentCpuId, pdmR3DevHlp_Untrusted_RegisterVMMDevHeap, pdmR3DevHlp_Untrusted_UnregisterVMMDevHeap, pdmR3DevHlp_Untrusted_VMReset, pdmR3DevHlp_Untrusted_VMSuspend, pdmR3DevHlp_Untrusted_VMSuspendSaveAndPowerOff, pdmR3DevHlp_Untrusted_VMPowerOff, pdmR3DevHlp_Untrusted_A20IsEnabled, pdmR3DevHlp_Untrusted_A20Set, pdmR3DevHlp_Untrusted_GetCpuId, pdmR3DevHlp_TMTimeVirtGet, pdmR3DevHlp_TMTimeVirtGetFreq, pdmR3DevHlp_TMTimeVirtGetNano, pdmR3DevHlp_Untrusted_GetSupDrvSession, PDM_DEVHLPR3_VERSION /* the end */ }; /** * Queue consumer callback for internal component. * * @returns Success indicator. * If false the item will not be removed and the flushing will stop. * @param pVM Pointer to the VM. * @param pItem The item to consume. Upon return this item will be freed. */ DECLCALLBACK(bool) pdmR3DevHlpQueueConsumer(PVM pVM, PPDMQUEUEITEMCORE pItem) { PPDMDEVHLPTASK pTask = (PPDMDEVHLPTASK)pItem; LogFlow(("pdmR3DevHlpQueueConsumer: enmOp=%d pDevIns=%p\n", pTask->enmOp, pTask->pDevInsR3)); switch (pTask->enmOp) { case PDMDEVHLPTASKOP_ISA_SET_IRQ: PDMIsaSetIrq(pVM, pTask->u.SetIRQ.iIrq, pTask->u.SetIRQ.iLevel, pTask->u.SetIRQ.uTagSrc); break; case PDMDEVHLPTASKOP_PCI_SET_IRQ: { /* Same as pdmR3DevHlp_PCISetIrq, except we've got a tag already. */ PPDMDEVINS pDevIns = pTask->pDevInsR3; PPCIDEVICE pPciDev = pDevIns->Internal.s.pPciDeviceR3; if (pPciDev) { PPDMPCIBUS pBus = pDevIns->Internal.s.pPciBusR3; /** @todo the bus should be associated with the PCI device not the PDM device. */ Assert(pBus); pdmLock(pVM); pBus->pfnSetIrqR3(pBus->pDevInsR3, pPciDev, pTask->u.SetIRQ.iIrq, pTask->u.SetIRQ.iLevel, pTask->u.SetIRQ.uTagSrc); pdmUnlock(pVM); } else AssertReleaseMsgFailed(("No PCI device registered!\n")); break; } case PDMDEVHLPTASKOP_IOAPIC_SET_IRQ: PDMIoApicSetIrq(pVM, pTask->u.SetIRQ.iIrq, pTask->u.SetIRQ.iLevel, pTask->u.SetIRQ.uTagSrc); break; default: AssertReleaseMsgFailed(("Invalid operation %d\n", pTask->enmOp)); break; } return true; } /** @} */
Java
package com.avrgaming.civcraft.endgame; import java.util.ArrayList; import com.avrgaming.civcraft.main.CivGlobal; import com.avrgaming.civcraft.main.CivMessage; import com.avrgaming.civcraft.object.Civilization; import com.avrgaming.civcraft.object.Town; import com.avrgaming.civcraft.sessiondb.SessionEntry; import com.avrgaming.civcraft.structure.wonders.Wonder; public class EndConditionScience extends EndGameCondition { String techname; @Override public void onLoad() { techname = this.getString("tech"); } @Override public boolean check(Civilization civ) { if (!civ.hasTechnology(techname)) { return false; } if (civ.isAdminCiv()) { return false; } boolean hasGreatLibrary = false; for (Town town : civ.getTowns()) { if (town.getMotherCiv() != null) { continue; } for (Wonder wonder :town.getWonders()) { if (wonder.isActive()) { if (wonder.getConfigId().equals("w_greatlibrary")) { hasGreatLibrary = true; break; } } } if (hasGreatLibrary) { break; } } if (!hasGreatLibrary) { return false; } return true; } @Override public boolean finalWinCheck(Civilization civ) { Civilization rival = getMostAccumulatedBeakers(); if (rival != civ) { CivMessage.global(civ.getName()+" doesn't have enough beakers for a scientific victory. The rival civilization of "+rival.getName()+" has more!"); return false; } return true; } public Civilization getMostAccumulatedBeakers() { double most = 0; Civilization mostCiv = null; for (Civilization civ : CivGlobal.getCivs()) { double beakers = getExtraBeakersInCiv(civ); if (beakers > most) { most = beakers; mostCiv = civ; } } return mostCiv; } @Override public String getSessionKey() { return "endgame:science"; } @Override protected void onWarDefeat(Civilization civ) { /* remove any extra beakers we might have. */ CivGlobal.getSessionDB().delete_all(getBeakerSessionKey(civ)); civ.removeTech(techname); CivMessage.sendCiv(civ, "We were defeated while trying to achieve a science victory! We've lost all of our accumulated beakers and our victory tech!"); civ.save(); this.onFailure(civ); } public static String getBeakerSessionKey(Civilization civ) { return "endgame:sciencebeakers:"+civ.getId(); } public double getExtraBeakersInCiv(Civilization civ) { ArrayList<SessionEntry> entries = CivGlobal.getSessionDB().lookup(getBeakerSessionKey(civ)); if (entries.size() == 0) { return 0; } return Double.valueOf(entries.get(0).value); } public void addExtraBeakersToCiv(Civilization civ, double beakers) { ArrayList<SessionEntry> entries = CivGlobal.getSessionDB().lookup(getBeakerSessionKey(civ)); double current = 0; if (entries.size() == 0) { CivGlobal.getSessionDB().add(getBeakerSessionKey(civ), ""+beakers, civ.getId(), 0, 0); current += beakers; } else { current = Double.valueOf(entries.get(0).value); current += beakers; CivGlobal.getSessionDB().update(entries.get(0).request_id, entries.get(0).key, ""+current); } //DecimalFormat df = new DecimalFormat("#.#"); //CivMessage.sendCiv(civ, "Added "+df.format(beakers)+" beakers to our scientific victory! We now have "+df.format(current)+" beakers saved up."); } public static Double getBeakersFor(Civilization civ) { ArrayList<SessionEntry> entries = CivGlobal.getSessionDB().lookup(getBeakerSessionKey(civ)); if (entries.size() == 0) { return 0.0; } else { return Double.valueOf(entries.get(0).value); } } }
Java
/* * Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ package org.visage.jdi.request; import org.visage.jdi.VisageThreadReference; import org.visage.jdi.VisageVirtualMachine; import org.visage.jdi.VisageWrapper; import com.sun.jdi.ObjectReference; import com.sun.jdi.ReferenceType; import com.sun.jdi.request.StepRequest; /** * * @author sundar */ public class VisageStepRequest extends VisageEventRequest implements StepRequest { public VisageStepRequest(VisageVirtualMachine visagevm, StepRequest underlying) { super(visagevm, underlying); } public void addClassExclusionFilter(String arg0) { underlying().addClassExclusionFilter(arg0); } public void addClassFilter(ReferenceType arg0) { underlying().addClassFilter(VisageWrapper.unwrap(arg0)); } public void addClassFilter(String arg0) { underlying().addClassFilter(arg0); } public void addInstanceFilter(ObjectReference ref) { underlying().addInstanceFilter(VisageWrapper.unwrap(ref)); } public int depth() { return underlying().depth(); } public int size() { return underlying().size(); } public VisageThreadReference thread() { return VisageWrapper.wrap(virtualMachine(), underlying().thread()); } @Override protected StepRequest underlying() { return (StepRequest) super.underlying(); } }
Java
/* * Copyright (C) 2014 Apple 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: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "bmalloc.h" #define EXPORT __attribute__((visibility("default"))) extern "C" { EXPORT void* mbmalloc(size_t); EXPORT void* mbmemalign(size_t, size_t); EXPORT void mbfree(void*, size_t); EXPORT void* mbrealloc(void*, size_t, size_t); EXPORT void mbscavenge(); void* mbmalloc(size_t size) { return bmalloc::api::malloc(size); } void* mbmemalign(size_t alignment, size_t size) { return bmalloc::api::memalign(alignment, size); } void mbfree(void* p, size_t) { bmalloc::api::free(p); } void* mbrealloc(void* p, size_t, size_t size) { return bmalloc::api::realloc(p, size); } void mbscavenge() { bmalloc::api::scavenge(); } } // extern "C"
Java
package gr.softaware.lib_1_3.data.convert.csv; import java.util.List; /** * * @author siggouroglou * @param <T> A class that implements the CsvGenerationModel interface. */ final public class CsvGenerator<T extends CsvGenerationModel> { private final List<CsvGenerationModel> modelList; public CsvGenerator(List<T> modelList) { this.modelList = (List<CsvGenerationModel>)modelList; } public StringBuilder getContent() { return getContent("\t", "\\t"); } public StringBuilder getContent(String separator, String separatorAsString) { StringBuilder builder = new StringBuilder(); // First line contains the separator. builder.append("sep=").append(separatorAsString).append("\n"); // Get the header. if(!modelList.isEmpty()) { builder.append(modelList.get(0).toCsvFormattedHeader(separator)).append("\n"); } // Get the data. modelList.stream().forEach((model) -> { builder.append(model.toCsvFormattedRow(separator)).append("\n"); }); return builder; } }
Java
<?php /** Author: Musavir Ifitkahr: kuala lumpur Malaysia */ class Admin_UserController extends Zend_Controller_Action { protected $user_session = null; protected $db; protected $language_id = null; protected $filter = null; protected $user = null; protected $baseurl = ''; public function init(){ Zend_Layout::startMvc( array('layoutPath' => APPLICATION_PATH . '/admin/layouts', 'layout' => 'layout') ); $this->db = Zend_Db_Table::getDefaultAdapter(); $this->user = new Application_Model_User(); $this->baseurl = Zend_Controller_Front::getInstance()->getBaseUrl(); //actual base url function $this->language_id = Zend_Registry::get('lang_id'); //get the instance of database adapter $this->user_session = new Zend_Session_Namespace("user_session"); // default namespace $this->filter = new Zend_Filter_StripTags; //Zend_Registry::set('lang_id',2); ini_set("max_execution_time", 0); $auth = Zend_Auth::getInstance(); //if not loggedin redirect to login page if (!$auth->hasIdentity()){ $this->_redirect('/admin/index/login');; } /* if(isset($this->user_session->role_id)){ $role = array('1' => 'Admin','2' => 'Payment Manager','3' => 'Content Manager','4' => 'Listing Manager', '3' => 'Deals Manager' ); $this->view->user = array( 'user_id' => $this->user_session->user_id, 'email' => $this->user_session->email, 'role_id' => $this->user_session->role_id, 'role_name' => $role[$this->user_session->role_id], 'user_name' =>$this->user_session->firstname, ); } */ } // this is default output function public function indexAction() { } public function newAction(){ //if not admin redirect to admin index dash board /* if ($this->user_session->role_id != 1){ $this->_redirect('/admin/index'); } */ //show message if it is set true if (isset($this->user_session->msg)){ $this->view->msg = $this->user_session->msg; unset($this->user_session->msg); } //$this->adapter = new Zend_File_Transfer_Adapter_Http(); $form = new Application_Form_UserForm(); $this->view->form = $form; if (!$this->_request->isPost()) { //$form->role->setValue($this->user_session->selected); $this->view->form = $form; return; } $formData = $this->_request->getPost(); if (!$form->isValid($formData)) { $this->view->form = $form; return; } $exist = $this->user->checkEmail($formData['email']); if($exist == true){ $this->view->msg = "<div class='errors'>Email (User ID) already exists. Please make another one .</div>"; return; } $formData['date_added'] = date("Y-m-d"); $this->view->msg = $this->user->addUser($formData); //$this->user_session->selected = $formData['role']; $this->user_session->msg = $this->view->msg; //$this->_redirect('/admin/user/new'); //clear all form fields $form->reset(); } public function messagePageAction(){ $this->view->msg = $this->user_session->msg; unset($this->user_session->country); unset($this->user_session->state); unset($this->user_session->add_more); } public function listAction(){ $query_string = $this->_request->getParam("query_string"); $results = null; $query_string = trim($query_string); if($query_string !=''){ if(is_string($query_string)){ $results = $this->user->findUser($query_string); } } else{ $results = $this->user->getUsers(); } if (count($results) > 0) { $this->Paginator($results); } else { $this->view->empty_rec = true; } } // for delete users public function deleteUsersAction(){ $user_id = $this->_request->getParam('id'); $delete = $this->user->deleteUsers($user_id); $this->_redirect('/admin/user/list/'); //var_dump($delete); } public function findUsersAction(){ //$this->ajaxed(); $email = $this->_request->getParam('email'); $results = $this->user->findUser($email); if (count($results) > 0) { $this->Paginator($results); } else { $this->view->empty_rec = true; } } public function editAction(){ $form = new Application_Form_UserForm(); $user_id = $this->_request->getParam('user_id'); $result = $this->user->getUser($user_id); $form->removeElement("password"); $this->view->user_id = $result->user_id; $form->email->setValue($result->email); $form->user_name->setValue($result->user_name); //$form->role->setValue($result->role); $this->view->form = $form; if (!$this->_request->isPost()) { $this->view->form = $form; return; } $formData = $this->_request->getPost(); if (!$form->isValid($formData)) { $this->view->form = $form; return; } $result = $this->user->updateUser($formData); $this->_redirect('admin/user/list'); } // for chNEGE password user public function updatePasswordAction(){ $user_id=$this->user_session->user_id; $this->view->user_id=$user_id; $form = new Application_Form_ChangePasswordForm(); $this->view->form = $form; $this->view->msg = ""; if (!$this->_request->isPost()) { return; } $formData = $this->_request->getPost(); if (!$form->isValid($formData)) { return; } //All business logics will come here if(strcmp($formData['pwd_current'],$formData['pwd'] ) == 0){ $this->view->msg = "<div class='alert alert-danger'>Old and New password are same</div>"; $this->view->form = $form; return; } if(strcmp($formData['pwd'],$formData['pwd_confirm'] ) != 0){ $this->view->msg = "<div class='alert alert-danger'>Passwords are not matching</div>"; $this->view->form = $form; return; } // var_dump($formData); if($this->user->passUpdate($user_id, $formData['pwd'])){ $this->view->msg = "<div class='alert alert-success'>Password successfully Updated</div>"; }else{ $this->view->msg = "<div class='alert alert-danger'>Password Update Failed. Try again</div>"; } } public function changePasswordAction(){ $form = new Application_Form_UserForm(); $form->removeElement("user_id"); $form->removeElement("firstname"); $form->removeElement("lastname"); $form->removeElement("email"); $user = new Application_Model_User(); $result = $user->getUser(); $form->password->setLabel("New Password"); $form->password->setValue($result->password); $this->view->form = $form; $formData; if (!$this->_request->isPost()) { $this->view->form = $form; return; } $formData = $this->_request->getPost(); if (!$form->isValid($formData)) { $this->view->form = $form; return; } /*if(!$user->currentPass($formData['current_password'])){ $this->view->msg = "Wrong current password"; return; }*/ else { $result = $user->updatePassword($formData); $this->view->msg = "Password is updated"; } } public function Paginator($results) { $page = $this->_getParam('page', 1); $paginator = Zend_Paginator::factory($results); $paginator->setItemCountPerPage(20); $paginator->setCurrentPageNumber($page); $this->view->paginator = $paginator; } /* public function confirmDeleteAction(){ $user_id = $this->_request->getParam('user_id'); $firstname = $this->_request->getParam('firstname'); $this->view->firstname = $firstname; $this->view->user_id = $user_id; } */ /* public function deleteAction(){ $user_id = $this->_request->getParam('user_id'); $user_table = new Application_Model_User(); $flag = $user_table->removeUser($user_id); if($flag){ $this->view->user_remove_report = "user has been removed! Successfully"; } } */ public function ajaxed() { $this->_helper->viewRenderer->setNoRender(); $this->_helper->layout()->disableLayout(); if (!$this->_request->isXmlHttpRequest() )return; // if not a ajax request leave function } public function __call($method, $args) { if ('Action' == substr($method, -6)) { // If the action method was not found, forward to the // index action return $this->_redirect('admin/index'); } // all other methods throw an exception throw new Exception('Invalid method "' . $method . '" called', 500); } }
Java
/* * This file is part of KITCard Reader. * Ⓒ 2012 Philipp Kern <phil@philkern.de> * * KITCard Reader 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. * * KITCard Reader 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 KITCard Reader. If not, see <http://www.gnu.org/licenses/>. */ package de.Ox539.kitcard.reader; /** * ReadCardTask: Read an NFC tag using the Wallet class asynchronously. * * This class provides the glue calling the Wallet class and passing * the information back to the Android UI layer. Detailed error * information is not provided yet. * * @author Philipp Kern <pkern@debian.org> */ import de.Ox539.kitcard.reader.Wallet.ReadCardResult; import android.nfc.Tag; import android.nfc.tech.MifareClassic; import android.os.AsyncTask; import android.widget.Toast; public class ReadCardTask extends AsyncTask<Tag, Integer, Pair<ReadCardResult, Wallet>> { private ScanActivity mActivity; public ReadCardTask(ScanActivity activity) { super(); this.mActivity = activity; } protected Pair<ReadCardResult, Wallet> doInBackground(Tag... tags) { MifareClassic card = null; try { card = MifareClassic.get(tags[0]); } catch (NullPointerException e) { /* Error while reading card. This problem occurs on HTC devices from the ONE series with Android Lollipop (status of June 2015) * Try to repair the tag. */ card = MifareClassic.get(MifareUtils.repairTag(tags[0])); } if(card == null) return new Pair<ReadCardResult, Wallet>(null, null); final Wallet wallet = new Wallet(card); final ReadCardResult result = wallet.readCard(); return new Pair<ReadCardResult, Wallet>(result, wallet); } protected void onPostExecute(Pair<ReadCardResult, Wallet> data) { ReadCardResult result = data.getValue0(); if(result == ReadCardResult.FAILURE) { // read failed Toast.makeText(mActivity, mActivity.getResources().getString(R.string.kitcard_read_failed), Toast.LENGTH_LONG).show(); return; } else if(result == ReadCardResult.OLD_STYLE_WALLET) { // old-style wallet encountered Toast.makeText(mActivity, mActivity.getResources().getString(R.string.kitcard_needs_reencode), Toast.LENGTH_LONG).show(); return; } final Wallet wallet = data.getValue1(); mActivity.updateCardNumber(wallet.getCardNumber()); mActivity.updateBalance(wallet.getCurrentBalance()); mActivity.updateLastTransaction(wallet.getLastTransactionValue()); mActivity.updateCardIssuer(wallet.getCardIssuer()); mActivity.updateCardType(wallet.getCardType()); } }
Java
/* * Copyright 2002-2005, Instant802 Networks, Inc. * Copyright 2005-2006, Devicescape Software, Inc. * Copyright 2007 Johannes Berg <johannes@sipsolutions.net> * Copyright 2008 Luis R. Rodriguez <lrodriguz@atheros.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ /** * DOC: Wireless regulatory infrastructure * * The usual implementation is for a driver to read a device EEPROM to * determine which regulatory domain it should be operating under, then * looking up the allowable channels in a driver-local table and finally * registering those channels in the wiphy structure. * * Another set of compliance enforcement is for drivers to use their * own compliance limits which can be stored on the EEPROM. The host * driver or firmware may ensure these are used. * * In addition to all this we provide an extra layer of regulatory * conformance. For drivers which do not have any regulatory * information CRDA provides the complete regulatory solution. * For others it provides a community effort on further restrictions * to enhance compliance. * * Note: When number of rules --> infinity we will not be able to * index on alpha2 any more, instead we'll probably have to * rely on some SHA1 checksum of the regdomain for example. * */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/kernel.h> #include <linux/export.h> #include <linux/slab.h> #include <linux/list.h> #include <linux/random.h> #include <linux/ctype.h> #include <linux/nl80211.h> #include <linux/platform_device.h> #include <linux/moduleparam.h> #include <net/cfg80211.h> #include "core.h" #include "reg.h" #include "regdb.h" #include "nl80211.h" #ifdef CONFIG_CFG80211_REG_DEBUG #define REG_DBG_PRINT(format, args...) \ printk(KERN_DEBUG pr_fmt(format), ##args) #else #define REG_DBG_PRINT(args...) #endif static struct regulatory_request core_request_world = { .initiator = NL80211_REGDOM_SET_BY_CORE, .alpha2[0] = '0', .alpha2[1] = '0', .intersect = false, .processed = true, .country_ie_env = ENVIRON_ANY, }; /* Receipt of information from last regulatory request */ static struct regulatory_request *last_request = &core_request_world; /* To trigger userspace events */ static struct platform_device *reg_pdev; static struct device_type reg_device_type = { .uevent = reg_device_uevent, }; /* * Central wireless core regulatory domains, we only need two, * the current one and a world regulatory domain in case we have no * information to give us an alpha2 */ const struct ieee80211_regdomain *cfg80211_regdomain; /* * Protects static reg.c components: * - cfg80211_world_regdom * - cfg80211_regdom * - last_request */ static DEFINE_MUTEX(reg_mutex); static inline void assert_reg_lock(void) { lockdep_assert_held(&reg_mutex); } /* Used to queue up regulatory hints */ static LIST_HEAD(reg_requests_list); static spinlock_t reg_requests_lock; /* Used to queue up beacon hints for review */ static LIST_HEAD(reg_pending_beacons); static spinlock_t reg_pending_beacons_lock; /* Used to keep track of processed beacon hints */ static LIST_HEAD(reg_beacon_list); struct reg_beacon { struct list_head list; struct ieee80211_channel chan; }; static void reg_todo(struct work_struct *work); static DECLARE_WORK(reg_work, reg_todo); static void reg_timeout_work(struct work_struct *work); static DECLARE_DELAYED_WORK(reg_timeout, reg_timeout_work); /* We keep a static world regulatory domain in case of the absence of CRDA */ static const struct ieee80211_regdomain world_regdom = { .n_reg_rules = 5, .alpha2 = "00", .reg_rules = { /* IEEE 802.11b/g, channels 1..11 */ REG_RULE(2412-10, 2462+10, 40, 6, 20, 0), /* IEEE 802.11b/g, channels 12..13. No HT40 * channel fits here. */ REG_RULE(2467-10, 2472+10, 20, 6, 20, NL80211_RRF_PASSIVE_SCAN | NL80211_RRF_NO_IBSS), /* IEEE 802.11 channel 14 - Only JP enables * this and for 802.11b only */ REG_RULE(2484-10, 2484+10, 20, 6, 20, NL80211_RRF_PASSIVE_SCAN | NL80211_RRF_NO_IBSS | NL80211_RRF_NO_OFDM), /* IEEE 802.11a, channel 36..48 */ REG_RULE(5180-10, 5240+10, 40, 6, 20, NL80211_RRF_PASSIVE_SCAN | NL80211_RRF_NO_IBSS), /* NB: 5260 MHz - 5700 MHz requies DFS */ /* IEEE 802.11a, channel 149..165 */ REG_RULE(5745-10, 5825+10, 40, 6, 20, NL80211_RRF_PASSIVE_SCAN | NL80211_RRF_NO_IBSS), } }; static const struct ieee80211_regdomain *cfg80211_world_regdom = &world_regdom; static char *ieee80211_regdom = "00"; static char user_alpha2[2]; module_param(ieee80211_regdom, charp, 0444); MODULE_PARM_DESC(ieee80211_regdom, "IEEE 802.11 regulatory domain code"); static void reset_regdomains(bool full_reset) { /* avoid freeing static information or freeing something twice */ if (cfg80211_regdomain == cfg80211_world_regdom) cfg80211_regdomain = NULL; if (cfg80211_world_regdom == &world_regdom) cfg80211_world_regdom = NULL; if (cfg80211_regdomain == &world_regdom) cfg80211_regdomain = NULL; kfree(cfg80211_regdomain); kfree(cfg80211_world_regdom); cfg80211_world_regdom = &world_regdom; cfg80211_regdomain = NULL; if (!full_reset) return; if (last_request != &core_request_world) kfree(last_request); last_request = &core_request_world; } /* * Dynamic world regulatory domain requested by the wireless * core upon initialization */ static void update_world_regdomain(const struct ieee80211_regdomain *rd) { BUG_ON(!last_request); reset_regdomains(false); cfg80211_world_regdom = rd; cfg80211_regdomain = rd; } bool is_world_regdom(const char *alpha2) { if (!alpha2) return false; if (alpha2[0] == '0' && alpha2[1] == '0') return true; return false; } static bool is_alpha2_set(const char *alpha2) { if (!alpha2) return false; if (alpha2[0] != 0 && alpha2[1] != 0) return true; return false; } static bool is_unknown_alpha2(const char *alpha2) { if (!alpha2) return false; /* * Special case where regulatory domain was built by driver * but a specific alpha2 cannot be determined */ if (alpha2[0] == '9' && alpha2[1] == '9') return true; return false; } static bool is_intersected_alpha2(const char *alpha2) { if (!alpha2) return false; /* * Special case where regulatory domain is the * result of an intersection between two regulatory domain * structures */ if (alpha2[0] == '9' && alpha2[1] == '8') return true; return false; } static bool is_an_alpha2(const char *alpha2) { if (!alpha2) return false; if (isalpha(alpha2[0]) && isalpha(alpha2[1])) return true; return false; } static bool alpha2_equal(const char *alpha2_x, const char *alpha2_y) { if (!alpha2_x || !alpha2_y) return false; if (alpha2_x[0] == alpha2_y[0] && alpha2_x[1] == alpha2_y[1]) return true; return false; } static bool regdom_changes(const char *alpha2) { assert_cfg80211_lock(); if (!cfg80211_regdomain) return true; if (alpha2_equal(cfg80211_regdomain->alpha2, alpha2)) return false; return true; } /* * The NL80211_REGDOM_SET_BY_USER regdom alpha2 is cached, this lets * you know if a valid regulatory hint with NL80211_REGDOM_SET_BY_USER * has ever been issued. */ static bool is_user_regdom_saved(void) { if (user_alpha2[0] == '9' && user_alpha2[1] == '7') return false; /* This would indicate a mistake on the design */ if (WARN((!is_world_regdom(user_alpha2) && !is_an_alpha2(user_alpha2)), "Unexpected user alpha2: %c%c\n", user_alpha2[0], user_alpha2[1])) return false; return true; } static int reg_copy_regd(const struct ieee80211_regdomain **dst_regd, const struct ieee80211_regdomain *src_regd) { struct ieee80211_regdomain *regd; int size_of_regd = 0; unsigned int i; size_of_regd = sizeof(struct ieee80211_regdomain) + ((src_regd->n_reg_rules + 1) * sizeof(struct ieee80211_reg_rule)); regd = kzalloc(size_of_regd, GFP_KERNEL); if (!regd) return -ENOMEM; memcpy(regd, src_regd, sizeof(struct ieee80211_regdomain)); for (i = 0; i < src_regd->n_reg_rules; i++) memcpy(&regd->reg_rules[i], &src_regd->reg_rules[i], sizeof(struct ieee80211_reg_rule)); *dst_regd = regd; return 0; } #ifdef CONFIG_CFG80211_INTERNAL_REGDB struct reg_regdb_search_request { char alpha2[2]; struct list_head list; }; static LIST_HEAD(reg_regdb_search_list); static DEFINE_MUTEX(reg_regdb_search_mutex); static void reg_regdb_search(struct work_struct *work) { struct reg_regdb_search_request *request; const struct ieee80211_regdomain *curdom, *regdom; int i, r; mutex_lock(&reg_regdb_search_mutex); while (!list_empty(&reg_regdb_search_list)) { request = list_first_entry(&reg_regdb_search_list, struct reg_regdb_search_request, list); list_del(&request->list); for (i=0; i<reg_regdb_size; i++) { curdom = reg_regdb[i]; if (!memcmp(request->alpha2, curdom->alpha2, 2)) { r = reg_copy_regd(&regdom, curdom); if (r) break; mutex_lock(&cfg80211_mutex); set_regdom(regdom); mutex_unlock(&cfg80211_mutex); break; } } kfree(request); } mutex_unlock(&reg_regdb_search_mutex); } static DECLARE_WORK(reg_regdb_work, reg_regdb_search); static void reg_regdb_query(const char *alpha2) { struct reg_regdb_search_request *request; if (!alpha2) return; request = kzalloc(sizeof(struct reg_regdb_search_request), GFP_KERNEL); if (!request) return; memcpy(request->alpha2, alpha2, 2); mutex_lock(&reg_regdb_search_mutex); list_add_tail(&request->list, &reg_regdb_search_list); mutex_unlock(&reg_regdb_search_mutex); schedule_work(&reg_regdb_work); } /* Feel free to add any other sanity checks here */ static void reg_regdb_size_check(void) { /* We should ideally BUILD_BUG_ON() but then random builds would fail */ WARN_ONCE(!reg_regdb_size, "db.txt is empty, you should update it..."); } #else static inline void reg_regdb_size_check(void) {} static inline void reg_regdb_query(const char *alpha2) {} #endif /* CONFIG_CFG80211_INTERNAL_REGDB */ /* * This lets us keep regulatory code which is updated on a regulatory * basis in userspace. Country information is filled in by * reg_device_uevent */ static int call_crda(const char *alpha2) { if (!is_world_regdom((char *) alpha2)) pr_info("Calling CRDA for country: %c%c\n", alpha2[0], alpha2[1]); else pr_info("Calling CRDA to update world regulatory domain\n"); /* query internal regulatory database (if it exists) */ reg_regdb_query(alpha2); return kobject_uevent(&reg_pdev->dev.kobj, KOBJ_CHANGE); } /* Used by nl80211 before kmalloc'ing our regulatory domain */ bool reg_is_valid_request(const char *alpha2) { assert_cfg80211_lock(); if (!last_request) return false; return alpha2_equal(last_request->alpha2, alpha2); } /* Sanity check on a regulatory rule */ static bool is_valid_reg_rule(const struct ieee80211_reg_rule *rule) { const struct ieee80211_freq_range *freq_range = &rule->freq_range; u32 freq_diff; if (freq_range->start_freq_khz <= 0 || freq_range->end_freq_khz <= 0) return false; if (freq_range->start_freq_khz > freq_range->end_freq_khz) return false; freq_diff = freq_range->end_freq_khz - freq_range->start_freq_khz; if (freq_range->end_freq_khz <= freq_range->start_freq_khz || freq_range->max_bandwidth_khz > freq_diff) return false; return true; } static bool is_valid_rd(const struct ieee80211_regdomain *rd) { const struct ieee80211_reg_rule *reg_rule = NULL; unsigned int i; if (!rd->n_reg_rules) return false; if (WARN_ON(rd->n_reg_rules > NL80211_MAX_SUPP_REG_RULES)) return false; for (i = 0; i < rd->n_reg_rules; i++) { reg_rule = &rd->reg_rules[i]; if (!is_valid_reg_rule(reg_rule)) return false; } return true; } static bool reg_does_bw_fit(const struct ieee80211_freq_range *freq_range, u32 center_freq_khz, u32 bw_khz) { u32 start_freq_khz, end_freq_khz; start_freq_khz = center_freq_khz - (bw_khz/2); end_freq_khz = center_freq_khz + (bw_khz/2); if (start_freq_khz >= freq_range->start_freq_khz && end_freq_khz <= freq_range->end_freq_khz) return true; return false; } /** * freq_in_rule_band - tells us if a frequency is in a frequency band * @freq_range: frequency rule we want to query * @freq_khz: frequency we are inquiring about * * This lets us know if a specific frequency rule is or is not relevant to * a specific frequency's band. Bands are device specific and artificial * definitions (the "2.4 GHz band" and the "5 GHz band"), however it is * safe for now to assume that a frequency rule should not be part of a * frequency's band if the start freq or end freq are off by more than 2 GHz. * This resolution can be lowered and should be considered as we add * regulatory rule support for other "bands". **/ static bool freq_in_rule_band(const struct ieee80211_freq_range *freq_range, u32 freq_khz) { #define ONE_GHZ_IN_KHZ 1000000 if (abs(freq_khz - freq_range->start_freq_khz) <= (2 * ONE_GHZ_IN_KHZ)) return true; if (abs(freq_khz - freq_range->end_freq_khz) <= (2 * ONE_GHZ_IN_KHZ)) return true; return false; #undef ONE_GHZ_IN_KHZ } /* * Helper for regdom_intersect(), this does the real * mathematical intersection fun */ static int reg_rules_intersect( const struct ieee80211_reg_rule *rule1, const struct ieee80211_reg_rule *rule2, struct ieee80211_reg_rule *intersected_rule) { const struct ieee80211_freq_range *freq_range1, *freq_range2; struct ieee80211_freq_range *freq_range; const struct ieee80211_power_rule *power_rule1, *power_rule2; struct ieee80211_power_rule *power_rule; u32 freq_diff; freq_range1 = &rule1->freq_range; freq_range2 = &rule2->freq_range; freq_range = &intersected_rule->freq_range; power_rule1 = &rule1->power_rule; power_rule2 = &rule2->power_rule; power_rule = &intersected_rule->power_rule; freq_range->start_freq_khz = max(freq_range1->start_freq_khz, freq_range2->start_freq_khz); freq_range->end_freq_khz = min(freq_range1->end_freq_khz, freq_range2->end_freq_khz); freq_range->max_bandwidth_khz = min(freq_range1->max_bandwidth_khz, freq_range2->max_bandwidth_khz); freq_diff = freq_range->end_freq_khz - freq_range->start_freq_khz; if (freq_range->max_bandwidth_khz > freq_diff) freq_range->max_bandwidth_khz = freq_diff; power_rule->max_eirp = min(power_rule1->max_eirp, power_rule2->max_eirp); power_rule->max_antenna_gain = min(power_rule1->max_antenna_gain, power_rule2->max_antenna_gain); intersected_rule->flags = (rule1->flags | rule2->flags); if (!is_valid_reg_rule(intersected_rule)) return -EINVAL; return 0; } /** * regdom_intersect - do the intersection between two regulatory domains * @rd1: first regulatory domain * @rd2: second regulatory domain * * Use this function to get the intersection between two regulatory domains. * Once completed we will mark the alpha2 for the rd as intersected, "98", * as no one single alpha2 can represent this regulatory domain. * * Returns a pointer to the regulatory domain structure which will hold the * resulting intersection of rules between rd1 and rd2. We will * kzalloc() this structure for you. */ static struct ieee80211_regdomain *regdom_intersect( const struct ieee80211_regdomain *rd1, const struct ieee80211_regdomain *rd2) { int r, size_of_regd; unsigned int x, y; unsigned int num_rules = 0, rule_idx = 0; const struct ieee80211_reg_rule *rule1, *rule2; struct ieee80211_reg_rule *intersected_rule; struct ieee80211_regdomain *rd; /* This is just a dummy holder to help us count */ struct ieee80211_reg_rule irule; /* Uses the stack temporarily for counter arithmetic */ intersected_rule = &irule; memset(intersected_rule, 0, sizeof(struct ieee80211_reg_rule)); if (!rd1 || !rd2) return NULL; /* * First we get a count of the rules we'll need, then we actually * build them. This is to so we can malloc() and free() a * regdomain once. The reason we use reg_rules_intersect() here * is it will return -EINVAL if the rule computed makes no sense. * All rules that do check out OK are valid. */ for (x = 0; x < rd1->n_reg_rules; x++) { rule1 = &rd1->reg_rules[x]; for (y = 0; y < rd2->n_reg_rules; y++) { rule2 = &rd2->reg_rules[y]; if (!reg_rules_intersect(rule1, rule2, intersected_rule)) num_rules++; memset(intersected_rule, 0, sizeof(struct ieee80211_reg_rule)); } } if (!num_rules) return NULL; size_of_regd = sizeof(struct ieee80211_regdomain) + ((num_rules + 1) * sizeof(struct ieee80211_reg_rule)); rd = kzalloc(size_of_regd, GFP_KERNEL); if (!rd) return NULL; for (x = 0; x < rd1->n_reg_rules; x++) { rule1 = &rd1->reg_rules[x]; for (y = 0; y < rd2->n_reg_rules; y++) { rule2 = &rd2->reg_rules[y]; /* * This time around instead of using the stack lets * write to the target rule directly saving ourselves * a memcpy() */ intersected_rule = &rd->reg_rules[rule_idx]; r = reg_rules_intersect(rule1, rule2, intersected_rule); /* * No need to memset here the intersected rule here as * we're not using the stack anymore */ if (r) continue; rule_idx++; } } if (rule_idx != num_rules) { kfree(rd); return NULL; } rd->n_reg_rules = num_rules; rd->alpha2[0] = '9'; rd->alpha2[1] = '8'; return rd; } /* * XXX: add support for the rest of enum nl80211_reg_rule_flags, we may * want to just have the channel structure use these */ static u32 map_regdom_flags(u32 rd_flags) { u32 channel_flags = 0; if (rd_flags & NL80211_RRF_PASSIVE_SCAN) channel_flags |= IEEE80211_CHAN_PASSIVE_SCAN; if (rd_flags & NL80211_RRF_NO_IBSS) channel_flags |= IEEE80211_CHAN_NO_IBSS; if (rd_flags & NL80211_RRF_DFS) channel_flags |= IEEE80211_CHAN_RADAR; return channel_flags; } static int freq_reg_info_regd(struct wiphy *wiphy, u32 center_freq, u32 desired_bw_khz, const struct ieee80211_reg_rule **reg_rule, const struct ieee80211_regdomain *custom_regd) { int i; bool band_rule_found = false; const struct ieee80211_regdomain *regd; bool bw_fits = false; if (!desired_bw_khz) desired_bw_khz = MHZ_TO_KHZ(20); regd = custom_regd ? custom_regd : cfg80211_regdomain; /* * Follow the driver's regulatory domain, if present, unless a country * IE has been processed or a user wants to help complaince further */ if (!custom_regd && last_request->initiator != NL80211_REGDOM_SET_BY_COUNTRY_IE && last_request->initiator != NL80211_REGDOM_SET_BY_USER && wiphy->regd) regd = wiphy->regd; if (!regd) return -EINVAL; for (i = 0; i < regd->n_reg_rules; i++) { const struct ieee80211_reg_rule *rr; const struct ieee80211_freq_range *fr = NULL; rr = &regd->reg_rules[i]; fr = &rr->freq_range; /* * We only need to know if one frequency rule was * was in center_freq's band, that's enough, so lets * not overwrite it once found */ if (!band_rule_found) band_rule_found = freq_in_rule_band(fr, center_freq); bw_fits = reg_does_bw_fit(fr, center_freq, desired_bw_khz); if (band_rule_found && bw_fits) { *reg_rule = rr; return 0; } } if (!band_rule_found) return -ERANGE; return -EINVAL; } int freq_reg_info(struct wiphy *wiphy, u32 center_freq, u32 desired_bw_khz, const struct ieee80211_reg_rule **reg_rule) { assert_cfg80211_lock(); return freq_reg_info_regd(wiphy, center_freq, desired_bw_khz, reg_rule, NULL); } EXPORT_SYMBOL(freq_reg_info); #ifdef CONFIG_CFG80211_REG_DEBUG static const char *reg_initiator_name(enum nl80211_reg_initiator initiator) { switch (initiator) { case NL80211_REGDOM_SET_BY_CORE: return "Set by core"; case NL80211_REGDOM_SET_BY_USER: return "Set by user"; case NL80211_REGDOM_SET_BY_DRIVER: return "Set by driver"; case NL80211_REGDOM_SET_BY_COUNTRY_IE: return "Set by country IE"; default: WARN_ON(1); return "Set by bug"; } } static void chan_reg_rule_print_dbg(struct ieee80211_channel *chan, u32 desired_bw_khz, const struct ieee80211_reg_rule *reg_rule) { const struct ieee80211_power_rule *power_rule; const struct ieee80211_freq_range *freq_range; char max_antenna_gain[32]; power_rule = &reg_rule->power_rule; freq_range = &reg_rule->freq_range; if (!power_rule->max_antenna_gain) snprintf(max_antenna_gain, 32, "N/A"); else snprintf(max_antenna_gain, 32, "%d", power_rule->max_antenna_gain); REG_DBG_PRINT("Updating information on frequency %d MHz " "for a %d MHz width channel with regulatory rule:\n", chan->center_freq, KHZ_TO_MHZ(desired_bw_khz)); REG_DBG_PRINT("%d KHz - %d KHz @ %d KHz), (%s mBi, %d mBm)\n", freq_range->start_freq_khz, freq_range->end_freq_khz, freq_range->max_bandwidth_khz, max_antenna_gain, power_rule->max_eirp); } #else static void chan_reg_rule_print_dbg(struct ieee80211_channel *chan, u32 desired_bw_khz, const struct ieee80211_reg_rule *reg_rule) { return; } #endif /* * Note that right now we assume the desired channel bandwidth * is always 20 MHz for each individual channel (HT40 uses 20 MHz * per channel, the primary and the extension channel). To support * smaller custom bandwidths such as 5 MHz or 10 MHz we'll need a * new ieee80211_channel.target_bw and re run the regulatory check * on the wiphy with the target_bw specified. Then we can simply use * that below for the desired_bw_khz below. */ static void handle_channel(struct wiphy *wiphy, enum nl80211_reg_initiator initiator, enum ieee80211_band band, unsigned int chan_idx) { int r; u32 flags, bw_flags = 0; u32 desired_bw_khz = MHZ_TO_KHZ(20); const struct ieee80211_reg_rule *reg_rule = NULL; const struct ieee80211_power_rule *power_rule = NULL; const struct ieee80211_freq_range *freq_range = NULL; struct ieee80211_supported_band *sband; struct ieee80211_channel *chan; struct wiphy *request_wiphy = NULL; assert_cfg80211_lock(); request_wiphy = wiphy_idx_to_wiphy(last_request->wiphy_idx); sband = wiphy->bands[band]; BUG_ON(chan_idx >= sband->n_channels); chan = &sband->channels[chan_idx]; flags = chan->orig_flags; r = freq_reg_info(wiphy, MHZ_TO_KHZ(chan->center_freq), desired_bw_khz, &reg_rule); if (r) { /* * We will disable all channels that do not match our * received regulatory rule unless the hint is coming * from a Country IE and the Country IE had no information * about a band. The IEEE 802.11 spec allows for an AP * to send only a subset of the regulatory rules allowed, * so an AP in the US that only supports 2.4 GHz may only send * a country IE with information for the 2.4 GHz band * while 5 GHz is still supported. */ if (initiator == NL80211_REGDOM_SET_BY_COUNTRY_IE && r == -ERANGE) return; REG_DBG_PRINT("Disabling freq %d MHz\n", chan->center_freq); chan->flags = IEEE80211_CHAN_DISABLED; return; } chan_reg_rule_print_dbg(chan, desired_bw_khz, reg_rule); power_rule = &reg_rule->power_rule; freq_range = &reg_rule->freq_range; if (freq_range->max_bandwidth_khz < MHZ_TO_KHZ(40)) bw_flags = IEEE80211_CHAN_NO_HT40; if (last_request->initiator == NL80211_REGDOM_SET_BY_DRIVER && request_wiphy && request_wiphy == wiphy && request_wiphy->flags & WIPHY_FLAG_STRICT_REGULATORY) { /* * This guarantees the driver's requested regulatory domain * will always be used as a base for further regulatory * settings */ chan->flags = chan->orig_flags = map_regdom_flags(reg_rule->flags) | bw_flags; chan->max_antenna_gain = chan->orig_mag = (int) MBI_TO_DBI(power_rule->max_antenna_gain); chan->max_power = chan->orig_mpwr = (int) MBM_TO_DBM(power_rule->max_eirp); return; } chan->beacon_found = false; chan->flags = flags | bw_flags | map_regdom_flags(reg_rule->flags); chan->max_antenna_gain = min(chan->orig_mag, (int) MBI_TO_DBI(power_rule->max_antenna_gain)); if (chan->orig_mpwr) chan->max_power = min(chan->orig_mpwr, (int) MBM_TO_DBM(power_rule->max_eirp)); else chan->max_power = (int) MBM_TO_DBM(power_rule->max_eirp); } static void handle_band(struct wiphy *wiphy, enum ieee80211_band band, enum nl80211_reg_initiator initiator) { unsigned int i; struct ieee80211_supported_band *sband; BUG_ON(!wiphy->bands[band]); sband = wiphy->bands[band]; for (i = 0; i < sband->n_channels; i++) handle_channel(wiphy, initiator, band, i); } static bool ignore_reg_update(struct wiphy *wiphy, enum nl80211_reg_initiator initiator) { if (!last_request) { REG_DBG_PRINT("Ignoring regulatory request %s since " "last_request is not set\n", reg_initiator_name(initiator)); return true; } if (initiator == NL80211_REGDOM_SET_BY_CORE && wiphy->flags & WIPHY_FLAG_CUSTOM_REGULATORY) { REG_DBG_PRINT("Ignoring regulatory request %s " "since the driver uses its own custom " "regulatory domain\n", reg_initiator_name(initiator)); return true; } /* * wiphy->regd will be set once the device has its own * desired regulatory domain set */ if (wiphy->flags & WIPHY_FLAG_STRICT_REGULATORY && !wiphy->regd && initiator != NL80211_REGDOM_SET_BY_COUNTRY_IE && !is_world_regdom(last_request->alpha2)) { REG_DBG_PRINT("Ignoring regulatory request %s " "since the driver requires its own regulatory " "domain to be set first\n", reg_initiator_name(initiator)); return true; } return false; } static void handle_reg_beacon(struct wiphy *wiphy, unsigned int chan_idx, struct reg_beacon *reg_beacon) { struct ieee80211_supported_band *sband; struct ieee80211_channel *chan; bool channel_changed = false; struct ieee80211_channel chan_before; assert_cfg80211_lock(); sband = wiphy->bands[reg_beacon->chan.band]; chan = &sband->channels[chan_idx]; if (likely(chan->center_freq != reg_beacon->chan.center_freq)) return; if (chan->beacon_found) return; chan->beacon_found = true; if (wiphy->flags & WIPHY_FLAG_DISABLE_BEACON_HINTS) return; chan_before.center_freq = chan->center_freq; chan_before.flags = chan->flags; if (chan->flags & IEEE80211_CHAN_PASSIVE_SCAN) { chan->flags &= ~IEEE80211_CHAN_PASSIVE_SCAN; channel_changed = true; } if (chan->flags & IEEE80211_CHAN_NO_IBSS) { chan->flags &= ~IEEE80211_CHAN_NO_IBSS; channel_changed = true; } if (channel_changed) nl80211_send_beacon_hint_event(wiphy, &chan_before, chan); } /* * Called when a scan on a wiphy finds a beacon on * new channel */ static void wiphy_update_new_beacon(struct wiphy *wiphy, struct reg_beacon *reg_beacon) { unsigned int i; struct ieee80211_supported_band *sband; assert_cfg80211_lock(); if (!wiphy->bands[reg_beacon->chan.band]) return; sband = wiphy->bands[reg_beacon->chan.band]; for (i = 0; i < sband->n_channels; i++) handle_reg_beacon(wiphy, i, reg_beacon); } /* * Called upon reg changes or a new wiphy is added */ static void wiphy_update_beacon_reg(struct wiphy *wiphy) { unsigned int i; struct ieee80211_supported_band *sband; struct reg_beacon *reg_beacon; assert_cfg80211_lock(); if (list_empty(&reg_beacon_list)) return; list_for_each_entry(reg_beacon, &reg_beacon_list, list) { if (!wiphy->bands[reg_beacon->chan.band]) continue; sband = wiphy->bands[reg_beacon->chan.band]; for (i = 0; i < sband->n_channels; i++) handle_reg_beacon(wiphy, i, reg_beacon); } } static bool reg_is_world_roaming(struct wiphy *wiphy) { if (is_world_regdom(cfg80211_regdomain->alpha2) || (wiphy->regd && is_world_regdom(wiphy->regd->alpha2))) return true; if (last_request && last_request->initiator != NL80211_REGDOM_SET_BY_COUNTRY_IE && wiphy->flags & WIPHY_FLAG_CUSTOM_REGULATORY) return true; return false; } /* Reap the advantages of previously found beacons */ static void reg_process_beacons(struct wiphy *wiphy) { /* * Means we are just firing up cfg80211, so no beacons would * have been processed yet. */ if (!last_request) return; if (!reg_is_world_roaming(wiphy)) return; wiphy_update_beacon_reg(wiphy); } static bool is_ht40_not_allowed(struct ieee80211_channel *chan) { if (!chan) return true; if (chan->flags & IEEE80211_CHAN_DISABLED) return true; /* This would happen when regulatory rules disallow HT40 completely */ if (IEEE80211_CHAN_NO_HT40 == (chan->flags & (IEEE80211_CHAN_NO_HT40))) return true; return false; } static void reg_process_ht_flags_channel(struct wiphy *wiphy, enum ieee80211_band band, unsigned int chan_idx) { struct ieee80211_supported_band *sband; struct ieee80211_channel *channel; struct ieee80211_channel *channel_before = NULL, *channel_after = NULL; unsigned int i; assert_cfg80211_lock(); sband = wiphy->bands[band]; BUG_ON(chan_idx >= sband->n_channels); channel = &sband->channels[chan_idx]; if (is_ht40_not_allowed(channel)) { channel->flags |= IEEE80211_CHAN_NO_HT40; return; } /* * We need to ensure the extension channels exist to * be able to use HT40- or HT40+, this finds them (or not) */ for (i = 0; i < sband->n_channels; i++) { struct ieee80211_channel *c = &sband->channels[i]; if (c->center_freq == (channel->center_freq - 20)) channel_before = c; if (c->center_freq == (channel->center_freq + 20)) channel_after = c; } /* * Please note that this assumes target bandwidth is 20 MHz, * if that ever changes we also need to change the below logic * to include that as well. */ if (is_ht40_not_allowed(channel_before)) channel->flags |= IEEE80211_CHAN_NO_HT40MINUS; else channel->flags &= ~IEEE80211_CHAN_NO_HT40MINUS; if (is_ht40_not_allowed(channel_after)) channel->flags |= IEEE80211_CHAN_NO_HT40PLUS; else channel->flags &= ~IEEE80211_CHAN_NO_HT40PLUS; } static void reg_process_ht_flags_band(struct wiphy *wiphy, enum ieee80211_band band) { unsigned int i; struct ieee80211_supported_band *sband; BUG_ON(!wiphy->bands[band]); sband = wiphy->bands[band]; for (i = 0; i < sband->n_channels; i++) reg_process_ht_flags_channel(wiphy, band, i); } static void reg_process_ht_flags(struct wiphy *wiphy) { enum ieee80211_band band; if (!wiphy) return; for (band = 0; band < IEEE80211_NUM_BANDS; band++) { if (wiphy->bands[band]) reg_process_ht_flags_band(wiphy, band); } } static void wiphy_update_regulatory(struct wiphy *wiphy, enum nl80211_reg_initiator initiator) { enum ieee80211_band band; assert_reg_lock(); if (ignore_reg_update(wiphy, initiator)) return; for (band = 0; band < IEEE80211_NUM_BANDS; band++) { if (wiphy->bands[band]) handle_band(wiphy, band, initiator); } reg_process_beacons(wiphy); reg_process_ht_flags(wiphy); if (wiphy->reg_notifier) wiphy->reg_notifier(wiphy, last_request); } void regulatory_update(struct wiphy *wiphy, enum nl80211_reg_initiator setby) { mutex_lock(&reg_mutex); wiphy_update_regulatory(wiphy, setby); mutex_unlock(&reg_mutex); } static void update_all_wiphy_regulatory(enum nl80211_reg_initiator initiator) { struct cfg80211_registered_device *rdev; list_for_each_entry(rdev, &cfg80211_rdev_list, list) wiphy_update_regulatory(&rdev->wiphy, initiator); } static void handle_channel_custom(struct wiphy *wiphy, enum ieee80211_band band, unsigned int chan_idx, const struct ieee80211_regdomain *regd) { int r; u32 desired_bw_khz = MHZ_TO_KHZ(20); u32 bw_flags = 0; const struct ieee80211_reg_rule *reg_rule = NULL; const struct ieee80211_power_rule *power_rule = NULL; const struct ieee80211_freq_range *freq_range = NULL; struct ieee80211_supported_band *sband; struct ieee80211_channel *chan; assert_reg_lock(); sband = wiphy->bands[band]; BUG_ON(chan_idx >= sband->n_channels); chan = &sband->channels[chan_idx]; r = freq_reg_info_regd(wiphy, MHZ_TO_KHZ(chan->center_freq), desired_bw_khz, &reg_rule, regd); if (r) { REG_DBG_PRINT("Disabling freq %d MHz as custom " "regd has no rule that fits a %d MHz " "wide channel\n", chan->center_freq, KHZ_TO_MHZ(desired_bw_khz)); chan->flags = IEEE80211_CHAN_DISABLED; return; } chan_reg_rule_print_dbg(chan, desired_bw_khz, reg_rule); power_rule = &reg_rule->power_rule; freq_range = &reg_rule->freq_range; if (freq_range->max_bandwidth_khz < MHZ_TO_KHZ(40)) bw_flags = IEEE80211_CHAN_NO_HT40; chan->flags |= map_regdom_flags(reg_rule->flags) | bw_flags; chan->max_antenna_gain = (int) MBI_TO_DBI(power_rule->max_antenna_gain); chan->max_power = (int) MBM_TO_DBM(power_rule->max_eirp); } static void handle_band_custom(struct wiphy *wiphy, enum ieee80211_band band, const struct ieee80211_regdomain *regd) { unsigned int i; struct ieee80211_supported_band *sband; BUG_ON(!wiphy->bands[band]); sband = wiphy->bands[band]; for (i = 0; i < sband->n_channels; i++) handle_channel_custom(wiphy, band, i, regd); } /* Used by drivers prior to wiphy registration */ void wiphy_apply_custom_regulatory(struct wiphy *wiphy, const struct ieee80211_regdomain *regd) { enum ieee80211_band band; unsigned int bands_set = 0; mutex_lock(&reg_mutex); for (band = 0; band < IEEE80211_NUM_BANDS; band++) { if (!wiphy->bands[band]) continue; handle_band_custom(wiphy, band, regd); bands_set++; } mutex_unlock(&reg_mutex); /* * no point in calling this if it won't have any effect * on your device's supportd bands. */ WARN_ON(!bands_set); } EXPORT_SYMBOL(wiphy_apply_custom_regulatory); /* * Return value which can be used by ignore_request() to indicate * it has been determined we should intersect two regulatory domains */ #define REG_INTERSECT 1 /* This has the logic which determines when a new request * should be ignored. */ static int ignore_request(struct wiphy *wiphy, struct regulatory_request *pending_request) { struct wiphy *last_wiphy = NULL; assert_cfg80211_lock(); /* All initial requests are respected */ if (!last_request) return 0; switch (pending_request->initiator) { case NL80211_REGDOM_SET_BY_CORE: return 0; case NL80211_REGDOM_SET_BY_COUNTRY_IE: last_wiphy = wiphy_idx_to_wiphy(last_request->wiphy_idx); if (unlikely(!is_an_alpha2(pending_request->alpha2))) return -EINVAL; if (last_request->initiator == NL80211_REGDOM_SET_BY_COUNTRY_IE) { if (last_wiphy != wiphy) { /* * Two cards with two APs claiming different * Country IE alpha2s. We could * intersect them, but that seems unlikely * to be correct. Reject second one for now. */ if (regdom_changes(pending_request->alpha2)) return -EOPNOTSUPP; return -EALREADY; } /* * Two consecutive Country IE hints on the same wiphy. * This should be picked up early by the driver/stack */ if (WARN_ON(regdom_changes(pending_request->alpha2))) return 0; return -EALREADY; } return 0; case NL80211_REGDOM_SET_BY_DRIVER: if (last_request->initiator == NL80211_REGDOM_SET_BY_CORE) { if (regdom_changes(pending_request->alpha2)) return 0; return -EALREADY; } /* * This would happen if you unplug and plug your card * back in or if you add a new device for which the previously * loaded card also agrees on the regulatory domain. */ if (last_request->initiator == NL80211_REGDOM_SET_BY_DRIVER && !regdom_changes(pending_request->alpha2)) return -EALREADY; return REG_INTERSECT; case NL80211_REGDOM_SET_BY_USER: if (last_request->initiator == NL80211_REGDOM_SET_BY_COUNTRY_IE) return REG_INTERSECT; /* * If the user knows better the user should set the regdom * to their country before the IE is picked up */ if (last_request->initiator == NL80211_REGDOM_SET_BY_USER && last_request->intersect) return -EOPNOTSUPP; /* * Process user requests only after previous user/driver/core * requests have been processed */ if (last_request->initiator == NL80211_REGDOM_SET_BY_CORE || last_request->initiator == NL80211_REGDOM_SET_BY_DRIVER || last_request->initiator == NL80211_REGDOM_SET_BY_USER) { if (regdom_changes(last_request->alpha2)) return -EAGAIN; } if (!regdom_changes(pending_request->alpha2)) return -EALREADY; return 0; } return -EINVAL; } static void reg_set_request_processed(void) { bool need_more_processing = false; last_request->processed = true; spin_lock(&reg_requests_lock); if (!list_empty(&reg_requests_list)) need_more_processing = true; spin_unlock(&reg_requests_lock); if (last_request->initiator == NL80211_REGDOM_SET_BY_USER) cancel_delayed_work_sync(&reg_timeout); if (need_more_processing) schedule_work(&reg_work); } /** * __regulatory_hint - hint to the wireless core a regulatory domain * @wiphy: if the hint comes from country information from an AP, this * is required to be set to the wiphy that received the information * @pending_request: the regulatory request currently being processed * * The Wireless subsystem can use this function to hint to the wireless core * what it believes should be the current regulatory domain. * * Returns zero if all went fine, %-EALREADY if a regulatory domain had * already been set or other standard error codes. * * Caller must hold &cfg80211_mutex and &reg_mutex */ static int __regulatory_hint(struct wiphy *wiphy, struct regulatory_request *pending_request) { bool intersect = false; int r = 0; assert_cfg80211_lock(); r = ignore_request(wiphy, pending_request); if (r == REG_INTERSECT) { if (pending_request->initiator == NL80211_REGDOM_SET_BY_DRIVER) { r = reg_copy_regd(&wiphy->regd, cfg80211_regdomain); if (r) { kfree(pending_request); return r; } } intersect = true; } else if (r) { /* * If the regulatory domain being requested by the * driver has already been set just copy it to the * wiphy */ if (r == -EALREADY && pending_request->initiator == NL80211_REGDOM_SET_BY_DRIVER) { r = reg_copy_regd(&wiphy->regd, cfg80211_regdomain); if (r) { kfree(pending_request); return r; } r = -EALREADY; goto new_request; } kfree(pending_request); return r; } new_request: if (last_request != &core_request_world) kfree(last_request); last_request = pending_request; last_request->intersect = intersect; pending_request = NULL; if (last_request->initiator == NL80211_REGDOM_SET_BY_USER) { user_alpha2[0] = last_request->alpha2[0]; user_alpha2[1] = last_request->alpha2[1]; } /* When r == REG_INTERSECT we do need to call CRDA */ if (r < 0) { /* * Since CRDA will not be called in this case as we already * have applied the requested regulatory domain before we just * inform userspace we have processed the request */ if (r == -EALREADY) { nl80211_send_reg_change_event(last_request); reg_set_request_processed(); } return r; } return call_crda(last_request->alpha2); } /* This processes *all* regulatory hints */ static void reg_process_hint(struct regulatory_request *reg_request) { int r = 0; struct wiphy *wiphy = NULL; enum nl80211_reg_initiator initiator = reg_request->initiator; BUG_ON(!reg_request->alpha2); if (wiphy_idx_valid(reg_request->wiphy_idx)) wiphy = wiphy_idx_to_wiphy(reg_request->wiphy_idx); if (reg_request->initiator == NL80211_REGDOM_SET_BY_DRIVER && !wiphy) { kfree(reg_request); return; } r = __regulatory_hint(wiphy, reg_request); /* This is required so that the orig_* parameters are saved */ if (r == -EALREADY && wiphy && wiphy->flags & WIPHY_FLAG_STRICT_REGULATORY) { wiphy_update_regulatory(wiphy, initiator); return; } /* * We only time out user hints, given that they should be the only * source of bogus requests. */ if (r != -EALREADY && reg_request->initiator == NL80211_REGDOM_SET_BY_USER) schedule_delayed_work(&reg_timeout, msecs_to_jiffies(3142)); } /* * Processes regulatory hints, this is all the NL80211_REGDOM_SET_BY_* * Regulatory hints come on a first come first serve basis and we * must process each one atomically. */ static void reg_process_pending_hints(void) { struct regulatory_request *reg_request; mutex_lock(&cfg80211_mutex); mutex_lock(&reg_mutex); /* When last_request->processed becomes true this will be rescheduled */ if (last_request && !last_request->processed) { REG_DBG_PRINT("Pending regulatory request, waiting " "for it to be processed...\n"); goto out; } spin_lock(&reg_requests_lock); if (list_empty(&reg_requests_list)) { spin_unlock(&reg_requests_lock); goto out; } reg_request = list_first_entry(&reg_requests_list, struct regulatory_request, list); list_del_init(&reg_request->list); spin_unlock(&reg_requests_lock); reg_process_hint(reg_request); out: mutex_unlock(&reg_mutex); mutex_unlock(&cfg80211_mutex); } /* Processes beacon hints -- this has nothing to do with country IEs */ static void reg_process_pending_beacon_hints(void) { struct cfg80211_registered_device *rdev; struct reg_beacon *pending_beacon, *tmp; /* * No need to hold the reg_mutex here as we just touch wiphys * and do not read or access regulatory variables. */ mutex_lock(&cfg80211_mutex); /* This goes through the _pending_ beacon list */ spin_lock_bh(&reg_pending_beacons_lock); if (list_empty(&reg_pending_beacons)) { spin_unlock_bh(&reg_pending_beacons_lock); goto out; } list_for_each_entry_safe(pending_beacon, tmp, &reg_pending_beacons, list) { list_del_init(&pending_beacon->list); /* Applies the beacon hint to current wiphys */ list_for_each_entry(rdev, &cfg80211_rdev_list, list) wiphy_update_new_beacon(&rdev->wiphy, pending_beacon); /* Remembers the beacon hint for new wiphys or reg changes */ list_add_tail(&pending_beacon->list, &reg_beacon_list); } spin_unlock_bh(&reg_pending_beacons_lock); out: mutex_unlock(&cfg80211_mutex); } static void reg_todo(struct work_struct *work) { reg_process_pending_hints(); reg_process_pending_beacon_hints(); } static void queue_regulatory_request(struct regulatory_request *request) { if (isalpha(request->alpha2[0])) request->alpha2[0] = toupper(request->alpha2[0]); if (isalpha(request->alpha2[1])) request->alpha2[1] = toupper(request->alpha2[1]); spin_lock(&reg_requests_lock); list_add_tail(&request->list, &reg_requests_list); spin_unlock(&reg_requests_lock); schedule_work(&reg_work); } /* * Core regulatory hint -- happens during cfg80211_init() * and when we restore regulatory settings. */ static int regulatory_hint_core(const char *alpha2) { struct regulatory_request *request; request = kzalloc(sizeof(struct regulatory_request), GFP_KERNEL); if (!request) return -ENOMEM; request->alpha2[0] = alpha2[0]; request->alpha2[1] = alpha2[1]; request->initiator = NL80211_REGDOM_SET_BY_CORE; queue_regulatory_request(request); return 0; } /* User hints */ int regulatory_hint_user(const char *alpha2) { struct regulatory_request *request; BUG_ON(!alpha2); request = kzalloc(sizeof(struct regulatory_request), GFP_KERNEL); if (!request) return -ENOMEM; request->wiphy_idx = WIPHY_IDX_STALE; request->alpha2[0] = alpha2[0]; request->alpha2[1] = alpha2[1]; request->initiator = NL80211_REGDOM_SET_BY_USER; queue_regulatory_request(request); return 0; } /* Driver hints */ int regulatory_hint(struct wiphy *wiphy, const char *alpha2) { struct regulatory_request *request; BUG_ON(!alpha2); BUG_ON(!wiphy); request = kzalloc(sizeof(struct regulatory_request), GFP_KERNEL); if (!request) return -ENOMEM; request->wiphy_idx = get_wiphy_idx(wiphy); /* Must have registered wiphy first */ BUG_ON(!wiphy_idx_valid(request->wiphy_idx)); request->alpha2[0] = alpha2[0]; request->alpha2[1] = alpha2[1]; request->initiator = NL80211_REGDOM_SET_BY_DRIVER; queue_regulatory_request(request); return 0; } EXPORT_SYMBOL(regulatory_hint); /* * We hold wdev_lock() here so we cannot hold cfg80211_mutex() and * therefore cannot iterate over the rdev list here. */ void regulatory_hint_11d(struct wiphy *wiphy, enum ieee80211_band band, u8 *country_ie, u8 country_ie_len) { char alpha2[2]; enum environment_cap env = ENVIRON_ANY; struct regulatory_request *request; mutex_lock(&reg_mutex); if (unlikely(!last_request)) goto out; /* IE len must be evenly divisible by 2 */ if (country_ie_len & 0x01) goto out; if (country_ie_len < IEEE80211_COUNTRY_IE_MIN_LEN) goto out; alpha2[0] = country_ie[0]; alpha2[1] = country_ie[1]; if (country_ie[2] == 'I') env = ENVIRON_INDOOR; else if (country_ie[2] == 'O') env = ENVIRON_OUTDOOR; /* * We will run this only upon a successful connection on cfg80211. * We leave conflict resolution to the workqueue, where can hold * cfg80211_mutex. */ if (likely(last_request->initiator == NL80211_REGDOM_SET_BY_COUNTRY_IE && wiphy_idx_valid(last_request->wiphy_idx))) goto out; request = kzalloc(sizeof(struct regulatory_request), GFP_KERNEL); if (!request) goto out; request->wiphy_idx = get_wiphy_idx(wiphy); request->alpha2[0] = alpha2[0]; request->alpha2[1] = alpha2[1]; request->initiator = NL80211_REGDOM_SET_BY_COUNTRY_IE; request->country_ie_env = env; mutex_unlock(&reg_mutex); queue_regulatory_request(request); return; out: mutex_unlock(&reg_mutex); } static void restore_alpha2(char *alpha2, bool reset_user) { /* indicates there is no alpha2 to consider for restoration */ alpha2[0] = '9'; alpha2[1] = '7'; /* The user setting has precedence over the module parameter */ if (is_user_regdom_saved()) { /* Unless we're asked to ignore it and reset it */ if (reset_user) { REG_DBG_PRINT("Restoring regulatory settings " "including user preference\n"); user_alpha2[0] = '9'; user_alpha2[1] = '7'; /* * If we're ignoring user settings, we still need to * check the module parameter to ensure we put things * back as they were for a full restore. */ if (!is_world_regdom(ieee80211_regdom)) { REG_DBG_PRINT("Keeping preference on " "module parameter ieee80211_regdom: %c%c\n", ieee80211_regdom[0], ieee80211_regdom[1]); alpha2[0] = ieee80211_regdom[0]; alpha2[1] = ieee80211_regdom[1]; } } else { REG_DBG_PRINT("Restoring regulatory settings " "while preserving user preference for: %c%c\n", user_alpha2[0], user_alpha2[1]); alpha2[0] = user_alpha2[0]; alpha2[1] = user_alpha2[1]; } } else if (!is_world_regdom(ieee80211_regdom)) { REG_DBG_PRINT("Keeping preference on " "module parameter ieee80211_regdom: %c%c\n", ieee80211_regdom[0], ieee80211_regdom[1]); alpha2[0] = ieee80211_regdom[0]; alpha2[1] = ieee80211_regdom[1]; } else REG_DBG_PRINT("Restoring regulatory settings\n"); } /* * Restoring regulatory settings involves ingoring any * possibly stale country IE information and user regulatory * settings if so desired, this includes any beacon hints * learned as we could have traveled outside to another country * after disconnection. To restore regulatory settings we do * exactly what we did at bootup: * * - send a core regulatory hint * - send a user regulatory hint if applicable * * Device drivers that send a regulatory hint for a specific country * keep their own regulatory domain on wiphy->regd so that does does * not need to be remembered. */ static void restore_regulatory_settings(bool reset_user) { char alpha2[2]; struct reg_beacon *reg_beacon, *btmp; struct regulatory_request *reg_request, *tmp; LIST_HEAD(tmp_reg_req_list); mutex_lock(&cfg80211_mutex); mutex_lock(&reg_mutex); reset_regdomains(true); restore_alpha2(alpha2, reset_user); /* * If there's any pending requests we simply * stash them to a temporary pending queue and * add then after we've restored regulatory * settings. */ spin_lock(&reg_requests_lock); if (!list_empty(&reg_requests_list)) { list_for_each_entry_safe(reg_request, tmp, &reg_requests_list, list) { if (reg_request->initiator != NL80211_REGDOM_SET_BY_USER) continue; list_del(&reg_request->list); list_add_tail(&reg_request->list, &tmp_reg_req_list); } } spin_unlock(&reg_requests_lock); /* Clear beacon hints */ spin_lock_bh(&reg_pending_beacons_lock); if (!list_empty(&reg_pending_beacons)) { list_for_each_entry_safe(reg_beacon, btmp, &reg_pending_beacons, list) { list_del(&reg_beacon->list); kfree(reg_beacon); } } spin_unlock_bh(&reg_pending_beacons_lock); if (!list_empty(&reg_beacon_list)) { list_for_each_entry_safe(reg_beacon, btmp, &reg_beacon_list, list) { list_del(&reg_beacon->list); kfree(reg_beacon); } } /* First restore to the basic regulatory settings */ cfg80211_regdomain = cfg80211_world_regdom; mutex_unlock(&reg_mutex); mutex_unlock(&cfg80211_mutex); regulatory_hint_core(cfg80211_regdomain->alpha2); /* * This restores the ieee80211_regdom module parameter * preference or the last user requested regulatory * settings, user regulatory settings takes precedence. */ if (is_an_alpha2(alpha2)) regulatory_hint_user(user_alpha2); if (list_empty(&tmp_reg_req_list)) return; mutex_lock(&cfg80211_mutex); mutex_lock(&reg_mutex); spin_lock(&reg_requests_lock); list_for_each_entry_safe(reg_request, tmp, &tmp_reg_req_list, list) { REG_DBG_PRINT("Adding request for country %c%c back " "into the queue\n", reg_request->alpha2[0], reg_request->alpha2[1]); list_del(&reg_request->list); list_add_tail(&reg_request->list, &reg_requests_list); } spin_unlock(&reg_requests_lock); mutex_unlock(&reg_mutex); mutex_unlock(&cfg80211_mutex); REG_DBG_PRINT("Kicking the queue\n"); schedule_work(&reg_work); } void regulatory_hint_disconnect(void) { REG_DBG_PRINT("All devices are disconnected, going to " "restore regulatory settings\n"); restore_regulatory_settings(false); } static bool freq_is_chan_12_13_14(u16 freq) { if (freq == ieee80211_channel_to_frequency(12, IEEE80211_BAND_2GHZ) || freq == ieee80211_channel_to_frequency(13, IEEE80211_BAND_2GHZ) || freq == ieee80211_channel_to_frequency(14, IEEE80211_BAND_2GHZ)) return true; return false; } int regulatory_hint_found_beacon(struct wiphy *wiphy, struct ieee80211_channel *beacon_chan, gfp_t gfp) { struct reg_beacon *reg_beacon; if (likely((beacon_chan->beacon_found || (beacon_chan->flags & IEEE80211_CHAN_RADAR) || (beacon_chan->band == IEEE80211_BAND_2GHZ && !freq_is_chan_12_13_14(beacon_chan->center_freq))))) return 0; reg_beacon = kzalloc(sizeof(struct reg_beacon), gfp); if (!reg_beacon) return -ENOMEM; REG_DBG_PRINT("Found new beacon on " "frequency: %d MHz (Ch %d) on %s\n", beacon_chan->center_freq, ieee80211_frequency_to_channel(beacon_chan->center_freq), wiphy_name(wiphy)); memcpy(&reg_beacon->chan, beacon_chan, sizeof(struct ieee80211_channel)); /* * Since we can be called from BH or and non-BH context * we must use spin_lock_bh() */ spin_lock_bh(&reg_pending_beacons_lock); list_add_tail(&reg_beacon->list, &reg_pending_beacons); spin_unlock_bh(&reg_pending_beacons_lock); schedule_work(&reg_work); return 0; } static void print_rd_rules(const struct ieee80211_regdomain *rd) { unsigned int i; const struct ieee80211_reg_rule *reg_rule = NULL; const struct ieee80211_freq_range *freq_range = NULL; const struct ieee80211_power_rule *power_rule = NULL; pr_info(" (start_freq - end_freq @ bandwidth), (max_antenna_gain, max_eirp)\n"); for (i = 0; i < rd->n_reg_rules; i++) { reg_rule = &rd->reg_rules[i]; freq_range = &reg_rule->freq_range; power_rule = &reg_rule->power_rule; /* * There may not be documentation for max antenna gain * in certain regions */ if (power_rule->max_antenna_gain) pr_info(" (%d KHz - %d KHz @ %d KHz), (%d mBi, %d mBm)\n", freq_range->start_freq_khz, freq_range->end_freq_khz, freq_range->max_bandwidth_khz, power_rule->max_antenna_gain, power_rule->max_eirp); else pr_info(" (%d KHz - %d KHz @ %d KHz), (N/A, %d mBm)\n", freq_range->start_freq_khz, freq_range->end_freq_khz, freq_range->max_bandwidth_khz, power_rule->max_eirp); } } static void print_regdomain(const struct ieee80211_regdomain *rd) { if (is_intersected_alpha2(rd->alpha2)) { if (last_request->initiator == NL80211_REGDOM_SET_BY_COUNTRY_IE) { struct cfg80211_registered_device *rdev; rdev = cfg80211_rdev_by_wiphy_idx( last_request->wiphy_idx); if (rdev) { pr_info("Current regulatory domain updated by AP to: %c%c\n", rdev->country_ie_alpha2[0], rdev->country_ie_alpha2[1]); } else pr_info("Current regulatory domain intersected:\n"); } else pr_info("Current regulatory domain intersected:\n"); } else if (is_world_regdom(rd->alpha2)) pr_info("World regulatory domain updated:\n"); else { if (is_unknown_alpha2(rd->alpha2)) pr_info("Regulatory domain changed to driver built-in settings (unknown country)\n"); else pr_info("Regulatory domain changed to country: %c%c\n", rd->alpha2[0], rd->alpha2[1]); } print_rd_rules(rd); } static void print_regdomain_info(const struct ieee80211_regdomain *rd) { pr_info("Regulatory domain: %c%c\n", rd->alpha2[0], rd->alpha2[1]); print_rd_rules(rd); } /* Takes ownership of rd only if it doesn't fail */ static int __set_regdom(const struct ieee80211_regdomain *rd) { const struct ieee80211_regdomain *intersected_rd = NULL; struct cfg80211_registered_device *rdev = NULL; struct wiphy *request_wiphy; /* Some basic sanity checks first */ if (is_world_regdom(rd->alpha2)) { if (WARN_ON(!reg_is_valid_request(rd->alpha2))) return -EINVAL; update_world_regdomain(rd); return 0; } if (!is_alpha2_set(rd->alpha2) && !is_an_alpha2(rd->alpha2) && !is_unknown_alpha2(rd->alpha2)) return -EINVAL; if (!last_request) return -EINVAL; /* * Lets only bother proceeding on the same alpha2 if the current * rd is non static (it means CRDA was present and was used last) * and the pending request came in from a country IE */ if (last_request->initiator != NL80211_REGDOM_SET_BY_COUNTRY_IE) { /* * If someone else asked us to change the rd lets only bother * checking if the alpha2 changes if CRDA was already called */ if (!regdom_changes(rd->alpha2)) return -EINVAL; } /* * Now lets set the regulatory domain, update all driver channels * and finally inform them of what we have done, in case they want * to review or adjust their own settings based on their own * internal EEPROM data */ if (WARN_ON(!reg_is_valid_request(rd->alpha2))) return -EINVAL; if (!is_valid_rd(rd)) { pr_err("Invalid regulatory domain detected:\n"); print_regdomain_info(rd); return -EINVAL; } request_wiphy = wiphy_idx_to_wiphy(last_request->wiphy_idx); if (!request_wiphy && (last_request->initiator == NL80211_REGDOM_SET_BY_DRIVER || last_request->initiator == NL80211_REGDOM_SET_BY_COUNTRY_IE)) { schedule_delayed_work(&reg_timeout, 0); return -ENODEV; } if (!last_request->intersect) { int r; if (last_request->initiator != NL80211_REGDOM_SET_BY_DRIVER) { reset_regdomains(false); cfg80211_regdomain = rd; return 0; } /* * For a driver hint, lets copy the regulatory domain the * driver wanted to the wiphy to deal with conflicts */ /* * Userspace could have sent two replies with only * one kernel request. */ if (request_wiphy->regd) return -EALREADY; r = reg_copy_regd(&request_wiphy->regd, rd); if (r) return r; reset_regdomains(false); cfg80211_regdomain = rd; return 0; } /* Intersection requires a bit more work */ if (last_request->initiator != NL80211_REGDOM_SET_BY_COUNTRY_IE) { intersected_rd = regdom_intersect(rd, cfg80211_regdomain); if (!intersected_rd) return -EINVAL; /* * We can trash what CRDA provided now. * However if a driver requested this specific regulatory * domain we keep it for its private use */ if (last_request->initiator == NL80211_REGDOM_SET_BY_DRIVER) request_wiphy->regd = rd; else kfree(rd); rd = NULL; reset_regdomains(false); cfg80211_regdomain = intersected_rd; return 0; } if (!intersected_rd) return -EINVAL; rdev = wiphy_to_dev(request_wiphy); rdev->country_ie_alpha2[0] = rd->alpha2[0]; rdev->country_ie_alpha2[1] = rd->alpha2[1]; rdev->env = last_request->country_ie_env; BUG_ON(intersected_rd == rd); kfree(rd); rd = NULL; reset_regdomains(false); cfg80211_regdomain = intersected_rd; return 0; } /* * Use this call to set the current regulatory domain. Conflicts with * multiple drivers can be ironed out later. Caller must've already * kmalloc'd the rd structure. Caller must hold cfg80211_mutex */ int set_regdom(const struct ieee80211_regdomain *rd) { int r; assert_cfg80211_lock(); mutex_lock(&reg_mutex); /* Note that this doesn't update the wiphys, this is done below */ r = __set_regdom(rd); if (r) { kfree(rd); mutex_unlock(&reg_mutex); return r; } /* This would make this whole thing pointless */ if (!last_request->intersect) BUG_ON(rd != cfg80211_regdomain); /* update all wiphys now with the new established regulatory domain */ update_all_wiphy_regulatory(last_request->initiator); print_regdomain(cfg80211_regdomain); nl80211_send_reg_change_event(last_request); reg_set_request_processed(); mutex_unlock(&reg_mutex); return r; } #ifdef CONFIG_HOTPLUG int reg_device_uevent(struct device *dev, struct kobj_uevent_env *env) { if (last_request && !last_request->processed) { if (add_uevent_var(env, "COUNTRY=%c%c", last_request->alpha2[0], last_request->alpha2[1])) return -ENOMEM; } return 0; } #else int reg_device_uevent(struct device *dev, struct kobj_uevent_env *env) { return -ENODEV; } #endif /* CONFIG_HOTPLUG */ /* Caller must hold cfg80211_mutex */ void reg_device_remove(struct wiphy *wiphy) { struct wiphy *request_wiphy = NULL; assert_cfg80211_lock(); mutex_lock(&reg_mutex); kfree(wiphy->regd); if (last_request) request_wiphy = wiphy_idx_to_wiphy(last_request->wiphy_idx); if (!request_wiphy || request_wiphy != wiphy) goto out; last_request->wiphy_idx = WIPHY_IDX_STALE; last_request->country_ie_env = ENVIRON_ANY; out: mutex_unlock(&reg_mutex); } static void reg_timeout_work(struct work_struct *work) { REG_DBG_PRINT("Timeout while waiting for CRDA to reply, " "restoring regulatory settings\n"); restore_regulatory_settings(true); } int __init regulatory_init(void) { int err = 0; reg_pdev = platform_device_register_simple("regulatory", 0, NULL, 0); if (IS_ERR(reg_pdev)) return PTR_ERR(reg_pdev); reg_pdev->dev.type = &reg_device_type; spin_lock_init(&reg_requests_lock); spin_lock_init(&reg_pending_beacons_lock); reg_regdb_size_check(); cfg80211_regdomain = cfg80211_world_regdom; user_alpha2[0] = '9'; user_alpha2[1] = '7'; /* We always try to get an update for the static regdomain */ err = regulatory_hint_core(cfg80211_regdomain->alpha2); if (err) { if (err == -ENOMEM) return err; /* * N.B. kobject_uevent_env() can fail mainly for when we're out * memory which is handled and propagated appropriately above * but it can also fail during a netlink_broadcast() or during * early boot for call_usermodehelper(). For now treat these * errors as non-fatal. */ pr_err("kobject_uevent_env() was unable to call CRDA during init\n"); #ifdef CONFIG_CFG80211_REG_DEBUG /* We want to find out exactly why when debugging */ WARN_ON(err); #endif } /* * Finally, if the user set the module parameter treat it * as a user hint. */ if (!is_world_regdom(ieee80211_regdom)) regulatory_hint_user(ieee80211_regdom); return 0; } void /* __init_or_exit */ regulatory_exit(void) { struct regulatory_request *reg_request, *tmp; struct reg_beacon *reg_beacon, *btmp; cancel_work_sync(&reg_work); cancel_delayed_work_sync(&reg_timeout); mutex_lock(&cfg80211_mutex); mutex_lock(&reg_mutex); reset_regdomains(true); dev_set_uevent_suppress(&reg_pdev->dev, true); platform_device_unregister(reg_pdev); spin_lock_bh(&reg_pending_beacons_lock); if (!list_empty(&reg_pending_beacons)) { list_for_each_entry_safe(reg_beacon, btmp, &reg_pending_beacons, list) { list_del(&reg_beacon->list); kfree(reg_beacon); } } spin_unlock_bh(&reg_pending_beacons_lock); if (!list_empty(&reg_beacon_list)) { list_for_each_entry_safe(reg_beacon, btmp, &reg_beacon_list, list) { list_del(&reg_beacon->list); kfree(reg_beacon); } } spin_lock(&reg_requests_lock); if (!list_empty(&reg_requests_list)) { list_for_each_entry_safe(reg_request, tmp, &reg_requests_list, list) { list_del(&reg_request->list); kfree(reg_request); } } spin_unlock(&reg_requests_lock); mutex_unlock(&reg_mutex); mutex_unlock(&cfg80211_mutex); }
Java
/*************************************************************************** qgssourcefieldsproperties.cpp --------------------- begin : July 2017 copyright : (C) 2017 by David Signer email : david at opengis dot ch *************************************************************************** * * * 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. * * * ***************************************************************************/ #include "qgssourcefieldsproperties.h" #include "qgsvectorlayer.h" #include "qgsproject.h" QgsSourceFieldsProperties::QgsSourceFieldsProperties( QgsVectorLayer *layer, QWidget *parent ) : QWidget( parent ) , mLayer( layer ) { if ( !layer ) return; setupUi( this ); layout()->setContentsMargins( 0, 0, 0, 0 ); layout()->setMargin( 0 ); //button appearance mAddAttributeButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionNewAttribute.svg" ) ) ); mDeleteAttributeButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionDeleteAttribute.svg" ) ) ); mToggleEditingButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionToggleEditing.svg" ) ) ); mCalculateFieldButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionCalculateField.svg" ) ) ); //button signals connect( mToggleEditingButton, &QAbstractButton::clicked, this, &QgsSourceFieldsProperties::toggleEditing ); connect( mAddAttributeButton, &QAbstractButton::clicked, this, &QgsSourceFieldsProperties::addAttributeClicked ); connect( mDeleteAttributeButton, &QAbstractButton::clicked, this, &QgsSourceFieldsProperties::deleteAttributeClicked ); connect( mCalculateFieldButton, &QAbstractButton::clicked, this, &QgsSourceFieldsProperties::calculateFieldClicked ); //slots connect( mLayer, &QgsVectorLayer::editingStarted, this, &QgsSourceFieldsProperties::editingToggled ); connect( mLayer, &QgsVectorLayer::editingStopped, this, &QgsSourceFieldsProperties::editingToggled ); connect( mLayer, &QgsVectorLayer::attributeAdded, this, &QgsSourceFieldsProperties::attributeAdded ); connect( mLayer, &QgsVectorLayer::attributeDeleted, this, &QgsSourceFieldsProperties::attributeDeleted ); //field list appearance mFieldsList->setColumnCount( AttrColCount ); mFieldsList->setSelectionBehavior( QAbstractItemView::SelectRows ); mFieldsList->setDragDropMode( QAbstractItemView::DragOnly ); mFieldsList->setHorizontalHeaderItem( AttrIdCol, new QTableWidgetItem( tr( "Id" ) ) ); mFieldsList->setHorizontalHeaderItem( AttrNameCol, new QTableWidgetItem( tr( "Name" ) ) ); mFieldsList->setHorizontalHeaderItem( AttrTypeCol, new QTableWidgetItem( tr( "Type" ) ) ); mFieldsList->setHorizontalHeaderItem( AttrTypeNameCol, new QTableWidgetItem( tr( "Type name" ) ) ); mFieldsList->setHorizontalHeaderItem( AttrLengthCol, new QTableWidgetItem( tr( "Length" ) ) ); mFieldsList->setHorizontalHeaderItem( AttrPrecCol, new QTableWidgetItem( tr( "Precision" ) ) ); mFieldsList->setHorizontalHeaderItem( AttrCommentCol, new QTableWidgetItem( tr( "Comment" ) ) ); mFieldsList->setHorizontalHeaderItem( AttrWMSCol, new QTableWidgetItem( QStringLiteral( "WMS" ) ) ); mFieldsList->setHorizontalHeaderItem( AttrWFSCol, new QTableWidgetItem( QStringLiteral( "WFS" ) ) ); mFieldsList->setHorizontalHeaderItem( AttrAliasCol, new QTableWidgetItem( tr( "Alias" ) ) ); mFieldsList->setSortingEnabled( true ); mFieldsList->sortByColumn( 0, Qt::AscendingOrder ); mFieldsList->setSelectionBehavior( QAbstractItemView::SelectRows ); mFieldsList->setSelectionMode( QAbstractItemView::ExtendedSelection ); mFieldsList->verticalHeader()->hide(); //load buttons and field list updateButtons(); } void QgsSourceFieldsProperties::init() { loadRows(); } void QgsSourceFieldsProperties::loadRows() { disconnect( mFieldsList, &QTableWidget::cellChanged, this, &QgsSourceFieldsProperties::attributesListCellChanged ); const QgsFields &fields = mLayer->fields(); mIndexedWidgets.clear(); mFieldsList->setRowCount( 0 ); for ( int i = 0; i < fields.count(); ++i ) attributeAdded( i ); mFieldsList->resizeColumnsToContents(); connect( mFieldsList, &QTableWidget::cellChanged, this, &QgsSourceFieldsProperties::attributesListCellChanged ); connect( mFieldsList, &QTableWidget::cellPressed, this, &QgsSourceFieldsProperties::attributesListCellPressed ); updateButtons(); updateFieldRenamingStatus(); } void QgsSourceFieldsProperties::updateFieldRenamingStatus() { bool canRenameFields = mLayer->isEditable() && ( mLayer->dataProvider()->capabilities() & QgsVectorDataProvider::RenameAttributes ) && !mLayer->readOnly(); for ( int row = 0; row < mFieldsList->rowCount(); ++row ) { if ( canRenameFields ) mFieldsList->item( row, AttrNameCol )->setFlags( mFieldsList->item( row, AttrNameCol )->flags() | Qt::ItemIsEditable ); else mFieldsList->item( row, AttrNameCol )->setFlags( mFieldsList->item( row, AttrNameCol )->flags() & ~Qt::ItemIsEditable ); } } void QgsSourceFieldsProperties::updateExpression() { QToolButton *btn = qobject_cast<QToolButton *>( sender() ); Q_ASSERT( btn ); int index = btn->property( "Index" ).toInt(); const QString exp = mLayer->expressionField( index ); QgsExpressionContext context; context << QgsExpressionContextUtils::globalScope() << QgsExpressionContextUtils::projectScope( QgsProject::instance() ); QgsExpressionBuilderDialog dlg( mLayer, exp, nullptr, QStringLiteral( "generic" ), context ); if ( dlg.exec() ) { mLayer->updateExpressionField( index, dlg.expressionText() ); loadRows(); } } void QgsSourceFieldsProperties::attributeAdded( int idx ) { bool sorted = mFieldsList->isSortingEnabled(); if ( sorted ) mFieldsList->setSortingEnabled( false ); const QgsFields &fields = mLayer->fields(); int row = mFieldsList->rowCount(); mFieldsList->insertRow( row ); setRow( row, idx, fields.at( idx ) ); mFieldsList->setCurrentCell( row, idx ); //in case there are rows following, there is increased the id to the correct ones for ( int i = idx + 1; i < mIndexedWidgets.count(); i++ ) mIndexedWidgets.at( i )->setData( Qt::DisplayRole, i ); if ( sorted ) mFieldsList->setSortingEnabled( true ); for ( int i = 0; i < mFieldsList->columnCount(); i++ ) { switch ( mLayer->fields().fieldOrigin( idx ) ) { case QgsFields::OriginExpression: if ( i == 7 ) continue; mFieldsList->item( row, i )->setBackgroundColor( QColor( 200, 200, 255 ) ); break; case QgsFields::OriginJoin: mFieldsList->item( row, i )->setBackgroundColor( QColor( 200, 255, 200 ) ); break; default: mFieldsList->item( row, i )->setBackgroundColor( QColor( 255, 255, 200 ) ); break; } } } void QgsSourceFieldsProperties::attributeDeleted( int idx ) { mFieldsList->removeRow( mIndexedWidgets.at( idx )->row() ); mIndexedWidgets.removeAt( idx ); for ( int i = idx; i < mIndexedWidgets.count(); i++ ) { mIndexedWidgets.at( i )->setData( Qt::DisplayRole, i ); } } void QgsSourceFieldsProperties::setRow( int row, int idx, const QgsField &field ) { QTableWidgetItem *dataItem = new QTableWidgetItem(); dataItem->setData( Qt::DisplayRole, idx ); switch ( mLayer->fields().fieldOrigin( idx ) ) { case QgsFields::OriginExpression: dataItem->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mIconExpression.svg" ) ) ); break; case QgsFields::OriginJoin: dataItem->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/propertyicons/join.svg" ) ) ); break; default: dataItem->setIcon( mLayer->fields().iconForField( idx ) ); break; } mFieldsList->setItem( row, AttrIdCol, dataItem ); mIndexedWidgets.insert( idx, mFieldsList->item( row, 0 ) ); mFieldsList->setItem( row, AttrNameCol, new QTableWidgetItem( field.name() ) ); mFieldsList->setItem( row, AttrAliasCol, new QTableWidgetItem( field.alias() ) ); mFieldsList->setItem( row, AttrTypeCol, new QTableWidgetItem( QVariant::typeToName( field.type() ) ) ); mFieldsList->setItem( row, AttrTypeNameCol, new QTableWidgetItem( field.typeName() ) ); mFieldsList->setItem( row, AttrLengthCol, new QTableWidgetItem( QString::number( field.length() ) ) ); mFieldsList->setItem( row, AttrPrecCol, new QTableWidgetItem( QString::number( field.precision() ) ) ); if ( mLayer->fields().fieldOrigin( idx ) == QgsFields::OriginExpression ) { QWidget *expressionWidget = new QWidget; expressionWidget->setLayout( new QHBoxLayout ); QToolButton *editExpressionButton = new QToolButton; editExpressionButton->setProperty( "Index", idx ); editExpressionButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mIconExpression.svg" ) ) ); connect( editExpressionButton, &QAbstractButton::clicked, this, &QgsSourceFieldsProperties::updateExpression ); expressionWidget->layout()->setContentsMargins( 0, 0, 0, 0 ); expressionWidget->layout()->addWidget( editExpressionButton ); expressionWidget->layout()->addWidget( new QLabel( mLayer->expressionField( idx ) ) ); expressionWidget->setStyleSheet( "background-color: rgb( 200, 200, 255 )" ); mFieldsList->setCellWidget( row, AttrCommentCol, expressionWidget ); } else { mFieldsList->setItem( row, AttrCommentCol, new QTableWidgetItem( field.comment() ) ); } QList<int> notEditableCols = QList<int>() << AttrIdCol << AttrNameCol << AttrAliasCol << AttrTypeCol << AttrTypeNameCol << AttrLengthCol << AttrPrecCol << AttrCommentCol; Q_FOREACH ( int i, notEditableCols ) { if ( notEditableCols[i] != AttrCommentCol || mLayer->fields().fieldOrigin( idx ) != QgsFields::OriginExpression ) mFieldsList->item( row, i )->setFlags( mFieldsList->item( row, i )->flags() & ~Qt::ItemIsEditable ); if ( notEditableCols[i] == AttrAliasCol ) mFieldsList->item( row, i )->setToolTip( tr( "Edit alias in the Form config tab" ) ); } bool canRenameFields = mLayer->isEditable() && ( mLayer->dataProvider()->capabilities() & QgsVectorDataProvider::RenameAttributes ) && !mLayer->readOnly(); if ( canRenameFields ) mFieldsList->item( row, AttrNameCol )->setFlags( mFieldsList->item( row, AttrNameCol )->flags() | Qt::ItemIsEditable ); else mFieldsList->item( row, AttrNameCol )->setFlags( mFieldsList->item( row, AttrNameCol )->flags() & ~Qt::ItemIsEditable ); //published WMS/WFS attributes QTableWidgetItem *wmsAttrItem = new QTableWidgetItem(); wmsAttrItem->setCheckState( mLayer->excludeAttributesWms().contains( field.name() ) ? Qt::Unchecked : Qt::Checked ); wmsAttrItem->setFlags( Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable ); mFieldsList->setItem( row, AttrWMSCol, wmsAttrItem ); QTableWidgetItem *wfsAttrItem = new QTableWidgetItem(); wfsAttrItem->setCheckState( mLayer->excludeAttributesWfs().contains( field.name() ) ? Qt::Unchecked : Qt::Checked ); wfsAttrItem->setFlags( Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable ); mFieldsList->setItem( row, AttrWFSCol, wfsAttrItem ); } bool QgsSourceFieldsProperties::addAttribute( const QgsField &field ) { QgsDebugMsg( "inserting attribute " + field.name() + " of type " + field.typeName() ); mLayer->beginEditCommand( tr( "Added attribute" ) ); if ( mLayer->addAttribute( field ) ) { mLayer->endEditCommand(); return true; } else { mLayer->destroyEditCommand(); QMessageBox::critical( this, tr( "Add Field" ), tr( "Failed to add field '%1' of type '%2'. Is the field name unique?" ).arg( field.name(), field.typeName() ) ); return false; } } void QgsSourceFieldsProperties::apply() { QSet<QString> excludeAttributesWMS, excludeAttributesWFS; for ( int i = 0; i < mFieldsList->rowCount(); i++ ) { if ( mFieldsList->item( i, AttrWMSCol )->checkState() == Qt::Unchecked ) { excludeAttributesWMS.insert( mFieldsList->item( i, AttrNameCol )->text() ); } if ( mFieldsList->item( i, AttrWFSCol )->checkState() == Qt::Unchecked ) { excludeAttributesWFS.insert( mFieldsList->item( i, AttrNameCol )->text() ); } } mLayer->setExcludeAttributesWms( excludeAttributesWMS ); mLayer->setExcludeAttributesWfs( excludeAttributesWFS ); } //SLOTS void QgsSourceFieldsProperties::editingToggled() { updateButtons(); updateFieldRenamingStatus(); } void QgsSourceFieldsProperties::addAttributeClicked() { QgsAddAttrDialog dialog( mLayer, this ); if ( dialog.exec() == QDialog::Accepted ) { addAttribute( dialog.field() ); loadRows(); } } void QgsSourceFieldsProperties::deleteAttributeClicked() { QSet<int> providerFields; QSet<int> expressionFields; Q_FOREACH ( QTableWidgetItem *item, mFieldsList->selectedItems() ) { if ( item->column() == 0 ) { int idx = mIndexedWidgets.indexOf( item ); if ( idx < 0 ) continue; if ( mLayer->fields().fieldOrigin( idx ) == QgsFields::OriginExpression ) expressionFields << idx; else providerFields << idx; } } if ( !expressionFields.isEmpty() ) mLayer->deleteAttributes( expressionFields.toList() ); if ( !providerFields.isEmpty() ) { mLayer->beginEditCommand( tr( "Deleted attributes" ) ); if ( mLayer->deleteAttributes( providerFields.toList() ) ) mLayer->endEditCommand(); else mLayer->destroyEditCommand(); } } void QgsSourceFieldsProperties::calculateFieldClicked() { if ( !mLayer ) { return; } QgsFieldCalculator calc( mLayer, this ); if ( calc.exec() == QDialog::Accepted ) { loadRows(); } } void QgsSourceFieldsProperties::attributesListCellChanged( int row, int column ) { if ( column == AttrNameCol && mLayer && mLayer->isEditable() ) { int idx = mIndexedWidgets.indexOf( mFieldsList->item( row, AttrIdCol ) ); QTableWidgetItem *nameItem = mFieldsList->item( row, column ); //avoiding that something will be changed, just because this is triggered by simple re-sorting if ( !nameItem || nameItem->text().isEmpty() || !mLayer->fields().exists( idx ) || mLayer->fields().at( idx ).name() == nameItem->text() ) return; mLayer->beginEditCommand( tr( "Rename attribute" ) ); if ( mLayer->renameAttribute( idx, nameItem->text() ) ) { mLayer->endEditCommand(); } else { mLayer->destroyEditCommand(); QMessageBox::critical( this, tr( "Rename Field" ), tr( "Failed to rename field to '%1'. Is the field name unique?" ).arg( nameItem->text() ) ); } } } void QgsSourceFieldsProperties::attributesListCellPressed( int /*row*/, int /*column*/ ) { updateButtons(); } //NICE FUNCTIONS void QgsSourceFieldsProperties::updateButtons() { int cap = mLayer->dataProvider()->capabilities(); mToggleEditingButton->setEnabled( ( cap & QgsVectorDataProvider::ChangeAttributeValues ) && !mLayer->readOnly() ); if ( mLayer->isEditable() ) { mDeleteAttributeButton->setEnabled( cap & QgsVectorDataProvider::DeleteAttributes ); mAddAttributeButton->setEnabled( cap & QgsVectorDataProvider::AddAttributes ); mToggleEditingButton->setChecked( true ); } else { mToggleEditingButton->setChecked( false ); mAddAttributeButton->setEnabled( false ); // Enable delete button if items are selected mDeleteAttributeButton->setEnabled( !mFieldsList->selectedItems().isEmpty() ); // and only if all selected items have their origin in an expression Q_FOREACH ( QTableWidgetItem *item, mFieldsList->selectedItems() ) { if ( item->column() == 0 ) { int idx = mIndexedWidgets.indexOf( item ); if ( mLayer->fields().fieldOrigin( idx ) != QgsFields::OriginExpression ) { mDeleteAttributeButton->setEnabled( false ); break; } } } } }
Java
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); ?> <!DOCTYPE html> <html lang="es_MX"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title></title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'> <link rel="stylesheet" type="text/css" href="css/reset.css"> <link rel="stylesheet" type="text/css" href="css/estilo.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css"> <?php echo link_tag('css/sistema.css'); ?> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> </head> <body style="background-color: #ffffff;"> <div class="container-fluid1"> <div id="foo"> <p id="spin_label" style="position:absolute; width: 100%; top: 50%; margin-top: 60px; text-align: center;"> </p> </div> <div class="row-fluid1" id="wrapper1"> <div class="alert" id="messages"></div> <!-- Inicia Formulario -->
Java
/* * IMG Pistachio USB PHY driver * * Copyright (C) 2015 Google, Inc. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. */ #include <linux/clk.h> #include <linux/delay.h> #include <linux/io.h> #include <linux/kernel.h> #include <linux/mfd/syscon.h> #include <linux/module.h> #include <linux/of.h> #include <linux/phy/phy.h> #include <linux/platform_device.h> #include <linux/regmap.h> #include <dt-bindings/phy/phy-pistachio-usb.h> #define USB_PHY_CONTROL0 0x00 #define USB_PHY_CONTROL0_OTG_DRVVBUS_SHIFT 11 #define USB_PHY_CONTROL0_OTG_DRVVBUS_MASK 1 #define USB_PHY_CONTROL1 0x04 #define USB_PHY_CONTROL1_FSEL_SHIFT 2 #define USB_PHY_CONTROL1_FSEL_MASK 0x7 #define USB_PHY_STRAP_CONTROL 0x10 #define USB_PHY_STRAP_CONTROL_REFCLK_SHIFT 4 #define USB_PHY_STRAP_CONTROL_REFCLK_MASK 0x3 #define USB_PHY_STATUS 0x14 #define USB_PHY_STATUS_RX_PHY_CLK BIT(9) #define USB_PHY_STATUS_RX_UTMI_CLK BIT(8) #define USB_PHY_STATUS_VBUS_FAULT BIT(7) struct pistachio_usb_phy { struct device *dev; struct regmap *cr_top; struct clk *phy_clk; bool vbus_drive; unsigned int refclk; }; static const unsigned long fsel_rate_map[] = { 9600000, 10000000, 12000000, 19200000, 20000000, 24000000, 0, 50000000, }; static int pistachio_usb_phy_power_on(struct phy *phy) { struct pistachio_usb_phy *p_phy = phy_get_drvdata(phy); unsigned long timeout, rate; unsigned int i; int ret; ret = clk_prepare_enable(p_phy->phy_clk); if (ret < 0) { dev_err(p_phy->dev, "Failed to enable PHY clock: %d\n", ret); return ret; } regmap_update_bits(p_phy->cr_top, USB_PHY_STRAP_CONTROL, USB_PHY_STRAP_CONTROL_REFCLK_MASK << USB_PHY_STRAP_CONTROL_REFCLK_SHIFT, p_phy->refclk << USB_PHY_STRAP_CONTROL_REFCLK_SHIFT); if (p_phy->vbus_drive) { /* allow USB block to control VBUS */ regmap_update_bits(p_phy->cr_top, USB_PHY_CONTROL0, USB_PHY_CONTROL0_OTG_DRVVBUS_MASK << USB_PHY_CONTROL0_OTG_DRVVBUS_SHIFT, 1 << USB_PHY_CONTROL0_OTG_DRVVBUS_SHIFT); } rate = clk_get_rate(p_phy->phy_clk); if (p_phy->refclk == REFCLK_XO_CRYSTAL && rate != 12000000) { dev_err(p_phy->dev, "Unsupported rate for XO crystal: %ld\n", rate); ret = -EINVAL; goto disable_clk; } for (i = 0; i < ARRAY_SIZE(fsel_rate_map); i++) { if (rate == fsel_rate_map[i]) break; } if (i == ARRAY_SIZE(fsel_rate_map)) { dev_err(p_phy->dev, "Unsupported clock rate: %lu\n", rate); ret = -EINVAL; goto disable_clk; } regmap_update_bits(p_phy->cr_top, USB_PHY_CONTROL1, USB_PHY_CONTROL1_FSEL_MASK << USB_PHY_CONTROL1_FSEL_SHIFT, i << USB_PHY_CONTROL1_FSEL_SHIFT); timeout = jiffies + msecs_to_jiffies(200); while (time_before(jiffies, timeout)) { unsigned int val; regmap_read(p_phy->cr_top, USB_PHY_STATUS, &val); if (val & USB_PHY_STATUS_VBUS_FAULT) { dev_err(p_phy->dev, "VBUS fault detected\n"); ret = -EIO; goto disable_clk; } if ((val & USB_PHY_STATUS_RX_PHY_CLK) && (val & USB_PHY_STATUS_RX_UTMI_CLK)) return 0; usleep_range(1000, 1500); } dev_err(p_phy->dev, "Timed out waiting for PHY to power on\n"); ret = -ETIMEDOUT; disable_clk: clk_disable_unprepare(p_phy->phy_clk); return ret; } static int pistachio_usb_phy_power_off(struct phy *phy) { struct pistachio_usb_phy *p_phy = phy_get_drvdata(phy); clk_disable_unprepare(p_phy->phy_clk); return 0; } static const struct phy_ops pistachio_usb_phy_ops = { .power_on = pistachio_usb_phy_power_on, .power_off = pistachio_usb_phy_power_off, .owner = THIS_MODULE, }; static int pistachio_usb_phy_probe(struct platform_device *pdev) { struct pistachio_usb_phy *p_phy; struct phy_provider *provider; struct phy *phy; int ret; p_phy = devm_kzalloc(&pdev->dev, sizeof(*p_phy), GFP_KERNEL); if (!p_phy) return -ENOMEM; p_phy->dev = &pdev->dev; platform_set_drvdata(pdev, p_phy); p_phy->cr_top = syscon_regmap_lookup_by_phandle(p_phy->dev->of_node, "img,cr-top"); if (IS_ERR(p_phy->cr_top)) { dev_err(p_phy->dev, "Failed to get CR_TOP registers: %ld\n", PTR_ERR(p_phy->cr_top)); return PTR_ERR(p_phy->cr_top); } p_phy->phy_clk = devm_clk_get(p_phy->dev, "usb_phy"); if (IS_ERR(p_phy->phy_clk)) { dev_err(p_phy->dev, "Failed to get usb_phy clock: %ld\n", PTR_ERR(p_phy->phy_clk)); return PTR_ERR(p_phy->phy_clk); } ret = of_property_read_u32(p_phy->dev->of_node, "img,refclk", &p_phy->refclk); if (ret < 0) { dev_err(p_phy->dev, "No reference clock selector specified\n"); return ret; } p_phy->vbus_drive = of_property_read_bool(p_phy->dev->of_node, "enable-vbus-drive"); phy = devm_phy_create(p_phy->dev, NULL, &pistachio_usb_phy_ops); if (IS_ERR(phy)) { dev_err(p_phy->dev, "Failed to create PHY: %ld\n", PTR_ERR(phy)); return PTR_ERR(phy); } phy_set_drvdata(phy, p_phy); provider = devm_of_phy_provider_register(p_phy->dev, of_phy_simple_xlate); if (IS_ERR(provider)) { dev_err(p_phy->dev, "Failed to register PHY provider: %ld\n", PTR_ERR(provider)); return PTR_ERR(provider); } return 0; } static const struct of_device_id pistachio_usb_phy_of_match[] = { { .compatible = "img,pistachio-usb-phy", }, { }, }; MODULE_DEVICE_TABLE(of, pistachio_usb_phy_of_match); static struct platform_driver pistachio_usb_phy_driver = { .probe = pistachio_usb_phy_probe, .driver = { .name = "pistachio-usb-phy", .of_match_table = pistachio_usb_phy_of_match, }, }; module_platform_driver(pistachio_usb_phy_driver); MODULE_AUTHOR("Andrew Bresticker <abrestic@chromium.org>"); MODULE_DESCRIPTION("IMG Pistachio USB2.0 PHY driver"); MODULE_LICENSE("GPL v2");
Java
<?php /** * @package Joomla.Administrator * @subpackage com_supperadmin * * @copyright Copyright (C) 2005 - 2014 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ defined('_JEXEC') or die; $supperAdmin = JFactory::isSupperAdmin(); // Include the component HTML helpers. JHtml::addIncludePath(JPATH_COMPONENT . '/helpers/html'); JHtml::_('bootstrap.tooltip'); JHtml::_('behavior.multiselect'); JHtml::_('formbehavior.chosen', 'select'); $user = JFactory::getUser(); $listOrder = $this->escape($this->state->get('list.ordering')); $listDirn = $this->escape($this->state->get('list.direction')); $canOrder = $user->authorise('core.edit.state', 'com_supperadmin'); $saveOrder = $listOrder == 'ordering'; if ($saveOrder) { $saveOrderingUrl = 'index.php?option=com_supperadmin&task=modules.saveOrderAjax&tmpl=component'; JHtml::_('sortablelist.sortable', 'articleList', 'adminForm', strtolower($listDirn), $saveOrderingUrl); } $sortFields = $this->getSortFields(); ?> <script type="text/javascript"> Joomla.orderTable = function () { table = document.getElementById("sortTable"); direction = document.getElementById("directionTable"); order = table.options[table.selectedIndex].value; if (order != '<?php echo $listOrder; ?>') { dirn = 'asc'; } else { dirn = direction.options[direction.selectedIndex].value; } Joomla.tableOrdering(order, dirn, ''); } </script> <div class="view-modules-default"> <?php echo $this->render_toolbar() ?> <form action="<?php echo JRoute::_('index.php?option=com_supperadmin&view=modules'); ?>" method="post" name="adminForm" id="adminForm"> <div id="main-container"> <div class="row"> <div class="col-md-12"> <div class="row"> <div class="col-md-12"> <?php echo JLayoutHelper::render('joomla.searchtools.default', array('view' => $this)); ?> </div> </div> <div class="row"> <div class="col-md-12"> <table class="table table-striped" id="itemList"> <thead> <tr> <th width="1%" class="nowrap center hidden-phone"> <?php echo JHtml::_('grid.sort', '<i class="icon-menu-2"></i>', 'ordering', $listDirn, $listOrder, null, 'asc', 'JGRID_HEADING_ORDERING'); ?> </th> <th width="1%" class="hidden-phone"> <?php echo JHtml::_('grid.checkall'); ?> </th> <th width="1%" class="nowrap center"> <?php echo JHtml::_('grid.sort', 'JSTATUS', 'enabled', $listDirn, $listOrder); ?> </th> <th class="title"> <?php echo JHtml::_('grid.sort', 'module title', 'name', $listDirn, $listOrder); ?> </th> <th class="title"> <?php echo JHtml::_('grid.sort', 'module name', 'name', $listDirn, $listOrder); ?> </th> <th class="title"> <?php echo JHtml::_('grid.sort', 'website', 'a.website_name', $listDirn, $listOrder); ?> </th> <th class="title"> <?php echo JHtml::_('grid.sort', 'Is System', 'a.issystem', $listDirn, $listOrder); ?> </th> <th width="5%" class="hidden-phone"> <?php echo JHtml::_('grid.sort', 'JGRID_HEADING_ACCESS', 'access', $listDirn, $listOrder); ?> </th> <th width="1%" class="nowrap center hidden-phone"> <?php echo JHtml::_('grid.sort', 'JGRID_HEADING_ID', 'id', $listDirn, $listOrder); ?> </th> </tr> </thead> <tfoot> <tr> <td colspan="12"> <?php echo $this->pagination->getListFooter(); ?> </td> </tr> </tfoot> <tbody> <?php foreach ($this->items as $i => $item) : $ordering = ($listOrder == 'ordering'); $canEdit = $user->authorise('core.edit', 'com_supperadmin'); $canCheckin = $user->authorise('core.manage', 'com_checkin') || $item->checked_out == $user->get('id') || $item->checked_out == 0; $canChange = $user->authorise('core.edit.state', 'com_supperadmin') && $canCheckin; ?> <tr class="row<?php echo $i % 2; ?>" item-id="<?php echo $item->id ?>" sortable-group-id="<?php echo $item->folder ?>"> <td class="order nowrap center hidden-phone"> <?php $iconClass = ''; if (!$canChange) { $iconClass = ' inactive'; } elseif (!$saveOrder) { $iconClass = ' inactive tip-top hasTooltip" title="' . JHtml::tooltipText('JORDERINGDISABLED'); } ?> <span class="sortable-handler<?php echo $iconClass ?>"> <i class="icon-menu"></i> </span> <?php if ($canChange && $saveOrder) : ?> <input type="text" style="display:none" name="order[]" size="5" value="<?php echo $item->ordering; ?>" class="width-20 text-area-order "/> <?php endif; ?> </td> <td class="center hidden-phone"> <?php echo JHtml::_('grid.id', $i, $item->id); ?> </td> <td class="center"> <?php echo JHtml::_('jgrid.published', $item->enabled, $i, 'modules.', $canChange); ?> </td> <td> <?php if ($item->checked_out) : ?> <?php echo JHtml::_('jgrid.checkedout', $i, $item->editor, $item->checked_out_time, 'supperadmin.', $canCheckin); ?> <?php endif; ?> <?php if ($canEdit) : ?> <a class="quick-edit-title" href="<?php echo JRoute::_('index.php?option=com_supperadmin&task=module.edit&id=' . (int)$item->id); ?>"> <?php echo $item->title; ?></a> <?php else : ?> <?php echo $item->title; ?> <?php endif; ?> </td> <td> <?php if ($item->checked_out) : ?> <?php echo JHtml::_('jgrid.checkedout', $i, $item->editor, $item->checked_out_time, 'supperadmin.', $canCheckin); ?> <?php endif; ?> <?php if ($canEdit) : ?> <a class="quick-edit-title" href="<?php echo JRoute::_('index.php?option=com_supperadmin&task=module.edit&id=' . (int)$item->id); ?>"> <?php echo $item->module; ?></a> <?php else : ?> <?php echo $item->module; ?> <?php endif; ?> </td> <td class="center hidden-phone"> <?php echo $item->website_name ?> </td> <td class="center"> <?php echo JHtml::_('jgrid.is_system', $item->issystem, $i, 'modules.', $canChange); ?> </td> <td class="small hidden-phone"> <?php echo $this->escape($item->access_level); ?> </td> <td class="center hidden-phone"> <?php echo (int)$item->id; ?> </td> </tr> <?php endforeach; ?> </tbody> </table> </div> </div> </div> </div> <div class="clearfix"></div> <input type="hidden" name="task" value=""/> <input type="hidden" name="boxchecked" value="0"/> <input type="hidden" name="filter_order" value="<?php echo $listOrder; ?>"/> <input type="hidden" name="filter_order_Dir" value="<?php echo $listDirn; ?>"/> <?php echo JHtml::_('form.token'); ?> </div> </form> </div> <?php // Search tools bar echo JLayoutHelper::render('joomla.contextmenu.contextmenu', array('view' => $this), null, array('debug' => false)); ?>
Java
/* Copyright (c) 2010, 2015, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2.0, as published by the Free Software Foundation. This program is also distributed with certain software (including but not limited to OpenSSL) that is licensed under separate terms, as designated in a particular file or component or in included license documentation. The authors of MySQL hereby grant you an additional permission to link the program and your derivative works with the separately licensed software that they have included with MySQL. 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, version 2.0, 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-1335 USA */ /** @file storage/perfschema/pfs_setup_object.cc Performance schema setup object (implementation). */ #include "my_global.h" #include "my_sys.h" #include "my_base.h" #include "sql_string.h" #include "pfs.h" #include "pfs_stat.h" #include "pfs_instr.h" #include "pfs_setup_object.h" #include "pfs_global.h" /** @addtogroup Performance_schema_buffers @{ */ uint setup_objects_version= 0; ulong setup_object_max; PFS_setup_object *setup_object_array= NULL; LF_HASH setup_object_hash; static bool setup_object_hash_inited= false; /** Initialize the setup object buffers. @param param sizing parameters @return 0 on success */ int init_setup_object(const PFS_global_param *param) { setup_object_max= param->m_setup_object_sizing; setup_object_array= NULL; if (setup_object_max > 0) { setup_object_array= PFS_MALLOC_ARRAY(setup_object_max, sizeof(PFS_setup_object), PFS_setup_object, MYF(MY_ZEROFILL)); if (unlikely(setup_object_array == NULL)) return 1; } return 0; } /** Cleanup all the setup object buffers. */ void cleanup_setup_object(void) { pfs_free(setup_object_array); setup_object_array= NULL; setup_object_max= 0; } C_MODE_START static uchar *setup_object_hash_get_key(const uchar *entry, size_t *length, my_bool) { const PFS_setup_object * const *typed_entry; const PFS_setup_object *setup_object; const void *result; typed_entry= reinterpret_cast<const PFS_setup_object* const *> (entry); DBUG_ASSERT(typed_entry != NULL); setup_object= *typed_entry; DBUG_ASSERT(setup_object != NULL); *length= setup_object->m_key.m_key_length; result= setup_object->m_key.m_hash_key; return const_cast<uchar*> (reinterpret_cast<const uchar*> (result)); } C_MODE_END /** Initialize the setup objects hash. @return 0 on success */ int init_setup_object_hash(void) { if ((! setup_object_hash_inited) && (setup_object_max > 0)) { lf_hash_init(&setup_object_hash, sizeof(PFS_setup_object*), LF_HASH_UNIQUE, 0, 0, setup_object_hash_get_key, &my_charset_bin); /* setup_object_hash.size= setup_object_max; */ setup_object_hash_inited= true; } return 0; } /** Cleanup the setup objects hash. */ void cleanup_setup_object_hash(void) { if (setup_object_hash_inited) { setup_object_hash_inited= false; lf_hash_destroy(&setup_object_hash); } } static LF_PINS* get_setup_object_hash_pins(PFS_thread *thread) { if (unlikely(thread->m_setup_object_hash_pins == NULL)) { if (! setup_object_hash_inited) return NULL; thread->m_setup_object_hash_pins= lf_hash_get_pins(&setup_object_hash); } return thread->m_setup_object_hash_pins; } static void set_setup_object_key(PFS_setup_object_key *key, enum_object_type object_type, const char *schema, uint schema_length, const char *object, uint object_length) { DBUG_ASSERT(schema_length <= NAME_LEN); DBUG_ASSERT(object_length <= NAME_LEN); char *ptr= &key->m_hash_key[0]; ptr[0]= (char) object_type; ptr++; if (schema_length) { memcpy(ptr, schema, schema_length); ptr+= schema_length; } ptr[0]= 0; ptr++; if (object_length) { memcpy(ptr, object, object_length); ptr+= object_length; } ptr[0]= 0; ptr++; key->m_key_length= (uint)(ptr - &key->m_hash_key[0]); } int insert_setup_object(enum_object_type object_type, const String *schema, const String *object, bool enabled, bool timed) { if (setup_object_max == 0) return HA_ERR_RECORD_FILE_FULL; PFS_thread *thread= PFS_thread::get_current_thread(); if (unlikely(thread == NULL)) return HA_ERR_OUT_OF_MEM; LF_PINS* pins= get_setup_object_hash_pins(thread); if (unlikely(pins == NULL)) return HA_ERR_OUT_OF_MEM; static uint PFS_ALIGNED setup_object_monotonic_index= 0; uint index; uint attempts= 0; PFS_setup_object *pfs; while (++attempts <= setup_object_max) { /* See create_mutex() */ index= PFS_atomic::add_u32(& setup_object_monotonic_index, 1) % setup_object_max; pfs= setup_object_array + index; if (pfs->m_lock.is_free()) { if (pfs->m_lock.free_to_dirty()) { set_setup_object_key(&pfs->m_key, object_type, schema->ptr(), schema->length(), object->ptr(), object->length()); pfs->m_schema_name= &pfs->m_key.m_hash_key[1]; pfs->m_schema_name_length= schema->length(); pfs->m_object_name= pfs->m_schema_name + pfs->m_schema_name_length + 1; pfs->m_object_name_length= object->length(); pfs->m_enabled= enabled; pfs->m_timed= timed; int res; res= lf_hash_insert(&setup_object_hash, pins, &pfs); if (likely(res == 0)) { pfs->m_lock.dirty_to_allocated(); setup_objects_version++; return 0; } pfs->m_lock.dirty_to_free(); if (res > 0) return HA_ERR_FOUND_DUPP_KEY; /* OOM in lf_hash_insert */ return HA_ERR_OUT_OF_MEM; } } } return HA_ERR_RECORD_FILE_FULL; } int delete_setup_object(enum_object_type object_type, const String *schema, const String *object) { PFS_thread *thread= PFS_thread::get_current_thread(); if (unlikely(thread == NULL)) return HA_ERR_OUT_OF_MEM; LF_PINS* pins= get_setup_object_hash_pins(thread); if (unlikely(pins == NULL)) return HA_ERR_OUT_OF_MEM; PFS_setup_object_key key; set_setup_object_key(&key, object_type, schema->ptr(), schema->length(), object->ptr(), object->length()); PFS_setup_object **entry; entry= reinterpret_cast<PFS_setup_object**> (lf_hash_search(&setup_object_hash, pins, key.m_hash_key, key.m_key_length)); if (entry && (entry != MY_ERRPTR)) { PFS_setup_object *pfs= *entry; lf_hash_delete(&setup_object_hash, pins, key.m_hash_key, key.m_key_length); pfs->m_lock.allocated_to_free(); } lf_hash_search_unpin(pins); setup_objects_version++; return 0; } int reset_setup_object() { PFS_thread *thread= PFS_thread::get_current_thread(); if (unlikely(thread == NULL)) return HA_ERR_OUT_OF_MEM; LF_PINS* pins= get_setup_object_hash_pins(thread); if (unlikely(pins == NULL)) return HA_ERR_OUT_OF_MEM; PFS_setup_object *pfs= setup_object_array; PFS_setup_object *pfs_last= setup_object_array + setup_object_max; for ( ; pfs < pfs_last; pfs++) { if (pfs->m_lock.is_populated()) { lf_hash_delete(&setup_object_hash, pins, pfs->m_key.m_hash_key, pfs->m_key.m_key_length); pfs->m_lock.allocated_to_free(); } } setup_objects_version++; return 0; } long setup_object_count() { return setup_object_hash.count; } void lookup_setup_object(PFS_thread *thread, enum_object_type object_type, const char *schema_name, int schema_name_length, const char *object_name, int object_name_length, bool *enabled, bool *timed) { PFS_setup_object_key key; PFS_setup_object **entry; PFS_setup_object *pfs; int i; /* The table io instrumentation uses "TABLE" and "TEMPORARY TABLE". SETUP_OBJECT uses "TABLE" for both concepts. There is no way to provide a different setup for: - TABLE foo.bar - TEMPORARY TABLE foo.bar */ DBUG_ASSERT(object_type != OBJECT_TYPE_TEMPORARY_TABLE); LF_PINS* pins= get_setup_object_hash_pins(thread); if (unlikely(pins == NULL)) { *enabled= false; *timed= false; return; } for (i= 1; i<=3; i++) { switch(i) { case 1: /* Lookup OBJECT_TYPE + OBJECT_SCHEMA + OBJECT_NAME in SETUP_OBJECTS */ set_setup_object_key(&key, object_type, schema_name, schema_name_length, object_name, object_name_length); break; case 2: /* Lookup OBJECT_TYPE + OBJECT_SCHEMA + "%" in SETUP_OBJECTS */ set_setup_object_key(&key, object_type, schema_name, schema_name_length, "%", 1); break; case 3: /* Lookup OBJECT_TYPE + "%" + "%" in SETUP_OBJECTS */ set_setup_object_key(&key, object_type, "%", 1, "%", 1); break; } entry= reinterpret_cast<PFS_setup_object**> (lf_hash_search(&setup_object_hash, pins, key.m_hash_key, key.m_key_length)); if (entry && (entry != MY_ERRPTR)) { pfs= *entry; *enabled= pfs->m_enabled; *timed= pfs->m_timed; lf_hash_search_unpin(pins); return; } lf_hash_search_unpin(pins); } *enabled= false; *timed= false; return; } /** @} */
Java
<?php /** Neapolitan (Nnapulitano) * * See MessagesQqq.php for message documentation incl. usage of parameters * To improve a translation please visit http://translatewiki.net * * @ingroup Language * @file * * @author Carmine Colacino * @author Cryptex * @author E. abu Filumena * @author SabineCretella * @author לערי ריינהארט */ $fallback = 'it'; $namespaceNames = array( NS_MEDIA => 'Media', NS_SPECIAL => 'Speciàle', NS_TALK => 'Chiàcchiera', NS_USER => 'Utente', NS_USER_TALK => 'Utente_chiàcchiera', NS_PROJECT_TALK => '$1_chiàcchiera', NS_FILE => 'Fiùra', NS_FILE_TALK => 'Fiùra_chiàcchiera', NS_MEDIAWIKI => 'MediaWiki', NS_MEDIAWIKI_TALK => 'MediaWiki_chiàcchiera', NS_TEMPLATE => 'Modello', NS_TEMPLATE_TALK => 'Modello_chiàcchiera', NS_HELP => 'Ajùto', NS_HELP_TALK => 'Ajùto_chiàcchiera', NS_CATEGORY => 'Categurìa', NS_CATEGORY_TALK => 'Categurìa_chiàcchiera', ); $namespaceAliases = array( 'Speciale' => NS_SPECIAL, 'Discussione' => NS_TALK, 'Utente' => NS_USER, 'Discussioni_utente' => NS_USER_TALK, 'Discussioni_$1' => NS_PROJECT_TALK, 'Immagine' => NS_FILE, 'Discussioni_immagine' => NS_FILE_TALK, 'MediaWiki' => NS_MEDIAWIKI, 'Discussioni_MediaWiki' => NS_MEDIAWIKI_TALK, 'Discussioni_template' => NS_TEMPLATE_TALK, 'Aiuto' => NS_HELP, 'Discussioni_aiuto' => NS_HELP_TALK, 'Categoria' => NS_CATEGORY, 'Discussioni_categoria' => NS_CATEGORY_TALK, ); $messages = array( # User preference toggles 'tog-underline' => "Sottolinia 'e jonte:", 'tog-highlightbroken' => 'Formatta \'e jonte defettose <a href="" class="new">accussì</a> (oppure: accussì<a href="" class="internal">?</a>).', 'tog-justify' => "Alliniamento d''e paracrafe mpare", 'tog-hideminor' => "Annascunne 'e cagne piccirille 'int'a ll'úrdeme cagne", 'tog-extendwatchlist' => "Spanne ll'asservate speciale pe fà vedé tutte 'e cagne possíbbele", 'tog-usenewrc' => 'Urdeme cagne avanzate (JavaScript)', 'tog-numberheadings' => "Annúmmera automatecamente 'e títule", 'tog-showtoolbar' => "Aspone 'a barra d''e stromiente 'e cagno (JavaScript)", 'tog-editondblclick' => "Cagna 'e pàggene cliccanno ddoje vote (JavaScript)", 'tog-editsection' => "Permette 'e cagnà 'e sezzione cu a jonta [cagna]", 'tog-editsectiononrightclick' => "Permette 'e cangne 'e sezzione cliccanno p''o tasto destro ncopp 'e titule 'e sezzione (JavaScript)", 'tog-showtoc' => "Mosta ll'innece pe 'e paggene cu cchiù 'e 3 sezzione", 'tog-rememberpassword' => "Ricurda 'a registrazzione pe' cchiu sessione", 'tog-editwidth' => "Larghezza massima d''a casella pe scrivere", 'underline-always' => 'Sèmpe', 'underline-never' => 'Màje', # Dates 'sunday' => 'dumméneca', 'monday' => 'lunnerì', 'tuesday' => 'marterì', 'wednesday' => 'miercurì', 'thursday' => 'gioverì', 'friday' => 'viernarì', 'saturday' => 'sàbbato', 'sun' => 'dum', 'mon' => 'lun', 'tue' => 'mar', 'wed' => 'mier', 'thu' => 'gio', 'fri' => 'ven', 'sat' => 'sab', 'january' => 'jennaro', 'february' => 'frevàro', 'march' => 'màrzo', 'april' => 'abbrile', 'may_long' => 'màjo', 'june' => 'giùgno', 'july' => 'luglio', 'august' => 'aústo', 'september' => 'settembre', 'october' => 'ottobbre', 'november' => 'nuvembre', 'december' => 'dicèmbre', 'january-gen' => 'jennaro', 'february-gen' => 'frevaro', 'march-gen' => 'màrzo', 'april-gen' => 'abbrile', 'may-gen' => 'maggio', 'june-gen' => 'giùgno', 'july-gen' => 'luglio', 'august-gen' => 'aùsto', 'september-gen' => 'settembre', 'october-gen' => 'ottovre', 'november-gen' => 'nuvembre', 'december-gen' => 'dicembre', 'jan' => 'jen', 'feb' => 'fre', 'mar' => 'mar', 'apr' => 'abb', 'may' => 'maj', 'jun' => 'giu', 'jul' => 'lug', 'aug' => 'aus', 'sep' => 'set', 'oct' => 'ott', 'nov' => 'nuv', 'dec' => 'dic', # Categories related messages 'category_header' => 'Paggene rìnt\'a categurìa "$1"', 'subcategories' => 'Categurìe secunnarie', 'about' => 'Nfromma', 'article' => 'Articulo', 'newwindow' => "(s'arape n'ata fenèsta)", 'cancel' => 'Scancèlla', 'mypage' => "'A paggena mia", 'mytalk' => "'E mmie chiacchieriàte", 'anontalk' => 'Chiacchierate pe chisto IP', # Cologne Blue skin 'qbfind' => 'Truòva', 'qbedit' => 'Càgna', 'qbpageoptions' => 'Chesta paggena', 'qbpageinfo' => "Nfrummazzione ncopp'â paggena", 'qbmyoptions' => "'E ppaggene mie", 'qbspecialpages' => 'Pàggene speciàle', 'errorpagetitle' => 'Sbaglio', 'returnto' => 'Torna a $1.', 'help' => 'Ajùto', 'search' => 'Truova', 'searchbutton' => 'Truova', 'go' => 'Vàje', 'history' => "Verziune 'e primma", 'history_short' => 'Cronologgia', 'info_short' => 'Nfurmazzione', 'printableversion' => "Verzione pe' stampa", 'permalink' => 'Jonta permanente', 'edit' => 'Càgna', 'editthispage' => 'Càgna chesta paggena', 'delete' => 'Scancèlla', 'deletethispage' => 'Scancèlla chésta paggena', 'protect' => 'Ferma', 'protectthispage' => 'Ferma chesta paggena', 'unprotect' => 'Sferma', 'unprotectthispage' => 'Sferma chesta paggena', 'newpage' => 'Paggena nòva', 'talkpage' => "Paggena 'e chiàcchiera", 'talkpagelinktext' => 'Chiàcchiera', 'specialpage' => 'Paggena speciàle', 'talk' => 'Chiàcchiera', 'toolbox' => 'Strumiente', 'imagepage' => 'Paggena fiùra', 'otherlanguages' => 'Ate léngue', 'redirectedfrom' => "(Redirect 'a $1)", 'lastmodifiedat' => "Urdema cagnamiénto pe' a paggena: $2, $1.", 'viewcount' => 'Chesta paggena è stata lètta {{PLURAL:$1|una vòta|$1 vòte}}.', 'jumpto' => 'Vaje a:', 'jumptonavigation' => 'navigazione', 'jumptosearch' => 'truova', # All link text and link target definitions of links into project namespace that get used by other message strings, with the exception of user group pages (see grouppage) and the disambiguation template definition (see disambiguations). 'aboutsite' => "'Nfrummazione ncòpp'a {{SITENAME}}", 'aboutpage' => "Project:'Nfrummazione", 'disclaimers' => 'Avvertimiènte', 'disclaimerpage' => 'Project:Avvertimiènte generale', 'edithelp' => 'Guida', 'helppage' => 'Help:Ajùto', 'mainpage' => 'Paggena prencepale', 'mainpage-description' => 'Paggena prencepale', 'portal' => "Porta d''a cummunetà", 'portal-url' => "Project:Porta d''a cummunetà", 'badaccess' => "Nun haje 'e premmesse abbastante.", 'newmessageslink' => "nuove 'mmasciàte", 'newmessagesdifflink' => "differenze cu 'a revisione precedente", 'youhavenewmessagesmulti' => 'Tiene nuove mmasciate $1', 'editsection' => 'càgna', 'editold' => 'càgna', 'toc' => 'Énnece', 'showtoc' => 'faje vedé', 'hidetoc' => 'annascunne', 'viewdeleted' => 'Vire $1?', # Short words for each namespace, by default used in the namespace tab in monobook 'nstab-main' => 'Articulo', 'nstab-user' => 'Paggena utente', 'nstab-project' => "Paggena 'e servizio", 'nstab-image' => 'Fiura', 'nstab-mediawiki' => "'Mmasciata", 'nstab-help' => 'Ajùto', 'nstab-category' => 'Categurìa', # General errors 'filedeleteerror' => 'Nun se pô scancellà \'o file "$1"', 'cannotdelete' => "Nun è possibbele scassà 'a paggena o 'a fiura addamannata. (Putria éssere stato già scancellato.)", 'badtitle' => "'O nnomme nun è jùsto", # Login and logout pages 'logouttext' => "'''Site asciùte.''' Putite cuntinuà a ausà {{SITENAME}} comme n'utente senza nomme, o si nò putite trasì n'ata vota, cu 'o stesso nomme o cu n'ato nomme.", 'welcomecreation' => "== Bemmenuto, $1! == 'O cunto è stato criato currettamente. Nun scurdà 'e perzonalizzà 'e ppreferenze 'e {{SITENAME}}.", 'remembermypassword' => 'Allicuordate d"a password', 'yourdomainname' => "Spiecà 'o dumminio", 'login' => 'Tràse', 'userlogin' => "Tràse o cria n'acciesso nuovo", 'logout' => 'Jèsce', 'userlogout' => 'Jèsce', 'notloggedin' => 'Acciesso nun affettuato', 'nologin' => "Nun haje ancora n'acciesso? '''$1'''.", 'nologinlink' => 'Crialo mmo', 'createaccount' => 'Cria nu cunto nuovo', 'gotaccount' => "Tiene già nu cunto? '''$1'''.", 'gotaccountlink' => 'Tràse', 'loginerror' => "Probblema 'e accièsso", 'loginsuccesstitle' => 'Acciesso affettuato', 'nosuchusershort' => 'Nun ce stanno utente cu o nòmme "<nowiki>$1</nowiki>". Cuntrolla si scrivìste buòno.', 'nouserspecified' => "Tiene 'a dìcere nu nomme pricìso.", 'acct_creation_throttle_hit' => 'Ce dispiace, haje già criato $1 utente. Nun ne pô crià ate.', 'accountcreated' => 'Cunto criato', 'loginlanguagelabel' => 'Lengua: $1', # Edit page toolbar 'image_sample' => 'Essempio.jpg', 'image_tip' => 'Fiura ncuorporata', # Edit pages 'minoredit' => 'Chisto è nu cagnamiénto piccerillo', 'watchthis' => "Tiene d'uocchio chesta paggena", 'savearticle' => "Sarva 'a paggena", 'preview' => 'Anteprimma', 'showpreview' => 'Vere anteprimma', 'showdiff' => "Fa veré 'e cagnamiente", 'blockededitsource' => "Ccà sotto venono mmustate 'e '''cagnamiente fatte''' â paggena '''$1''':", 'loginreqtitle' => "Pe' cagnà chesta paggena abbesognate aseguì ll'acciesso ô sito.", 'loginreqlink' => "aseguì ll'acciesso", 'loginreqpagetext' => "Pe' veré ate ppaggene abbesognate $1.", 'accmailtitle' => "'O password è stato mannato.", 'accmailtext' => '\'A password pe ll\'utente "$1" fuje mannata ô nnerizzo $2.', 'previewnote' => "'''Chesta è sola n'anteprimma; 'e cagnamiénte â paggena NUN songo ancora sarvate!'''", 'editing' => "Cagnamiento 'e $1", 'templatesused' => "Template ausate 'a chesta paggena:", # "Undo" feature 'undo-summary' => "Canciella 'o cagnamiento $1 'e [[Special:Contributions/$2|$2]] ([[User talk:$2|Chiàcchiera]])", # History pages 'currentrev' => "Verzione 'e mmo", # Revision deletion 'rev-delundel' => 'faje vedé/annascunne', # Search results 'searchresults' => "Risultato d''a recerca", 'searchresulttext' => "Pe sapé de cchiù ncopp'â comme ascia 'a {{SITENAME}}, vere [[{{MediaWiki:Helppage}}|Ricerca in {{SITENAME}}]].", 'notitlematches' => "Voce addemannata nun truvata dint' 'e titule 'e articulo", 'notextmatches' => "Voce addemannata nun truvata dint' 'e teste 'e articulo", 'searchhelp-url' => 'Help:Ajùto', 'powersearch' => 'Truova', # Preferences page 'mypreferences' => "Preferenze d''e mie", 'changepassword' => 'Cagna password', 'prefs-rc' => 'Urdeme nove', 'prefs-watchlist' => 'Asservate speciale', 'columns' => 'Culonne:', 'timezoneregion-africa' => 'Afreca', 'username' => 'Nomme utente', 'yourlanguage' => 'Lengua:', # User rights log 'rightsnone' => '(nisciuno)', # Recent changes 'recentchanges' => 'Urdeme nove', 'recentchangestext' => "Ncoppa chesta paggena song' appresentate ll'urdeme cagnamiente fatto ê cuntenute d\"o sito.", 'rcnote' => "Ccà sotto nce songo ll'urdeme {{PLURAL:$1|cangiamiento|'''$1''' cangiamiente}} 'e ll'urdeme {{PLURAL:$2|juorno|'''$2''' juorne}}, agghiuornate a $3.", 'rclistfrom' => "Faje vedé 'e cagnamiénte fatte a partì 'a $1", 'rcshowhideminor' => "$1 'e cagnamiénte piccerille", 'rcshowhidebots' => "$1 'e bot", 'rcshowhideliu' => "$1 ll'utente reggìstrate", 'rcshowhideanons' => "$1 ll'utente anonime", 'rcshowhidemine' => "$1 'e ffatiche mmee", 'rclinks' => "Faje vedé ll'urdeme $1 cagnamiente dint' ll'urdeme $2 juorne<br />$3", 'hide' => 'annascunne', 'show' => 'faje vedé', 'rc_categories_any' => 'Qualònca', # Recent changes linked 'recentchangeslinked' => 'Cagnamiénte cullegate', 'recentchangeslinked-feed' => 'Cagnamiénte cullegate', 'recentchangeslinked-toolbox' => 'Cagnamiénte cullegate', # Upload 'upload' => 'Careca file', 'uploadedimage' => 'ha carecato "[[$1]]"', # Special:ListFiles 'listfiles_name' => 'Nomme', # File description page 'file-anchor-link' => 'Fiura', 'filehist-user' => 'Utente', 'imagelinks' => 'Jonte ê ffiure', # Random page 'randompage' => 'Na paggena qualsiase', 'randompage-nopages' => 'Nessuna pagina nel namespace selezionato.', 'disambiguations' => "Paggene 'e disambigua", 'doubleredirects' => 'Redirect duppie', # Miscellaneous special pages 'nbytes' => '$1 {{PLURAL:$1|byte|byte}}', 'ncategories' => '$1 {{PLURAL:$1|categoria|categorie}}', 'nlinks' => '$1 {{PLURAL:$1|cullegamiento|cullegamiente}}', 'popularpages' => "Paggene cchiù 'speziunate", 'wantedpages' => 'Paggene cchiù addemannate', 'shortpages' => 'Paggene curte', 'longpages' => 'Paggene cchiú longhe', 'newpages' => 'Paggene cchiù frische', 'move' => 'Spusta', 'movethispage' => 'Spusta chesta paggena', # Special:AllPages 'allpages' => "Tutte 'e ppaggene", 'allarticles' => "Tutt' 'e vvoce", 'allinnamespace' => "Tutt' 'e ppaggene d''o namespace $1", # Special:Categories 'categories' => 'Categurìe', 'categoriespagetext' => "Lista cumpleta d\"e categurie presente ncopp' 'o sito.", # Special:LinkSearch 'linksearch-ok' => 'Truova', # Watchlist 'addedwatch' => 'Aggiunto ai Osservate Speciale tue', 'watch' => 'Secuta', 'notanarticle' => 'Chesta paggena nun è na voce', 'enotif_newpagetext' => 'Chesta è na paggena nòva.', 'changed' => 'cagnata', # Delete 'deletepage' => 'Scancella paggena', 'excontent' => "'o cuntenuto era: '$1'", 'excontentauthor' => "'o cuntenuto era: '$1' (e ll'unneco cuntribbutore era '[[Special:Contributions/$2|$2]]')", 'exbeforeblank' => "'O cuntenuto apprimm' 'a ll'arrevacamento era: '$1'", 'exblank' => "'a paggena era vacante", 'actioncomplete' => 'Azzione fernuta', 'deletedtext' => 'Qauccheruno ha scancellata \'a paggena "<nowiki>$1</nowiki>". Addumannà \'o $2 pe na lista d"e ppaggene scancellate urdemamente.', 'deletedarticle' => 'ha scancellato "[[$1]]"', 'dellogpage' => 'Scancellazione', 'deletionlog' => 'Log d"e scancellazione', 'deletecomment' => 'Raggióne', # Rollback 'rollback' => "Ausa na revizione 'e primma", 'revertpage' => "Cangiaje 'e cagnamiénte 'e [[Special:Contributions/$2|$2]] ([[User talk:$2|discussione]]), cu â verzione 'e pprimma 'e [[User:$1|$1]]", # Protect 'prot_1movedto2' => 'ha spustato [[$1]] a [[$2]]', 'protect-expiry-options' => '2 ore:2 hours,1 juorno:1 day,3 juorne:3 days,1 semmana:1 week,2 semmane:2 weeks,1 mise:1 month,3 mese:3 months,6 mese:6 months,1 anno:1 year,infinito:infinite', # Undelete 'viewdeletedpage' => "Vìre 'e ppàggine scancellate", # Namespace form on various pages 'invert' => "abbarruca 'a sceveta", # Contributions 'contributions' => 'Contribbute utente', 'mycontris' => 'Mie contribbute', 'sp-contributions-talk' => 'Chiàcchiera', # What links here 'whatlinkshere' => 'Paggene ca cullegano a chesta', 'whatlinkshere-title' => 'Paggene ca cullegano a $1', 'nolinkshere' => "Nisciuna paggena cuntene jonte ca mpuntano a '''[[:$1]]'''.", # Block/unblock 'blockip' => 'Ferma utelizzatóre', 'ipadressorusername' => 'Nnerizzo IP o nomme utente', 'ipboptions' => '2 ore:2 hours,1 juorno:1 day,3 juorne:3 days,1 semmana:1 week,2 semmane:2 weeks,1 mise:1 month,3 mese:3 months,6 mese:6 months,1 anno:1 year,infinito:infinite', 'blockipsuccesssub' => 'Blocco aseguito', 'blocklistline' => '$1, $2 ha fermato $3 ($4)', 'blocklink' => 'ferma', 'blocklogpage' => 'Blocche', 'blocklogentry' => 'ha fermato "[[$1]]" pe\' nu mumento \'e $2 $3', 'blocklogtext' => "Chesta è 'a lista d''e azzione 'e blocco e sblocco utente. 'E nnerizze IP bloccate automaticamente nun nce so'. Addumannà 'a [[Special:IPBlockList|lista IP bloccate]] pp' 'a lista d''e nnerizze e nomme utente 'o ca blocco nce sta.", # Move page 'movearticle' => "Spusta 'a paggena", 'newtitle' => 'Titulo nuovo:', 'movepagebtn' => "Spusta 'a paggena", 'articleexists' => "Na paggena cu chisto nomme asiste già, o pure 'o nomme scegliuto nun è buono. Scegliere n'ato titulo.", 'movedto' => 'spustata a', '1movedto2' => 'ha spustato [[$1]] a [[$2]]', '1movedto2_redir' => '[[$1]] spustata a [[$2]] trammeto redirect', 'movereason' => 'Raggióne', 'delete_and_move' => 'Scancèlla e spusta', 'delete_and_move_confirm' => "Sì, suprascrivi 'a paggena asistente", # Export 'export' => "Spurta 'e ppaggene", # Namespace 8 related 'allmessages' => "'Mmasciate d''o sistema", 'allmessagesname' => 'Nomme', 'allmessagescurrent' => "Testo 'e mo", # Special:Import 'import' => 'Mpurta paggene', 'import-interwiki-submit' => 'Mpurta', # Import log 'import-logentry-upload' => 'ha mpurtato [[$1]] trammeto upload', # Tooltip help for the actions 'tooltip-pt-logout' => 'Jésce (logout)', 'tooltip-minoredit' => 'Rénne chìsto cagnamiénto cchiù ppiccirìllo.', 'tooltip-save' => "Sàrva 'e cagnamiénte.", 'tooltip-preview' => "Primma 'e sarvà, vìre primma chille ca hê cagnàte!", # Attribution 'others' => 'ate', # Info page 'numedits' => "Nummero 'e cagnamiente (articulo): $1", 'numwatchers' => "Nummero 'e asservature: $1", # Special:NewFiles 'noimages' => "Nun nc'è nind' 'a veré.", 'ilsubmit' => 'Truova', 'exif-xyresolution-i' => '$1 punte pe pollice (dpi)', 'exif-meteringmode-0' => 'Scanusciuto', 'exif-meteringmode-255' => 'Ato', 'exif-lightsource-0' => 'Scanusciuta', 'exif-lightsource-10' => "'Ntruvulato", 'exif-lightsource-11' => 'Aumbruso', 'exif-gaincontrol-0' => 'Nisciuno', 'exif-subjectdistancerange-0' => 'Scanusciuta', # External editor support 'edit-externally-help' => "Pe piglià cchiù nfromma veré 'e [http://www.mediawiki.org/wiki/Manual:External_editors struzione] ('n ngrese)", # 'all' in various places, this might be different for inflected languages 'namespacesall' => 'Tutte', # E-mail address confirmation 'confirmemail_needlogin' => "Abbesognate $1 pe cunfirmà 'o nnerizzo 'e e-mail d''o vuosto.", 'confirmemail_loggedin' => "'O nnerizzo 'e e-mail è vàleto", # Trackbacks 'trackbackremove' => '([$1 Scarta])', # Delete conflict 'deletedwhileediting' => 'Attenziòne: quaccherùno have scancellàto chesta pàggena prìmma ca tu accuminciàste â scrìvere!', # Auto-summaries 'autoredircomment' => 'Redirect â paggena [[$1]]', 'autosumm-new' => 'Paggena nuova: $1', # Special:SpecialPages 'specialpages' => 'Paggene speciale', );
Java
#!/usr/bin/env python import glob, os, sys import sipconfig from PyQt4 import pyqtconfig def get_diana_version(): depends = filter(lambda line: line.startswith("Depends:"), open("debian/control").readlines()) for line in depends: pieces = line.split() for piece in pieces: name_pieces = piece.strip(",").split("-") if len(name_pieces) == 2 and name_pieces[0] == "diana": return name_pieces[1] return None def get_python_diana_version(): line = open("debian/changelog").readline() pieces = line.split() return pieces[1][1:-1] if __name__ == "__main__": if len(sys.argv) not in (1, 3, 5): sys.stderr.write("Usage: %s [<directory containing diana headers> <directory containing libdiana>] " "[<directory containing metlibs headers> <directory containing metlibs libraries>]\n" % sys.argv[0]) sys.exit(1) if len(sys.argv) == 5: metlibs_inc_dir = sys.argv[3] metlibs_lib_dir = sys.argv[4] else: metlibs_inc_dir = "/usr/include/metlibs" metlibs_lib_dir = "/usr/lib" if len(sys.argv) >= 3: diana_inc_dir = sys.argv[1] diana_lib_dir = sys.argv[2] else: diana_inc_dir = "/usr/include/diana" diana_lib_dir = "/usr/lib" qt_pkg_dir = os.getenv("qt_pkg_dir") python_diana_pkg_dir = os.getenv("python_diana_pkg_dir") dest_pkg_dir = os.path.join(python_diana_pkg_dir, "metno") config = pyqtconfig.Configuration() # The name of the SIP build file generated by SIP and used by the build # system. sip_files_dir = "sip" modules = ["std", "metlibs", "diana"] if not os.path.exists("modules"): os.mkdir("modules") # Run SIP to generate the code. output_dirs = [] for module in modules: output_dir = os.path.join("modules", module) build_file = module + ".sbf" build_path = os.path.join(output_dir, build_file) if not os.path.exists(output_dir): os.mkdir(output_dir) sip_file = os.path.join("sip", module, module+".sip") command = " ".join([config.sip_bin, "-c", output_dir, "-b", build_path, "-I"+config.sip_inc_dir, "-I"+config.pyqt_sip_dir, "-I"+diana_inc_dir, "-I/usr/include", "-I"+metlibs_inc_dir, "-I"+qt_pkg_dir+"/include", "-I"+qt_pkg_dir+"/share/sip/PyQt4", "-Isip", config.pyqt_sip_flags, "-w", "-o", # generate docstrings for signatures sip_file]) sys.stdout.write(command+"\n") sys.stdout.flush() if os.system(command) != 0: sys.exit(1) # Create the Makefile (within the diana directory). makefile = pyqtconfig.QtGuiModuleMakefile( config, build_file, dir=output_dir, install_dir=dest_pkg_dir, qt=["QtCore", "QtGui", "QtNetwork", "QtXml", "QtXmlPatterns"] ) if module == "diana": makefile.extra_include_dirs += [ diana_inc_dir, os.path.join(diana_inc_dir, "PaintGL"), metlibs_inc_dir, qt_pkg_dir+"/include" ] makefile.extra_lib_dirs += [diana_lib_dir, qt_pkg_dir+"/lib"] makefile.extra_lflags += ["-Wl,-rpath="+diana_lib_dir, "-Wl,-fPIC"] makefile.extra_libs += ["diana"] if module == "metlibs": makefile.extra_include_dirs.append(diana_inc_dir) makefile.extra_include_dirs.append("/usr/include/metlibs") makefile.extra_lib_dirs += [diana_lib_dir, "/usr/lib", metlibs_lib_dir, qt_pkg_dir+"/lib"] makefile.extra_lflags += ["-Wl,-rpath="+diana_lib_dir, "-Wl,-fPIC"] makefile.extra_libs += ["miLogger", "coserver", "diana"] makefile.generate() output_dirs.append(output_dir) # Update the metno package version. diana_version = get_diana_version() python_diana_version = get_python_diana_version() if not diana_version or not python_diana_version: sys.stderr.write("Failed to find version information for Diana (%s) " "or python-diana (%s)\n" % (repr(diana_version), repr(python_diana_version))) sys.exit(1) f = open("python/metno/versions.py", "w") f.write('\ndiana_version = "%s"\npython_diana_version = "%s"\n' % ( diana_version, python_diana_version)) # Generate the top-level Makefile. python_files = glob.glob(os.path.join("python", "metno", "*.py")) sipconfig.ParentMakefile( configuration = config, subdirs = output_dirs, installs = [(python_files, dest_pkg_dir)] ).generate() sys.exit()
Java
// SPDX-License-Identifier: GPL-2.0 #include "core/subsurface-string.h" #include "qPrefDisplay.h" #include "qPrefPrivate.h" #include <QApplication> #include <QFont> static const QString group = QStringLiteral("Display"); QPointF qPrefDisplay::st_tooltip_position; static const QPointF st_tooltip_position_default = QPointF(0,0); QString qPrefDisplay::st_lastDir; static const QString st_lastDir_default = ""; QString qPrefDisplay::st_theme; static const QString st_theme_default = "Blue"; QString qPrefDisplay::st_userSurvey; static const QString st_userSurvey_default = ""; QByteArray qPrefDisplay::st_mainSplitter; static const QByteArray st_mainSplitter_default = ""; QByteArray qPrefDisplay::st_topSplitter; static const QByteArray st_topSplitter_default = ""; QByteArray qPrefDisplay::st_bottomSplitter; static const QByteArray st_bottomSplitter_default = ""; bool qPrefDisplay::st_maximized; static bool st_maximized_default = false; QByteArray qPrefDisplay::st_geometry; static const QByteArray st_geometry_default = 0; QByteArray qPrefDisplay::st_windowState; static const QByteArray st_windowState_default = 0; int qPrefDisplay::st_lastState; static int st_lastState_default = false; qPrefDisplay::qPrefDisplay(QObject *parent) : QObject(parent) { } qPrefDisplay *qPrefDisplay::instance() { static qPrefDisplay *self = new qPrefDisplay; return self; } void qPrefDisplay::loadSync(bool doSync) { disk_animation_speed(doSync); disk_divelist_font(doSync); disk_font_size(doSync); disk_mobile_scale(doSync); disk_display_invalid_dives(doSync); disk_show_developer(doSync); if (!doSync) { load_tooltip_position(); load_theme(); load_userSurvey(); load_mainSplitter(); load_topSplitter(); load_bottomSplitter(); load_maximized(); load_geometry(); load_windowState(); load_lastState(); } } void qPrefDisplay::set_divelist_font(const QString &value) { QString newValue = value; if (value.contains(",")) newValue = value.left(value.indexOf(",")); if (newValue != prefs.divelist_font && !subsurface_ignore_font(qPrintable(newValue))) { qPrefPrivate::copy_txt(&prefs.divelist_font, value); disk_divelist_font(true); qApp->setFont(QFont(newValue)); emit instance()->divelist_fontChanged(value); } } void qPrefDisplay::disk_divelist_font(bool doSync) { if (doSync) qPrefPrivate::propSetValue(keyFromGroupAndName(group, "divelist_font"), prefs.divelist_font, default_prefs.divelist_font); else setCorrectFont(); } void qPrefDisplay::set_font_size(double value) { if (!IS_FP_SAME(value, prefs.font_size)) { prefs.font_size = value; disk_font_size(true); QFont defaultFont = qApp->font(); defaultFont.setPointSizeF(prefs.font_size * prefs.mobile_scale); qApp->setFont(defaultFont); emit instance()->font_sizeChanged(value); } } void qPrefDisplay::disk_font_size(bool doSync) { // inverted logic compared to the other disk_xxx functions if (!doSync) setCorrectFont(); #if !defined(SUBSURFACE_MOBILE) // we never want to save the font_size to disk - we always want to grab that from the system default else qPrefPrivate::propSetValue(keyFromGroupAndName(group, "font_size"), prefs.font_size, default_prefs.font_size); #endif } void qPrefDisplay::set_mobile_scale(double value) { if (!IS_FP_SAME(value, prefs.mobile_scale)) { prefs.mobile_scale = value; disk_mobile_scale(true); QFont defaultFont = qApp->font(); defaultFont.setPointSizeF(prefs.font_size * prefs.mobile_scale); qApp->setFont(defaultFont); emit instance()->mobile_scaleChanged(value); emit instance()->font_sizeChanged(value); } } void qPrefDisplay::disk_mobile_scale(bool doSync) { if (doSync) { qPrefPrivate::propSetValue(keyFromGroupAndName(group, "mobile_scale"), prefs.mobile_scale, default_prefs.mobile_scale); } else { prefs.mobile_scale = qPrefPrivate::propValue(keyFromGroupAndName(group, "mobile_scale"), default_prefs.mobile_scale).toDouble(); setCorrectFont(); } } //JAN static const QString group = QStringLiteral("Animations"); HANDLE_PREFERENCE_INT(Display, "animation_speed", animation_speed); HANDLE_PREFERENCE_BOOL(Display, "displayinvalid", display_invalid_dives); HANDLE_PREFERENCE_BOOL(Display, "show_developer", show_developer); void qPrefDisplay::setCorrectFont() { // get the font from the settings or our defaults // respect the system default font size if none is explicitly set QFont defaultFont = qPrefPrivate::propValue(keyFromGroupAndName(group, "divelist_font"), prefs.divelist_font).value<QFont>(); if (IS_FP_SAME(system_divelist_default_font_size, -1.0)) { prefs.font_size = qApp->font().pointSizeF(); system_divelist_default_font_size = prefs.font_size; // this way we don't save it on exit } prefs.font_size = qPrefPrivate::propValue(keyFromGroupAndName(group, "font_size"), prefs.font_size).toFloat(); // painful effort to ignore previous default fonts on Windows - ridiculous QString fontName = defaultFont.toString(); if (fontName.contains(",")) fontName = fontName.left(fontName.indexOf(",")); if (subsurface_ignore_font(qPrintable(fontName))) { defaultFont = QFont(prefs.divelist_font); } else { free((void *)prefs.divelist_font); prefs.divelist_font = copy_qstring(fontName); } defaultFont.setPointSizeF(prefs.font_size * prefs.mobile_scale); qApp->setFont(defaultFont); prefs.display_invalid_dives = qPrefPrivate::propValue(keyFromGroupAndName(group, "displayinvalid"), default_prefs.display_invalid_dives).toBool(); } HANDLE_PROP_QSTRING(Display, "FileDialog/LastDir", lastDir); HANDLE_PROP_QSTRING(Display, "Theme/currentTheme", theme); HANDLE_PROP_QPOINTF(Display, "ProfileMap/tooltip_position", tooltip_position); HANDLE_PROP_QSTRING(Display, "UserSurvey/SurveyDone", userSurvey); HANDLE_PROP_QBYTEARRAY(Display, "MainWindow/mainSplitter", mainSplitter); HANDLE_PROP_QBYTEARRAY(Display, "MainWindow/topSplitter", topSplitter); HANDLE_PROP_QBYTEARRAY(Display, "MainWindow/bottomSplitter", bottomSplitter); HANDLE_PROP_BOOL(Display, "MainWindow/maximized", maximized); HANDLE_PROP_QBYTEARRAY(Display, "MainWindow/geometry", geometry); HANDLE_PROP_QBYTEARRAY(Display, "MainWindow/windowState", windowState); HANDLE_PROP_INT(Display, "MainWindow/lastState", lastState);
Java
from datetime import datetime from flask import current_app from flask.cli import with_appcontext from invenio_db import db from hepdata.cli import fix from hepdata.ext.elasticsearch.api import index_record_ids, push_data_keywords from hepdata.modules.submission.models import HEPSubmission, DataSubmission from hepdata.modules.records.utils.common import get_record_by_id from hepdata.modules.records.utils.doi_minter import generate_doi_for_table from hepdata.modules.records.utils.submission import finalise_datasubmission @fix.command() @with_appcontext def create_missing_datasubmission_records(): # Get submissions with missing IDs missing_submissions = DataSubmission.query \ .join(HEPSubmission, HEPSubmission.publication_recid == DataSubmission.publication_recid) \ .filter( DataSubmission.associated_recid == None, DataSubmission.publication_inspire_id == None, DataSubmission.version == HEPSubmission.version, HEPSubmission.overall_status == 'finished') missing_submissions = missing_submissions.all() if not missing_submissions: print("No datasubmissions found with missing record or inspire ids.") return # Organise missing submissions by publication submissions_by_publication = {} for submission in missing_submissions: if submission.publication_recid in submissions_by_publication: submissions_by_publication[submission.publication_recid].append(submission) else: submissions_by_publication[submission.publication_recid] = [submission] # Loop through each publication for publication_recid, submissions in submissions_by_publication.items(): publication_record = get_record_by_id(publication_recid) current_time = "{:%Y-%m-%d %H:%M:%S}".format(datetime.utcnow()) generated_record_ids = [] for submission in submissions: # Finalise each data submission that does not have a record finalise_datasubmission(current_time, {}, generated_record_ids, publication_record, publication_recid, submission, submission.version) # Register the datasubmission's DOI if not current_app.config.get('TESTING', False): generate_doi_for_table.delay(submission.doi) print(f"Generated DOI {submission.doi}") else: print(f"Would generate DOI {submission.doi}") # finalise_datasubmission does not commit, so commit once for each publication db.session.commit() # Reindex the publication and its updated datasubmissions index_record_ids([publication_recid] + generated_record_ids) push_data_keywords(pub_ids=[publication_recid])
Java
/* Core.css for Mocha UI Theme: Default Copyright: Copyright (c) 2007-2009 Greg Houston, <http://greghoustondesign.com/>. License: MIT-style license. Required by: Layout.js */ /* Layout ---------------------------------------------------------------- */ html, body { background: #fff; } body { margin: 0; /* Required */ } #desktop { position: relative; min-width: 400px; /* Helps keep header content from wrapping */ height: 100%; min-height: 100%; overflow: hidden; cursor: default; /* Fix for issue in IE7. IE7 wants to use the I-bar text cursor */ } #desktopHeader { background: #f2f2f2; } #desktopTitlebarWrapper { position: relative; height: 45px; overflow: hidden; background: #718BA6 url(../images/skin/bg-header.gif) repeat-x; } #desktopTitlebar { padding: 7px 8px 6px 8px; height: 32px; background: url(../images/skin/logo.gif) no-repeat; background-position: left 0; } #desktopTitlebar h1.applicationTitle { display: none; margin: 0; padding: 0 5px 0 0; font-size: 20px; line-height: 25px; font-weight: bold; color: #fff; } #desktopTitlebar h2.tagline { padding: 7px 0 0 0; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 10px; color: #d4dce4; font-weight: bold; text-align: center; text-transform: uppercase; } #desktopTitlebar h2.tagline .taglineEm { color: #fff; font-weight: bold; } #topNav { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 10px; position: absolute; right: 0; top: 0; color: #d4dce4; text-align: right; padding: 13px 10px 0 0; } #topNav a { color: #fff; font-weight: normal; } #topNav a:hover { text-decoration: none; } /* Navbar */ #desktopNavbar { background: #f2f2f2; /*height: 30px;*/ margin: 0 0px; overflow: hidden; /* Remove this line if you want the menu to be backward compatible with Firefox 2 */ /* Fixes by Chris */ /*background-color: #ccc;*/ height: 20px; margin-bottom: 5px; border-bottom: 1px solid #3f3f3f; } #desktopNavbar ul { padding: 0; margin: 0; list-style: none; font-size: 12px; } #desktopNavbar li { float: left; } #desktopNavbar a { display: block; } #desktopNavbar ul li a { /*padding: 6px 10px 6px 10px;*/ color: #333; font-weight: normal; /* Fix by Chris */ padding: 2px 10px 6px 10px; } #desktopNavbar ul li a:hover { color: #333; /* Fix By Chris */ background-color: #fff; } #desktopNavbar ul li a.arrow-right, #desktopNavbar ul li a:hover.arrow-right { background-image: url(../images/skin/arrow-right.gif); background-repeat: no-repeat; background-position: right 7px; } #desktopNavbar li ul { padding: 2px; border: 1px solid #3f3f3f; background: #fff url(../images/skin/bg-dropdown.gif) repeat-y; position: absolute; width: 164px; left: -999em; z-index: 8000; /* Fix by Chris */ margin-top: -6px; } #desktopNavbar li:hover ul ul, #desktopNavbar li.ieHover ul ul, #desktopNavbar li:hover ul ul ul, #desktopNavbar li.ieHover ul ul ul { left: -999em; } #desktopNavbar li ul ul { /* third-and-above-level lists */ margin: -22px 0 0 163px; } #desktopNavbar li ul li .check { position: absolute; top: 8px; left: 6px; width: 5px; height: 5px; background: #555; overflow: hidden; line-height: 1px; font-size: 1px; } #desktopNavbar li ul li a { position: relative; /*padding: 1px 9px 1px 25px;*/ width: 130px; color: #3f3f3f; font-weight: normal; /* Fix By Chris */ padding: 1px 9px 1px 20px; /* Reduce left padding */ } #desktopNavbar li ul li a:hover { background: #6C98D9; color: #fff; -moz-border-radius: 2px; } #desktopNavbar li ul li a:hover .check { background: #fff; } #desktopNavbar li:hover ul, #desktopNavbar li.ieHover ul, #desktopNavbar li li.ieHover ul, #desktopNavbar li li li.ieHover ul, #desktopNavbar li li:hover ul, #desktopNavbar li li li:hover ul { /* lists nested under hovered list items */ left: auto; } #desktopNavbar li:hover { /* For IE7 */ position: static; } li.divider { margin-top: 2px; padding-top: 3px; border-top: 1px solid #ebebeb; } #pageWrapper { position: relative; overflow: hidden; /* This can be set to hidden or auto */ border-top: 1px solid #909090; border-bottom: 1px solid #909090; /*height: 100%;*/ } /* Footer */ #desktopFooterWrapper { position: absolute; left: 0; bottom: 0; width: 100%; height: 30px; overflow: hidden; } #desktopFooter { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 10px; height: 24px; padding: 6px 8px 0 8px; background: #f2f2f2; } /* Panel Layout ---------------------------------------------------------------- */ /* Columns */ .column { position: relative; float: left; overflow: hidden; /* Required by IE6 */ } /* Panels */ .panel { position: relative; overflow: auto; background: #f8f8f8; border-bottom: 1px solid #b9b9b9; } .panelWrapper.collapsed .panel-header { border-bottom: 0; } .panelAlt { background: #f2f2f2; } .bottomPanel { border-bottom: 0; } .pad { padding: 8px; } #mainPanel { background: #fff; } .panel-header { position: relative; background: #f1f1f1 url(../images/skin/bg-panel-header.gif) repeat-x; height: 30px; overflow: hidden; border-bottom: 1px solid #d3d3d3; } .panel-headerContent { padding-top: 2px; } .panel-headerContent.tabs { background: url(../images/skin/tabs.gif) repeat-x; background-position: left -68px; } .panel-header h2 { display: inline-block; font-size: 12px; margin: 0; padding: 3px 8px 0 8px; height: 22px; overflow: hidden; color: #333; } .panel-collapse { background: url(../images/skin/collapse-expand.gif) left top no-repeat; } .panel-expand { background: url(../images/skin/collapse-expand.gif) left -16px no-repeat; } .icon16 { margin: 4px 0 0 2px; cursor: pointer; } /* Column and Panel Handles */ .horizontalHandle { height: 4px; line-height: 1px; font-size: 1px; overflow: hidden; background: #eee url(../images/skin/bg-handle-horizontal.gif) repeat-x; } .horizontalHandle.detached .handleIcon { background: transparent; } .horizontalHandle .handleIcon { margin: 0 auto; height: 4px; line-height: 1px; font-size: 1px; overflow: hidden; background: url(../images/skin/handle-icon-horizontal.gif) center center no-repeat; } .columnHandle { min-height: 10px; float: left; width: 4px; overflow: hidden; background: #c3c3c3 url(../images/skin/handle-icon.gif) center center no-repeat; border: 1px solid #909090; border-top: 0; border-bottom: 0; } /* Toolboxes */ .toolbox { float: right; margin-top: 3px; padding: 0 5px; height: 24px; overflow: hidden; text-align: right; } .panel-header-toolbox { } div.toolbox.divider { /* Have to specify div here for IE6's sake */ background: url(../images/skin/toolbox-divider.gif) repeat-y; padding-left: 8px; } .toolbox img.disabled { cursor: default; } .iconWrapper { display: inline-block; height: 22px; min-width: 22px; overflow: hidden; border: 1px solid transparent; } * html .iconWrapper { padding: 1px; border: 0; } .iconWrapper img { cursor: pointer; margin: 0; padding: 3px; } .iconWrapper:hover { border: 1px solid #a0a0a0; -moz-border-radius: 3px; } #spinnerWrapper { width: 16px; height: 16px; background: url(../images/skin/spinner-placeholder.gif) no-repeat; margin: 4px 5px 0 5px; } #spinner { display: none; background: url(../images/skin/spinner.gif) no-repeat; width: 16px; height: 16px; }
Java
/****************************************************************************** * * rawverse.cpp - code for class 'RawVerse'- a module that reads raw text * files: ot and nt using indexs ??.bks ??.cps ??.vss * and provides lookup and parsing functions based on * class VerseKey * * $Id$ * * Copyright 1997-2013 CrossWire Bible Society (http://www.crosswire.org) * CrossWire Bible Society * P. O. Box 2528 * Tempe, AZ 85280-2528 * * 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 version 2. * * 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. * */ #include <ctype.h> #include <stdio.h> #include <fcntl.h> #include <errno.h> #include <utilstr.h> #include <rawverse.h> #include <versekey.h> #include <sysdata.h> #include <filemgr.h> #include <swbuf.h> SWORD_NAMESPACE_START /****************************************************************************** * RawVerse Statics */ int RawVerse::instance = 0; const char RawVerse::nl = '\n'; /****************************************************************************** * RawVerse Constructor - Initializes data for instance of RawVerse * * ENT: ipath - path of the directory where data and index files are located. * be sure to include the trailing separator (e.g. '/' or '\') * (e.g. 'modules/texts/rawtext/webster/') */ RawVerse::RawVerse(const char *ipath, int fileMode) { SWBuf buf; path = 0; stdstr(&path, ipath); if ((path[strlen(path)-1] == '/') || (path[strlen(path)-1] == '\\')) path[strlen(path)-1] = 0; if (fileMode == -1) { // try read/write if possible fileMode = FileMgr::RDWR; } buf.setFormatted("%s/ot.vss", path); idxfp[0] = FileMgr::getSystemFileMgr()->open(buf, fileMode, true); buf.setFormatted("%s/nt.vss", path); idxfp[1] = FileMgr::getSystemFileMgr()->open(buf, fileMode, true); buf.setFormatted("%s/ot", path); textfp[0] = FileMgr::getSystemFileMgr()->open(buf, fileMode, true); buf.setFormatted("%s/nt", path); textfp[1] = FileMgr::getSystemFileMgr()->open(buf, fileMode, true); instance++; } /****************************************************************************** * RawVerse Destructor - Cleans up instance of RawVerse */ RawVerse::~RawVerse() { int loop1; if (path) delete [] path; --instance; for (loop1 = 0; loop1 < 2; loop1++) { FileMgr::getSystemFileMgr()->close(idxfp[loop1]); FileMgr::getSystemFileMgr()->close(textfp[loop1]); } } /****************************************************************************** * RawVerse::findoffset - Finds the offset of the key verse from the indexes * * ENT: testmt - testament to find (0 - Bible/module introduction) * idxoff - offset into .vss * start - address to store the starting offset * size - address to store the size of the entry */ void RawVerse::findOffset(char testmt, long idxoff, long *start, unsigned short *size) const { idxoff *= 6; if (!testmt) testmt = ((idxfp[1]) ? 1:2); if (idxfp[testmt-1]->getFd() >= 0) { idxfp[testmt-1]->seek(idxoff, SEEK_SET); __s32 tmpStart; __u16 tmpSize; idxfp[testmt-1]->read(&tmpStart, 4); long len = idxfp[testmt-1]->read(&tmpSize, 2); // read size *start = swordtoarch32(tmpStart); *size = swordtoarch16(tmpSize); if (len < 2) { *size = (unsigned short)((*start) ? (textfp[testmt-1]->seek(0, SEEK_END) - (long)*start) : 0); // if for some reason we get an error reading size, make size to end of file } } else { *start = 0; *size = 0; } } /****************************************************************************** * RawVerse::readtext - gets text at a given offset * * ENT: testmt - testament file to search in (0 - Old; 1 - New) * start - starting offset where the text is located in the file * size - size of text entry + 2 (null)(null) * buf - buffer to store text * */ void RawVerse::readText(char testmt, long start, unsigned short size, SWBuf &buf) const { buf = ""; buf.setFillByte(0); buf.setSize(size + 1); if (!testmt) testmt = ((idxfp[1]) ? 1:2); if (size) { if (textfp[testmt-1]->getFd() >= 0) { textfp[testmt-1]->seek(start, SEEK_SET); textfp[testmt-1]->read(buf.getRawData(), (int)size); } } } /****************************************************************************** * RawVerse::settext - Sets text for current offset * * ENT: testmt - testament to find (0 - Bible/module introduction) * idxoff - offset into .vss * buf - buffer to store * len - length of buffer (0 - null terminated) */ void RawVerse::doSetText(char testmt, long idxoff, const char *buf, long len) { __s32 start; __u16 size; idxoff *= 6; if (!testmt) testmt = ((idxfp[1]) ? 1:2); size = (len < 0) ? strlen(buf) : len; start = (__s32)textfp[testmt-1]->seek(0, SEEK_END); idxfp[testmt-1]->seek(idxoff, SEEK_SET); if (size) { textfp[testmt-1]->seek(start, SEEK_SET); textfp[testmt-1]->write(buf, (int)size); // add a new line to make data file easier to read in an editor textfp[testmt-1]->write(&nl, 1); } else { start = 0; } start = archtosword32(start); size = archtosword16(size); idxfp[testmt-1]->write(&start, 4); idxfp[testmt-1]->write(&size, 2); } /****************************************************************************** * RawVerse::linkentry - links one entry to another * * ENT: testmt - testament to find (0 - Bible/module introduction) * destidxoff - dest offset into .vss * srcidxoff - source offset into .vss */ void RawVerse::doLinkEntry(char testmt, long destidxoff, long srcidxoff) { __s32 start; __u16 size; destidxoff *= 6; srcidxoff *= 6; if (!testmt) testmt = ((idxfp[1]) ? 1:2); // get source idxfp[testmt-1]->seek(srcidxoff, SEEK_SET); idxfp[testmt-1]->read(&start, 4); idxfp[testmt-1]->read(&size, 2); // write dest idxfp[testmt-1]->seek(destidxoff, SEEK_SET); idxfp[testmt-1]->write(&start, 4); idxfp[testmt-1]->write(&size, 2); } /****************************************************************************** * RawVerse::createModule - Creates new module files * * ENT: path - directory to store module files * RET: error status */ char RawVerse::createModule(const char *ipath, const char *v11n) { char *path = 0; char *buf = new char [ strlen (ipath) + 20 ]; FileDesc *fd, *fd2; stdstr(&path, ipath); if ((path[strlen(path)-1] == '/') || (path[strlen(path)-1] == '\\')) path[strlen(path)-1] = 0; sprintf(buf, "%s/ot", path); FileMgr::removeFile(buf); fd = FileMgr::getSystemFileMgr()->open(buf, FileMgr::CREAT|FileMgr::WRONLY, FileMgr::IREAD|FileMgr::IWRITE); fd->getFd(); FileMgr::getSystemFileMgr()->close(fd); sprintf(buf, "%s/nt", path); FileMgr::removeFile(buf); fd = FileMgr::getSystemFileMgr()->open(buf, FileMgr::CREAT|FileMgr::WRONLY, FileMgr::IREAD|FileMgr::IWRITE); fd->getFd(); FileMgr::getSystemFileMgr()->close(fd); sprintf(buf, "%s/ot.vss", path); FileMgr::removeFile(buf); fd = FileMgr::getSystemFileMgr()->open(buf, FileMgr::CREAT|FileMgr::WRONLY, FileMgr::IREAD|FileMgr::IWRITE); fd->getFd(); sprintf(buf, "%s/nt.vss", path); FileMgr::removeFile(buf); fd2 = FileMgr::getSystemFileMgr()->open(buf, FileMgr::CREAT|FileMgr::WRONLY, FileMgr::IREAD|FileMgr::IWRITE); fd2->getFd(); VerseKey vk; vk.setVersificationSystem(v11n); vk.setIntros(1); __s32 offset = 0; __u16 size = 0; offset = archtosword32(offset); size = archtosword16(size); for (vk = TOP; !vk.popError(); vk++) { if (vk.getTestament() < 2) { fd->write(&offset, 4); fd->write(&size, 2); } else { fd2->write(&offset, 4); fd2->write(&size, 2); } } fd2->write(&offset, 4); fd2->write(&size, 2); FileMgr::getSystemFileMgr()->close(fd); FileMgr::getSystemFileMgr()->close(fd2); delete [] path; delete [] buf; return 0; } SWORD_NAMESPACE_END
Java
// KinematicObjectSphereConstraint.h // // Breannan Smith // Last updated: 09/16/2015 #ifndef KINEMATIC_OBJECT_SPHERE_CONSTRAINT_H #define KINEMATIC_OBJECT_SPHERE_CONSTRAINT_H #include "scisim/Constraints/Constraint.h" class KinematicObjectSphereConstraint final : public Constraint { public: // sphere_idx: index of sphere // r: radius of sphere // n: collision normal // kinematic_index: index of the kinematic body // X: center of mass of kinematic object // V: velocity of kinematic object // omega: angular velocity of kinematic object KinematicObjectSphereConstraint( const unsigned sphere_idx, const scalar& r, const Vector3s& n, const unsigned kinematic_index, const Vector3s& X, const Vector3s& V, const Vector3s& omega ); virtual ~KinematicObjectSphereConstraint() override; // Inherited from Constraint virtual scalar evalNdotV( const VectorXs& q, const VectorXs& v ) const override; virtual void evalgradg( const VectorXs& q, const int col, SparseMatrixsc& G, const FlowableSystem& fsys ) const override; virtual void computeGeneralizedFrictionGivenTangentSample( const VectorXs& q, const VectorXs& t, const unsigned column, SparseMatrixsc& D ) const override; virtual int impactStencilSize() const override; virtual int frictionStencilSize() const override; virtual void getSimulatedBodyIndices( std::pair<int,int>& bodies ) const override; virtual void getBodyIndices( std::pair<int,int>& bodies ) const override; virtual void evalKinematicNormalRelVel( const VectorXs& q, const int strt_idx, VectorXs& gdotN ) const override; virtual void evalH( const VectorXs& q, const MatrixXXsc& basis, MatrixXXsc& H0, MatrixXXsc& H1 ) const override; virtual bool conservesTranslationalMomentum() const override; virtual bool conservesAngularMomentumUnderImpact() const override; virtual bool conservesAngularMomentumUnderImpactAndFriction() const override; virtual std::string name() const override; // For binary force output virtual void getWorldSpaceContactPoint( const VectorXs& q, VectorXs& contact_point ) const override; virtual void getWorldSpaceContactNormal( const VectorXs& q, VectorXs& contact_normal ) const override; unsigned sphereIdx() const; private: virtual void computeContactBasis( const VectorXs& q, const VectorXs& v, MatrixXXsc& basis ) const override; virtual VectorXs computeRelativeVelocity( const VectorXs& q, const VectorXs& v ) const override; virtual void setBodyIndex0( const unsigned idx ) override; virtual VectorXs computeKinematicRelativeVelocity( const VectorXs& q, const VectorXs& v ) const override; //Vector3s computeKinematicCollisionPointVelocity( const VectorXs& q ) const; // Index of the colliding sphere unsigned m_sphere_idx; // Sphere's radius const scalar m_r; // Normal to prevent penetration along const Vector3s m_n; // Index of the kinematic body const unsigned m_kinematic_index; // Center of the kinematic object const Vector3s m_X; // Translational velocity of the kinematic object const Vector3s m_V; // Rotational velocity of the kinematic object const Vector3s m_omega; }; #endif
Java
#pragma once #ifndef __TRINITY_UPDATEFIELDFLAGS_H__ #define __TRINITY_UPDATEFIELDFLAGS_H__ #include "UpdateFieldFlags.h" // Auto generated for version 17359 // > Object uint32 ObjectUpdateFieldFlags[OBJECT_END] = { UF_FLAG_PUBLIC, // OBJECT_FIELD_GUID UF_FLAG_PUBLIC, // OBJECT_FIELD_GUID UF_FLAG_PUBLIC, // OBJECT_FIELD_DATA UF_FLAG_PUBLIC, // OBJECT_FIELD_DATA UF_FLAG_PUBLIC, // OBJECT_FIELD_TYPE UF_FLAG_VIEWER_DEPENDENT, // OBJECT_FIELD_ENTRY_ID UF_FLAG_VIEWER_DEPENDENT | UF_FLAG_URGENT, // OBJECT_FIELD_DYNAMIC_FLAGS UF_FLAG_PUBLIC, // OBJECT_FIELD_SCALE }; // > Object > Item uint32 ItemUpdateFieldFlags[ITEM_END] = { UF_FLAG_PUBLIC, // OBJECT_FIELD_GUID UF_FLAG_PUBLIC, // OBJECT_FIELD_GUID UF_FLAG_PUBLIC, // OBJECT_FIELD_DATA UF_FLAG_PUBLIC, // OBJECT_FIELD_DATA UF_FLAG_PUBLIC, // OBJECT_FIELD_TYPE UF_FLAG_VIEWER_DEPENDENT, // OBJECT_FIELD_ENTRY_ID UF_FLAG_VIEWER_DEPENDENT | UF_FLAG_URGENT, // OBJECT_FIELD_DYNAMIC_FLAGS UF_FLAG_PUBLIC, // OBJECT_FIELD_SCALE UF_FLAG_PUBLIC, // ITEM_FIELD_OWNER UF_FLAG_PUBLIC, // ITEM_FIELD_OWNER UF_FLAG_PUBLIC, // ITEM_FIELD_CONTAINED_IN UF_FLAG_PUBLIC, // ITEM_FIELD_CONTAINED_IN UF_FLAG_PUBLIC, // ITEM_FIELD_CREATOR UF_FLAG_PUBLIC, // ITEM_FIELD_CREATOR UF_FLAG_PUBLIC, // ITEM_FIELD_GIFT_CREATOR UF_FLAG_PUBLIC, // ITEM_FIELD_GIFT_CREATOR UF_FLAG_OWNER, // ITEM_FIELD_STACK_COUNT UF_FLAG_OWNER, // ITEM_FIELD_EXPIRATION UF_FLAG_OWNER, // ITEM_FIELD_SPELL_CHARGES UF_FLAG_OWNER, // ITEM_FIELD_SPELL_CHARGES UF_FLAG_OWNER, // ITEM_FIELD_SPELL_CHARGES UF_FLAG_OWNER, // ITEM_FIELD_SPELL_CHARGES UF_FLAG_OWNER, // ITEM_FIELD_SPELL_CHARGES UF_FLAG_PUBLIC, // ITEM_FIELD_DYNAMIC_FLAGS UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_PROPERTY_SEED UF_FLAG_PUBLIC, // ITEM_FIELD_RANDOM_PROPERTIES_ID UF_FLAG_OWNER, // ITEM_FIELD_DURABILITY UF_FLAG_OWNER, // ITEM_FIELD_MAX_DURABILITY UF_FLAG_PUBLIC, // ITEM_FIELD_CREATE_PLAYED_TIME UF_FLAG_OWNER, // ITEM_FIELD_MODIFIERS_MASK }; // > Object > Item > Container uint32 ContainerUpdateFieldFlags[CONTAINER_END] = { UF_FLAG_PUBLIC, // OBJECT_FIELD_GUID UF_FLAG_PUBLIC, // OBJECT_FIELD_GUID UF_FLAG_PUBLIC, // OBJECT_FIELD_DATA UF_FLAG_PUBLIC, // OBJECT_FIELD_DATA UF_FLAG_PUBLIC, // OBJECT_FIELD_TYPE UF_FLAG_VIEWER_DEPENDENT, // OBJECT_FIELD_ENTRY_ID UF_FLAG_VIEWER_DEPENDENT | UF_FLAG_URGENT, // OBJECT_FIELD_DYNAMIC_FLAGS UF_FLAG_PUBLIC, // OBJECT_FIELD_SCALE UF_FLAG_PUBLIC, // ITEM_FIELD_OWNER UF_FLAG_PUBLIC, // ITEM_FIELD_OWNER UF_FLAG_PUBLIC, // ITEM_FIELD_CONTAINED_IN UF_FLAG_PUBLIC, // ITEM_FIELD_CONTAINED_IN UF_FLAG_PUBLIC, // ITEM_FIELD_CREATOR UF_FLAG_PUBLIC, // ITEM_FIELD_CREATOR UF_FLAG_PUBLIC, // ITEM_FIELD_GIFT_CREATOR UF_FLAG_PUBLIC, // ITEM_FIELD_GIFT_CREATOR UF_FLAG_OWNER, // ITEM_FIELD_STACK_COUNT UF_FLAG_OWNER, // ITEM_FIELD_EXPIRATION UF_FLAG_OWNER, // ITEM_FIELD_SPELL_CHARGES UF_FLAG_OWNER, // ITEM_FIELD_SPELL_CHARGES UF_FLAG_OWNER, // ITEM_FIELD_SPELL_CHARGES UF_FLAG_OWNER, // ITEM_FIELD_SPELL_CHARGES UF_FLAG_OWNER, // ITEM_FIELD_SPELL_CHARGES UF_FLAG_PUBLIC, // ITEM_FIELD_DYNAMIC_FLAGS UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT UF_FLAG_PUBLIC, // ITEM_FIELD_PROPERTY_SEED UF_FLAG_PUBLIC, // ITEM_FIELD_RANDOM_PROPERTIES_ID UF_FLAG_OWNER, // ITEM_FIELD_DURABILITY UF_FLAG_OWNER, // ITEM_FIELD_MAX_DURABILITY UF_FLAG_PUBLIC, // ITEM_FIELD_CREATE_PLAYED_TIME UF_FLAG_OWNER, // ITEM_FIELD_MODIFIERS_MASK UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS UF_FLAG_PUBLIC, // CONTAINER_FIELD_NUM_SLOTS }; // > Object > Unit uint32 UnitUpdateFieldFlags[UNIT_END] = { UF_FLAG_PUBLIC, // OBJECT_FIELD_GUID UF_FLAG_PUBLIC, // OBJECT_FIELD_GUID UF_FLAG_PUBLIC, // OBJECT_FIELD_DATA UF_FLAG_PUBLIC, // OBJECT_FIELD_DATA UF_FLAG_PUBLIC, // OBJECT_FIELD_TYPE UF_FLAG_PUBLIC | UF_FLAG_VIEWER_DEPENDENT, // OBJECT_FIELD_ENTRY_ID UF_FLAG_VIEWER_DEPENDENT | UF_FLAG_URGENT, // OBJECT_FIELD_DYNAMIC_FLAGS UF_FLAG_PUBLIC, // OBJECT_FIELD_SCALE UF_FLAG_PUBLIC, // UNIT_FIELD_CHARM UF_FLAG_PUBLIC, // UNIT_FIELD_CHARM UF_FLAG_PUBLIC, // UNIT_FIELD_SUMMON UF_FLAG_PUBLIC, // UNIT_FIELD_SUMMON UF_FLAG_PRIVATE, // UNIT_FIELD_CRITTER UF_FLAG_PRIVATE, // UNIT_FIELD_CRITTER UF_FLAG_PUBLIC, // UNIT_FIELD_CHARMED_BY UF_FLAG_PUBLIC, // UNIT_FIELD_CHARMED_BY UF_FLAG_PUBLIC, // UNIT_FIELD_SUMMONED_BY UF_FLAG_PUBLIC, // UNIT_FIELD_SUMMONED_BY UF_FLAG_PUBLIC, // UNIT_FIELD_CREATED_BY UF_FLAG_PUBLIC, // UNIT_FIELD_CREATED_BY UF_FLAG_PUBLIC, // UNIT_FIELD_DEMON_CREATOR UF_FLAG_PUBLIC, // UNIT_FIELD_DEMON_CREATOR UF_FLAG_PUBLIC, // UNIT_FIELD_TARGET UF_FLAG_PUBLIC, // UNIT_FIELD_TARGET UF_FLAG_PUBLIC, // UNIT_FIELD_BATTLE_PET_COMPANION_GUID UF_FLAG_PUBLIC, // UNIT_FIELD_BATTLE_PET_COMPANION_GUID UF_FLAG_PUBLIC | UF_FLAG_URGENT, // UNIT_FIELD_CHANNEL_OBJECT UF_FLAG_PUBLIC | UF_FLAG_URGENT, // UNIT_FIELD_CHANNEL_OBJECT UF_FLAG_PUBLIC | UF_FLAG_URGENT, // UNIT_FIELD_CHANNEL_SPELL UF_FLAG_PUBLIC, // UNIT_FIELD_SUMMONED_BY_HOME_REALM UF_FLAG_PUBLIC, // UNIT_FIELD_SEX UF_FLAG_PUBLIC, // UNIT_FIELD_DISPLAY_POWER UF_FLAG_PUBLIC, // UNIT_FIELD_OVERRIDE_DISPLAY_POWER_ID UF_FLAG_PUBLIC, // UNIT_FIELD_HEALTH UF_FLAG_PUBLIC, // UNIT_FIELD_POWER UF_FLAG_PUBLIC, // UNIT_FIELD_POWER UF_FLAG_PUBLIC, // UNIT_FIELD_POWER UF_FLAG_PUBLIC, // UNIT_FIELD_POWER UF_FLAG_PUBLIC, // UNIT_FIELD_POWER UF_FLAG_PUBLIC, // UNIT_FIELD_MAX_HEALTH UF_FLAG_PUBLIC, // UNIT_FIELD_MAX_POWER UF_FLAG_PUBLIC, // UNIT_FIELD_MAX_POWER UF_FLAG_PUBLIC, // UNIT_FIELD_MAX_POWER UF_FLAG_PUBLIC, // UNIT_FIELD_MAX_POWER UF_FLAG_PUBLIC, // UNIT_FIELD_MAX_POWER UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_ALL_UNITS, // UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_ALL_UNITS, // UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_ALL_UNITS, // UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_ALL_UNITS, // UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_ALL_UNITS, // UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_ALL_UNITS, // UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_ALL_UNITS, // UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_ALL_UNITS, // UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_ALL_UNITS, // UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_ALL_UNITS, // UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER UF_FLAG_PUBLIC, // UNIT_FIELD_LEVEL UF_FLAG_PUBLIC, // UNIT_FIELD_EFFECTIVE_LEVEL UF_FLAG_PUBLIC, // UNIT_FIELD_FACTION_TEMPLATE UF_FLAG_PUBLIC, // UNIT_FIELD_VIRTUAL_ITEM_ID UF_FLAG_PUBLIC, // UNIT_FIELD_VIRTUAL_ITEM_ID UF_FLAG_PUBLIC, // UNIT_FIELD_VIRTUAL_ITEM_ID UF_FLAG_PUBLIC, // UNIT_FIELD_FLAGS UF_FLAG_PUBLIC, // UNIT_FIELD_FLAGS2 UF_FLAG_PUBLIC, // UNIT_FIELD_AURA_STATE UF_FLAG_PUBLIC, // UNIT_FIELD_ATTACK_ROUND_BASE_TIME UF_FLAG_PUBLIC, // UNIT_FIELD_ATTACK_ROUND_BASE_TIME UF_FLAG_PRIVATE, // UNIT_FIELD_RANGED_ATTACK_ROUND_BASE_TIME UF_FLAG_PUBLIC, // UNIT_FIELD_BOUNDING_RADIUS UF_FLAG_PUBLIC, // UNIT_FIELD_COMBAT_REACH UF_FLAG_VIEWER_DEPENDENT | UF_FLAG_URGENT, // UNIT_FIELD_DISPLAY_ID UF_FLAG_PUBLIC | UF_FLAG_URGENT, // UNIT_FIELD_NATIVE_DISPLAY_ID UF_FLAG_PUBLIC | UF_FLAG_URGENT, // UNIT_FIELD_MOUNT_DISPLAY_ID UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_EMPATH, // UNIT_FIELD_MIN_DAMAGE UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_EMPATH, // UNIT_FIELD_MAX_DAMAGE UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_EMPATH, // UNIT_FIELD_MIN_OFF_HAND_DAMAGE UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_EMPATH, // UNIT_FIELD_MAX_OFF_HAND_DAMAGE UF_FLAG_PUBLIC, // UNIT_FIELD_ANIM_TIER UF_FLAG_PUBLIC, // UNIT_FIELD_PET_NUMBER UF_FLAG_PUBLIC, // UNIT_FIELD_PET_NAME_TIMESTAMP UF_FLAG_OWNER, // UNIT_FIELD_PET_EXPERIENCE UF_FLAG_OWNER, // UNIT_FIELD_PET_NEXT_LEVEL_EXPERIENCE UF_FLAG_PUBLIC, // UNIT_FIELD_MOD_CASTING_SPEED UF_FLAG_PUBLIC, // UNIT_FIELD_MOD_SPELL_HASTE UF_FLAG_PUBLIC, // UNIT_FIELD_MOD_HASTE UF_FLAG_PUBLIC, // UNIT_FIELD_MOD_RANGED_HASTE UF_FLAG_PUBLIC, // UNIT_FIELD_MOD_HASTE_REGEN UF_FLAG_PUBLIC, // UNIT_FIELD_CREATED_BY_SPELL UF_FLAG_PUBLIC | UF_FLAG_VIEWER_DEPENDENT, // UNIT_FIELD_NPC_FLAGS UF_FLAG_PUBLIC, // UNIT_FIELD_NPC_FLAGS UF_FLAG_PUBLIC, // UNIT_FIELD_EMOTE_STATE UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_STATS UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_STATS UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_STATS UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_STATS UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_STATS UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_STAT_POS_BUFF UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_STAT_POS_BUFF UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_STAT_POS_BUFF UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_STAT_POS_BUFF UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_STAT_POS_BUFF UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_STAT_NEG_BUFF UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_STAT_NEG_BUFF UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_STAT_NEG_BUFF UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_STAT_NEG_BUFF UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_STAT_NEG_BUFF UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_EMPATH, // UNIT_FIELD_RESISTANCES UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_EMPATH, // UNIT_FIELD_RESISTANCES UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_EMPATH, // UNIT_FIELD_RESISTANCES UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_EMPATH, // UNIT_FIELD_RESISTANCES UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_EMPATH, // UNIT_FIELD_RESISTANCES UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_EMPATH, // UNIT_FIELD_RESISTANCES UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_EMPATH, // UNIT_FIELD_RESISTANCES UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCE_BUFF_MODS_POSITIVE UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCE_BUFF_MODS_POSITIVE UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCE_BUFF_MODS_POSITIVE UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCE_BUFF_MODS_POSITIVE UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCE_BUFF_MODS_POSITIVE UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCE_BUFF_MODS_POSITIVE UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCE_BUFF_MODS_POSITIVE UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCE_BUFF_MODS_NEGATIVE UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCE_BUFF_MODS_NEGATIVE UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCE_BUFF_MODS_NEGATIVE UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCE_BUFF_MODS_NEGATIVE UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCE_BUFF_MODS_NEGATIVE UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCE_BUFF_MODS_NEGATIVE UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCE_BUFF_MODS_NEGATIVE UF_FLAG_PUBLIC, // UNIT_FIELD_BASE_MANA UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_BASE_HEALTH UF_FLAG_PUBLIC, // UNIT_FIELD_SHAPESHIFT_FORM UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_ATTACK_POWER UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_ATTACK_POWER_MOD_POS UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_ATTACK_POWER_MOD_NEG UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_ATTACK_POWER_MULTIPLIER UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RANGED_ATTACK_POWER UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RANGED_ATTACK_POWER_MOD_POS UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RANGED_ATTACK_POWER_MOD_NEG UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_MIN_RANGED_DAMAGE UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_MAX_RANGED_DAMAGE UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MODIFIER UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MODIFIER UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MODIFIER UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MODIFIER UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MODIFIER UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MODIFIER UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MODIFIER UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MULTIPLIER UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MULTIPLIER UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MULTIPLIER UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MULTIPLIER UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MULTIPLIER UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MULTIPLIER UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MULTIPLIER UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_MAX_HEALTH_MODIFIER UF_FLAG_PUBLIC, // UNIT_FIELD_HOVER_HEIGHT UF_FLAG_PUBLIC, // UNIT_FIELD_MIN_ITEM_LEVEL UF_FLAG_PUBLIC, // UNIT_FIELD_MAX_ITEM_LEVEL UF_FLAG_PUBLIC, // UNIT_FIELD_WILD_BATTLE_PET_LEVEL UF_FLAG_PUBLIC, // UNIT_FIELD_BATTLE_PET_COMPANION_NAME_TIMESTAMP UF_FLAG_PUBLIC, // UNIT_FIELD_INTERACT_SPELL_ID }; // > Object > Unit > Player uint32 PlayerUpdateFieldFlags[PLAYER_END] = { UF_FLAG_PUBLIC, // OBJECT_FIELD_GUID UF_FLAG_PUBLIC, // OBJECT_FIELD_GUID UF_FLAG_PUBLIC, // OBJECT_FIELD_DATA UF_FLAG_PUBLIC, // OBJECT_FIELD_DATA UF_FLAG_PUBLIC, // OBJECT_FIELD_TYPE UF_FLAG_PUBLIC | UF_FLAG_VIEWER_DEPENDENT, // OBJECT_FIELD_ENTRY_ID UF_FLAG_VIEWER_DEPENDENT | UF_FLAG_URGENT, // OBJECT_FIELD_DYNAMIC_FLAGS UF_FLAG_PUBLIC, // OBJECT_FIELD_SCALE UF_FLAG_PUBLIC, // UNIT_FIELD_CHARM UF_FLAG_PUBLIC, // UNIT_FIELD_CHARM UF_FLAG_PUBLIC, // UNIT_FIELD_SUMMON UF_FLAG_PUBLIC, // UNIT_FIELD_SUMMON UF_FLAG_PRIVATE, // UNIT_FIELD_CRITTER UF_FLAG_PRIVATE, // UNIT_FIELD_CRITTER UF_FLAG_PUBLIC, // UNIT_FIELD_CHARMED_BY UF_FLAG_PUBLIC, // UNIT_FIELD_CHARMED_BY UF_FLAG_PUBLIC, // UNIT_FIELD_SUMMONED_BY UF_FLAG_PUBLIC, // UNIT_FIELD_SUMMONED_BY UF_FLAG_PUBLIC, // UNIT_FIELD_CREATED_BY UF_FLAG_PUBLIC, // UNIT_FIELD_CREATED_BY UF_FLAG_PUBLIC, // UNIT_FIELD_DEMON_CREATOR UF_FLAG_PUBLIC, // UNIT_FIELD_DEMON_CREATOR UF_FLAG_PUBLIC, // UNIT_FIELD_TARGET UF_FLAG_PUBLIC, // UNIT_FIELD_TARGET UF_FLAG_PUBLIC, // UNIT_FIELD_BATTLE_PET_COMPANION_GUID UF_FLAG_PUBLIC, // UNIT_FIELD_BATTLE_PET_COMPANION_GUID UF_FLAG_PUBLIC | UF_FLAG_URGENT, // UNIT_FIELD_CHANNEL_OBJECT UF_FLAG_PUBLIC | UF_FLAG_URGENT, // UNIT_FIELD_CHANNEL_OBJECT UF_FLAG_PUBLIC | UF_FLAG_URGENT, // UNIT_FIELD_CHANNEL_SPELL UF_FLAG_PUBLIC, // UNIT_FIELD_SUMMONED_BY_HOME_REALM UF_FLAG_PUBLIC, // UNIT_FIELD_SEX UF_FLAG_PUBLIC, // UNIT_FIELD_DISPLAY_POWER UF_FLAG_PUBLIC, // UNIT_FIELD_OVERRIDE_DISPLAY_POWER_ID UF_FLAG_PUBLIC, // UNIT_FIELD_HEALTH UF_FLAG_PUBLIC, // UNIT_FIELD_POWER UF_FLAG_PUBLIC, // UNIT_FIELD_POWER UF_FLAG_PUBLIC, // UNIT_FIELD_POWER UF_FLAG_PUBLIC, // UNIT_FIELD_POWER UF_FLAG_PUBLIC, // UNIT_FIELD_POWER UF_FLAG_PUBLIC, // UNIT_FIELD_MAX_HEALTH UF_FLAG_PUBLIC, // UNIT_FIELD_MAX_POWER UF_FLAG_PUBLIC, // UNIT_FIELD_MAX_POWER UF_FLAG_PUBLIC, // UNIT_FIELD_MAX_POWER UF_FLAG_PUBLIC, // UNIT_FIELD_MAX_POWER UF_FLAG_PUBLIC, // UNIT_FIELD_MAX_POWER UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_ALL_UNITS, // UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_ALL_UNITS, // UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_ALL_UNITS, // UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_ALL_UNITS, // UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_ALL_UNITS, // UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_ALL_UNITS, // UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_ALL_UNITS, // UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_ALL_UNITS, // UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_ALL_UNITS, // UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_ALL_UNITS, // UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER UF_FLAG_PUBLIC, // UNIT_FIELD_LEVEL UF_FLAG_PUBLIC, // UNIT_FIELD_EFFECTIVE_LEVEL UF_FLAG_PUBLIC, // UNIT_FIELD_FACTION_TEMPLATE UF_FLAG_PUBLIC, // UNIT_FIELD_VIRTUAL_ITEM_ID UF_FLAG_PUBLIC, // UNIT_FIELD_VIRTUAL_ITEM_ID UF_FLAG_PUBLIC, // UNIT_FIELD_VIRTUAL_ITEM_ID UF_FLAG_PUBLIC, // UNIT_FIELD_FLAGS UF_FLAG_PUBLIC, // UNIT_FIELD_FLAGS2 UF_FLAG_PUBLIC, // UNIT_FIELD_AURA_STATE UF_FLAG_PUBLIC, // UNIT_FIELD_ATTACK_ROUND_BASE_TIME UF_FLAG_PUBLIC, // UNIT_FIELD_ATTACK_ROUND_BASE_TIME UF_FLAG_PRIVATE, // UNIT_FIELD_RANGED_ATTACK_ROUND_BASE_TIME UF_FLAG_PUBLIC, // UNIT_FIELD_BOUNDING_RADIUS UF_FLAG_PUBLIC, // UNIT_FIELD_COMBAT_REACH UF_FLAG_VIEWER_DEPENDENT | UF_FLAG_URGENT, // UNIT_FIELD_DISPLAY_ID UF_FLAG_PUBLIC | UF_FLAG_URGENT, // UNIT_FIELD_NATIVE_DISPLAY_ID UF_FLAG_PUBLIC | UF_FLAG_URGENT, // UNIT_FIELD_MOUNT_DISPLAY_ID UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_EMPATH, // UNIT_FIELD_MIN_DAMAGE UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_EMPATH, // UNIT_FIELD_MAX_DAMAGE UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_EMPATH, // UNIT_FIELD_MIN_OFF_HAND_DAMAGE UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_EMPATH, // UNIT_FIELD_MAX_OFF_HAND_DAMAGE UF_FLAG_PUBLIC, // UNIT_FIELD_ANIM_TIER UF_FLAG_PUBLIC, // UNIT_FIELD_PET_NUMBER UF_FLAG_PUBLIC, // UNIT_FIELD_PET_NAME_TIMESTAMP UF_FLAG_OWNER, // UNIT_FIELD_PET_EXPERIENCE UF_FLAG_OWNER, // UNIT_FIELD_PET_NEXT_LEVEL_EXPERIENCE UF_FLAG_PUBLIC, // UNIT_FIELD_MOD_CASTING_SPEED UF_FLAG_PUBLIC, // UNIT_FIELD_MOD_SPELL_HASTE UF_FLAG_PUBLIC, // UNIT_FIELD_MOD_HASTE UF_FLAG_PUBLIC, // UNIT_FIELD_MOD_RANGED_HASTE UF_FLAG_PUBLIC, // UNIT_FIELD_MOD_HASTE_REGEN UF_FLAG_PUBLIC, // UNIT_FIELD_CREATED_BY_SPELL UF_FLAG_PUBLIC | UF_FLAG_VIEWER_DEPENDENT, // UNIT_FIELD_NPC_FLAGS UF_FLAG_PUBLIC, // UNIT_FIELD_NPC_FLAGS UF_FLAG_PUBLIC, // UNIT_FIELD_EMOTE_STATE UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_STATS UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_STATS UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_STATS UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_STATS UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_STATS UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_STAT_POS_BUFF UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_STAT_POS_BUFF UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_STAT_POS_BUFF UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_STAT_POS_BUFF UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_STAT_POS_BUFF UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_STAT_NEG_BUFF UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_STAT_NEG_BUFF UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_STAT_NEG_BUFF UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_STAT_NEG_BUFF UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_STAT_NEG_BUFF UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_EMPATH, // UNIT_FIELD_RESISTANCES UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_EMPATH, // UNIT_FIELD_RESISTANCES UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_EMPATH, // UNIT_FIELD_RESISTANCES UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_EMPATH, // UNIT_FIELD_RESISTANCES UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_EMPATH, // UNIT_FIELD_RESISTANCES UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_EMPATH, // UNIT_FIELD_RESISTANCES UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_EMPATH, // UNIT_FIELD_RESISTANCES UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCE_BUFF_MODS_POSITIVE UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCE_BUFF_MODS_POSITIVE UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCE_BUFF_MODS_POSITIVE UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCE_BUFF_MODS_POSITIVE UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCE_BUFF_MODS_POSITIVE UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCE_BUFF_MODS_POSITIVE UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCE_BUFF_MODS_POSITIVE UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCE_BUFF_MODS_NEGATIVE UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCE_BUFF_MODS_NEGATIVE UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCE_BUFF_MODS_NEGATIVE UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCE_BUFF_MODS_NEGATIVE UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCE_BUFF_MODS_NEGATIVE UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCE_BUFF_MODS_NEGATIVE UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCE_BUFF_MODS_NEGATIVE UF_FLAG_PUBLIC, // UNIT_FIELD_BASE_MANA UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_BASE_HEALTH UF_FLAG_PUBLIC, // UNIT_FIELD_SHAPESHIFT_FORM UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_ATTACK_POWER UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_ATTACK_POWER_MOD_POS UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_ATTACK_POWER_MOD_NEG UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_ATTACK_POWER_MULTIPLIER UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RANGED_ATTACK_POWER UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RANGED_ATTACK_POWER_MOD_POS UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RANGED_ATTACK_POWER_MOD_NEG UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_MIN_RANGED_DAMAGE UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_MAX_RANGED_DAMAGE UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MODIFIER UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MODIFIER UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MODIFIER UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MODIFIER UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MODIFIER UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MODIFIER UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MODIFIER UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MULTIPLIER UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MULTIPLIER UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MULTIPLIER UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MULTIPLIER UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MULTIPLIER UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MULTIPLIER UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MULTIPLIER UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_MAX_HEALTH_MODIFIER UF_FLAG_PUBLIC, // UNIT_FIELD_HOVER_HEIGHT UF_FLAG_PUBLIC, // UNIT_FIELD_MIN_ITEM_LEVEL UF_FLAG_PUBLIC, // UNIT_FIELD_MAX_ITEM_LEVEL UF_FLAG_PUBLIC, // UNIT_FIELD_WILD_BATTLE_PET_LEVEL UF_FLAG_PUBLIC, // UNIT_FIELD_BATTLE_PET_COMPANION_NAME_TIMESTAMP UF_FLAG_PUBLIC, // UNIT_FIELD_INTERACT_SPELL_ID UF_FLAG_PUBLIC, // PLAYER_FIELD_DUEL_ARBITER UF_FLAG_PUBLIC, // PLAYER_FIELD_DUEL_ARBITER UF_FLAG_PUBLIC, // PLAYER_FIELD_PLAYER_FLAGS UF_FLAG_PUBLIC, // PLAYER_FIELD_GUILD_RANK_ID UF_FLAG_PUBLIC, // PLAYER_FIELD_GUILD_DELETE_DATE UF_FLAG_PUBLIC, // PLAYER_FIELD_GUILD_LEVEL UF_FLAG_PUBLIC, // PLAYER_FIELD_HAIR_COLOR_ID UF_FLAG_PUBLIC, // PLAYER_FIELD_REST_STATE UF_FLAG_PUBLIC, // PLAYER_FIELD_ARENA_FACTION UF_FLAG_PUBLIC, // PLAYER_FIELD_DUEL_TEAM UF_FLAG_PUBLIC, // PLAYER_FIELD_GUILD_TIME_STAMP UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS UF_FLAG_PUBLIC, // PLAYER_FIELD_PLAYER_TITLE UF_FLAG_PUBLIC, // PLAYER_FIELD_FAKE_INEBRIATION UF_FLAG_PUBLIC, // PLAYER_FIELD_VIRTUAL_PLAYER_REALM UF_FLAG_PUBLIC, // PLAYER_FIELD_CURRENT_SPEC_ID UF_FLAG_PUBLIC, // PLAYER_FIELD_TAXI_MOUNT_ANIM_KIT_ID UF_FLAG_PUBLIC, // PLAYER_FIELD_CURRENT_BATTLE_PET_BREED_QUALITY UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_FARSIGHT_OBJECT UF_FLAG_PRIVATE, // PLAYER_FIELD_FARSIGHT_OBJECT UF_FLAG_PRIVATE, // PLAYER_FIELD_KNOWN_TITLES UF_FLAG_PRIVATE, // PLAYER_FIELD_KNOWN_TITLES UF_FLAG_PRIVATE, // PLAYER_FIELD_KNOWN_TITLES UF_FLAG_PRIVATE, // PLAYER_FIELD_KNOWN_TITLES UF_FLAG_PRIVATE, // PLAYER_FIELD_KNOWN_TITLES UF_FLAG_PRIVATE, // PLAYER_FIELD_KNOWN_TITLES UF_FLAG_PRIVATE, // PLAYER_FIELD_KNOWN_TITLES UF_FLAG_PRIVATE, // PLAYER_FIELD_KNOWN_TITLES UF_FLAG_PRIVATE, // PLAYER_FIELD_KNOWN_TITLES UF_FLAG_PRIVATE, // PLAYER_FIELD_KNOWN_TITLES UF_FLAG_PRIVATE, // PLAYER_FIELD_COINAGE UF_FLAG_PRIVATE, // PLAYER_FIELD_COINAGE UF_FLAG_PRIVATE, // PLAYER_FIELD_XP UF_FLAG_PRIVATE, // PLAYER_FIELD_NEXT_LEVEL_XP UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL UF_FLAG_PRIVATE, // PLAYER_FIELD_CHARACTER_POINTS UF_FLAG_PRIVATE, // PLAYER_FIELD_MAX_TALENT_TIERS UF_FLAG_PRIVATE, // PLAYER_FIELD_TRACK_CREATURE_MASK UF_FLAG_PRIVATE, // PLAYER_FIELD_TRACK_RESOURCE_MASK UF_FLAG_PRIVATE, // PLAYER_FIELD_MAINHAND_EXPERTISE UF_FLAG_PRIVATE, // PLAYER_FIELD_OFFHAND_EXPERTISE UF_FLAG_PRIVATE, // PLAYER_FIELD_RANGED_EXPERTISE UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATING_EXPERTISE UF_FLAG_PRIVATE, // PLAYER_FIELD_BLOCK_PERCENTAGE UF_FLAG_PRIVATE, // PLAYER_FIELD_DODGE_PERCENTAGE UF_FLAG_PRIVATE, // PLAYER_FIELD_PARRY_PERCENTAGE UF_FLAG_PRIVATE, // PLAYER_FIELD_CRIT_PERCENTAGE UF_FLAG_PRIVATE, // PLAYER_FIELD_RANGED_CRIT_PERCENTAGE UF_FLAG_PRIVATE, // PLAYER_FIELD_OFFHAND_CRIT_PERCENTAGE UF_FLAG_PRIVATE, // PLAYER_FIELD_SPELL_CRIT_PERCENTAGE UF_FLAG_PRIVATE, // PLAYER_FIELD_SPELL_CRIT_PERCENTAGE UF_FLAG_PRIVATE, // PLAYER_FIELD_SPELL_CRIT_PERCENTAGE UF_FLAG_PRIVATE, // PLAYER_FIELD_SPELL_CRIT_PERCENTAGE UF_FLAG_PRIVATE, // PLAYER_FIELD_SPELL_CRIT_PERCENTAGE UF_FLAG_PRIVATE, // PLAYER_FIELD_SPELL_CRIT_PERCENTAGE UF_FLAG_PRIVATE, // PLAYER_FIELD_SPELL_CRIT_PERCENTAGE UF_FLAG_PRIVATE, // PLAYER_FIELD_SHIELD_BLOCK UF_FLAG_PRIVATE, // PLAYER_FIELD_SHIELD_BLOCK_CRIT_PERCENTAGE UF_FLAG_PRIVATE, // PLAYER_FIELD_MASTERY UF_FLAG_PRIVATE, // PLAYER_FIELD_PVP_POWER_DAMAGE UF_FLAG_PRIVATE, // PLAYER_FIELD_PVP_POWER_HEALING UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES UF_FLAG_PRIVATE, // PLAYER_FIELD_REST_STATE_BONUS_POOL UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_DAMAGE_DONE_POS UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_DAMAGE_DONE_POS UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_DAMAGE_DONE_POS UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_DAMAGE_DONE_POS UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_DAMAGE_DONE_POS UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_DAMAGE_DONE_POS UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_DAMAGE_DONE_POS UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_DAMAGE_DONE_NEG UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_DAMAGE_DONE_NEG UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_DAMAGE_DONE_NEG UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_DAMAGE_DONE_NEG UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_DAMAGE_DONE_NEG UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_DAMAGE_DONE_NEG UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_DAMAGE_DONE_NEG UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_DAMAGE_DONE_PERCENT UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_DAMAGE_DONE_PERCENT UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_DAMAGE_DONE_PERCENT UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_DAMAGE_DONE_PERCENT UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_DAMAGE_DONE_PERCENT UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_DAMAGE_DONE_PERCENT UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_DAMAGE_DONE_PERCENT UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_HEALING_DONE_POS UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_HEALING_PERCENT UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_HEALING_DONE_PERCENT UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_PERIODIC_HEALING_DONE_PERCENT UF_FLAG_PRIVATE, // PLAYER_FIELD_WEAPON_DMG_MULTIPLIERS UF_FLAG_PRIVATE, // PLAYER_FIELD_WEAPON_DMG_MULTIPLIERS UF_FLAG_PRIVATE, // PLAYER_FIELD_WEAPON_DMG_MULTIPLIERS UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_SPELL_POWER_PERCENT UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_RESILIENCE_PERCENT UF_FLAG_PRIVATE, // PLAYER_FIELD_OVERRIDE_SPELL_POWER_BY_APPERCENT UF_FLAG_PRIVATE, // PLAYER_FIELD_OVERRIDE_APBY_SPELL_POWER_PERCENT UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_TARGET_RESISTANCE UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE UF_FLAG_PRIVATE, // PLAYER_FIELD_LIFETIME_MAX_RANK UF_FLAG_PRIVATE, // PLAYER_FIELD_SELF_RES_SPELL UF_FLAG_PRIVATE, // PLAYER_FIELD_PVP_MEDALS UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_PRICE UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_PRICE UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_PRICE UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_PRICE UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_PRICE UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_PRICE UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_PRICE UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_PRICE UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_PRICE UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_PRICE UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_PRICE UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_PRICE UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_TIMESTAMP UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_TIMESTAMP UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_TIMESTAMP UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_TIMESTAMP UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_TIMESTAMP UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_TIMESTAMP UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_TIMESTAMP UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_TIMESTAMP UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_TIMESTAMP UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_TIMESTAMP UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_TIMESTAMP UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_TIMESTAMP UF_FLAG_PRIVATE, // PLAYER_FIELD_YESTERDAY_HONORABLE_KILLS UF_FLAG_PRIVATE, // PLAYER_FIELD_LIFETIME_HONORABLE_KILLS UF_FLAG_PRIVATE, // PLAYER_FIELD_WATCHED_FACTION_INDEX UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATINGS UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATINGS UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATINGS UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATINGS UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATINGS UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATINGS UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATINGS UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATINGS UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATINGS UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATINGS UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATINGS UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATINGS UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATINGS UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATINGS UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATINGS UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATINGS UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATINGS UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATINGS UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATINGS UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATINGS UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATINGS UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATINGS UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATINGS UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATINGS UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATINGS UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATINGS UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATINGS UF_FLAG_PRIVATE, // PLAYER_FIELD_PVP_INFO UF_FLAG_PRIVATE, // PLAYER_FIELD_PVP_INFO UF_FLAG_PRIVATE, // PLAYER_FIELD_PVP_INFO UF_FLAG_PRIVATE, // PLAYER_FIELD_PVP_INFO UF_FLAG_PRIVATE, // PLAYER_FIELD_PVP_INFO UF_FLAG_PRIVATE, // PLAYER_FIELD_PVP_INFO UF_FLAG_PRIVATE, // PLAYER_FIELD_PVP_INFO UF_FLAG_PRIVATE, // PLAYER_FIELD_PVP_INFO UF_FLAG_PRIVATE, // PLAYER_FIELD_PVP_INFO UF_FLAG_PRIVATE, // PLAYER_FIELD_PVP_INFO UF_FLAG_PRIVATE, // PLAYER_FIELD_PVP_INFO UF_FLAG_PRIVATE, // PLAYER_FIELD_PVP_INFO UF_FLAG_PRIVATE, // PLAYER_FIELD_PVP_INFO UF_FLAG_PRIVATE, // PLAYER_FIELD_PVP_INFO UF_FLAG_PRIVATE, // PLAYER_FIELD_PVP_INFO UF_FLAG_PRIVATE, // PLAYER_FIELD_PVP_INFO UF_FLAG_PRIVATE, // PLAYER_FIELD_PVP_INFO UF_FLAG_PRIVATE, // PLAYER_FIELD_PVP_INFO UF_FLAG_PRIVATE, // PLAYER_FIELD_PVP_INFO UF_FLAG_PRIVATE, // PLAYER_FIELD_PVP_INFO UF_FLAG_PRIVATE, // PLAYER_FIELD_PVP_INFO UF_FLAG_PRIVATE, // PLAYER_FIELD_PVP_INFO UF_FLAG_PRIVATE, // PLAYER_FIELD_PVP_INFO UF_FLAG_PRIVATE, // PLAYER_FIELD_PVP_INFO UF_FLAG_PRIVATE, // PLAYER_FIELD_MAX_LEVEL UF_FLAG_PRIVATE, // PLAYER_FIELD_RUNE_REGEN UF_FLAG_PRIVATE, // PLAYER_FIELD_RUNE_REGEN UF_FLAG_PRIVATE, // PLAYER_FIELD_RUNE_REGEN UF_FLAG_PRIVATE, // PLAYER_FIELD_RUNE_REGEN UF_FLAG_PRIVATE, // PLAYER_FIELD_NO_REAGENT_COST_MASK UF_FLAG_PRIVATE, // PLAYER_FIELD_NO_REAGENT_COST_MASK UF_FLAG_PRIVATE, // PLAYER_FIELD_NO_REAGENT_COST_MASK UF_FLAG_PRIVATE, // PLAYER_FIELD_NO_REAGENT_COST_MASK UF_FLAG_PRIVATE, // PLAYER_FIELD_GLYPH_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_GLYPH_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_GLYPH_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_GLYPH_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_GLYPH_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_GLYPH_SLOTS UF_FLAG_PRIVATE, // PLAYER_FIELD_GLYPHS UF_FLAG_PRIVATE, // PLAYER_FIELD_GLYPHS UF_FLAG_PRIVATE, // PLAYER_FIELD_GLYPHS UF_FLAG_PRIVATE, // PLAYER_FIELD_GLYPHS UF_FLAG_PRIVATE, // PLAYER_FIELD_GLYPHS UF_FLAG_PRIVATE, // PLAYER_FIELD_GLYPHS UF_FLAG_PRIVATE, // PLAYER_FIELD_GLYPH_SLOTS_ENABLED UF_FLAG_PRIVATE, // PLAYER_FIELD_PET_SPELL_POWER UF_FLAG_PRIVATE, // PLAYER_FIELD_RESEARCHING UF_FLAG_PRIVATE, // PLAYER_FIELD_RESEARCHING UF_FLAG_PRIVATE, // PLAYER_FIELD_RESEARCHING UF_FLAG_PRIVATE, // PLAYER_FIELD_RESEARCHING UF_FLAG_PRIVATE, // PLAYER_FIELD_RESEARCHING UF_FLAG_PRIVATE, // PLAYER_FIELD_RESEARCHING UF_FLAG_PRIVATE, // PLAYER_FIELD_RESEARCHING UF_FLAG_PRIVATE, // PLAYER_FIELD_RESEARCHING UF_FLAG_PRIVATE, // PLAYER_FIELD_PROFESSION_SKILL_LINE UF_FLAG_PRIVATE, // PLAYER_FIELD_PROFESSION_SKILL_LINE UF_FLAG_PRIVATE, // PLAYER_FIELD_UI_HIT_MODIFIER UF_FLAG_PRIVATE, // PLAYER_FIELD_UI_SPELL_HIT_MODIFIER UF_FLAG_PRIVATE, // PLAYER_FIELD_HOME_REALM_TIME_OFFSET UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_PET_HASTE UF_FLAG_PRIVATE, // PLAYER_FIELD_SUMMONED_BATTLE_PET_GUID UF_FLAG_PRIVATE, // PLAYER_FIELD_SUMMONED_BATTLE_PET_GUID UF_FLAG_PRIVATE | UF_FLAG_URGENT_SELF_ONLY, // PLAYER_FIELD_OVERRIDE_SPELLS_ID UF_FLAG_PRIVATE, // PLAYER_FIELD_LFG_BONUS_FACTION_ID UF_FLAG_PRIVATE, // PLAYER_FIELD_LOOT_SPEC_ID UF_FLAG_PRIVATE | UF_FLAG_URGENT_SELF_ONLY, // PLAYER_FIELD_OVERRIDE_ZONE_PVPTYPE UF_FLAG_PRIVATE, // PLAYER_FIELD_ITEM_LEVEL_DELTA }; // > Object > GameObject uint32 GameObjectUpdateFieldFlags[GAMEOBJECT_END] = { UF_FLAG_PUBLIC, // OBJECT_FIELD_GUID UF_FLAG_PUBLIC, // OBJECT_FIELD_GUID UF_FLAG_PUBLIC, // OBJECT_FIELD_DATA UF_FLAG_PUBLIC, // OBJECT_FIELD_DATA UF_FLAG_PUBLIC, // OBJECT_FIELD_TYPE UF_FLAG_VIEWER_DEPENDENT, // OBJECT_FIELD_ENTRY_ID UF_FLAG_VIEWER_DEPENDENT | UF_FLAG_URGENT, // OBJECT_FIELD_DYNAMIC_FLAGS UF_FLAG_PUBLIC, // OBJECT_FIELD_SCALE UF_FLAG_PUBLIC, // GAMEOBJECT_FIELD_CREATED_BY UF_FLAG_PUBLIC, // GAMEOBJECT_FIELD_CREATED_BY UF_FLAG_PUBLIC, // GAMEOBJECT_FIELD_DISPLAY_ID UF_FLAG_PUBLIC | UF_FLAG_URGENT, // GAMEOBJECT_FIELD_FLAGS UF_FLAG_PUBLIC, // GAMEOBJECT_FIELD_PARENT_ROTATION UF_FLAG_PUBLIC, // GAMEOBJECT_FIELD_PARENT_ROTATION UF_FLAG_PUBLIC, // GAMEOBJECT_FIELD_PARENT_ROTATION UF_FLAG_PUBLIC, // GAMEOBJECT_FIELD_PARENT_ROTATION UF_FLAG_PUBLIC, // GAMEOBJECT_FIELD_FACTION_TEMPLATE UF_FLAG_PUBLIC, // GAMEOBJECT_FIELD_LEVEL UF_FLAG_PUBLIC | UF_FLAG_URGENT, // GAMEOBJECT_FIELD_PERCENT_HEALTH UF_FLAG_PUBLIC | UF_FLAG_URGENT, // GAMEOBJECT_FIELD_STATE_SPELL_VISUAL_ID }; // > Object > DynamicObject uint32 DynamicObjectUpdateFieldFlags[DYNAMICOBJECT_END] = { UF_FLAG_PUBLIC, // OBJECT_FIELD_GUID UF_FLAG_PUBLIC, // OBJECT_FIELD_GUID UF_FLAG_PUBLIC, // OBJECT_FIELD_DATA UF_FLAG_PUBLIC, // OBJECT_FIELD_DATA UF_FLAG_PUBLIC, // OBJECT_FIELD_TYPE UF_FLAG_VIEWER_DEPENDENT, // OBJECT_FIELD_ENTRY_ID UF_FLAG_VIEWER_DEPENDENT | UF_FLAG_URGENT, // OBJECT_FIELD_DYNAMIC_FLAGS UF_FLAG_PUBLIC, // OBJECT_FIELD_SCALE UF_FLAG_PUBLIC, // DYNAMICOBJECT_FIELD_CASTER UF_FLAG_PUBLIC, // DYNAMICOBJECT_FIELD_CASTER UF_FLAG_VIEWER_DEPENDENT, // DYNAMICOBJECT_FIELD_TYPE_AND_VISUAL_ID UF_FLAG_PUBLIC, // DYNAMICOBJECT_FIELD_SPELL_ID UF_FLAG_PUBLIC, // DYNAMICOBJECT_FIELD_RADIUS UF_FLAG_PUBLIC, // DYNAMICOBJECT_FIELD_CAST_TIME }; // > Object > Corpse uint32 CorpseUpdateFieldFlags[CORPSE_END] = { UF_FLAG_PUBLIC, // OBJECT_FIELD_GUID UF_FLAG_PUBLIC, // OBJECT_FIELD_GUID UF_FLAG_PUBLIC, // OBJECT_FIELD_DATA UF_FLAG_PUBLIC, // OBJECT_FIELD_DATA UF_FLAG_PUBLIC, // OBJECT_FIELD_TYPE UF_FLAG_VIEWER_DEPENDENT, // OBJECT_FIELD_ENTRY_ID UF_FLAG_VIEWER_DEPENDENT | UF_FLAG_URGENT, // OBJECT_FIELD_DYNAMIC_FLAGS UF_FLAG_PUBLIC, // OBJECT_FIELD_SCALE UF_FLAG_PUBLIC, // CORPSE_FIELD_OWNER UF_FLAG_PUBLIC, // CORPSE_FIELD_OWNER UF_FLAG_PUBLIC, // CORPSE_FIELD_PARTY_GUID UF_FLAG_PUBLIC, // CORPSE_FIELD_PARTY_GUID UF_FLAG_PUBLIC, // CORPSE_FIELD_DISPLAY_ID UF_FLAG_PUBLIC, // CORPSE_FIELD_ITEMS UF_FLAG_PUBLIC, // CORPSE_FIELD_ITEMS UF_FLAG_PUBLIC, // CORPSE_FIELD_ITEMS UF_FLAG_PUBLIC, // CORPSE_FIELD_ITEMS UF_FLAG_PUBLIC, // CORPSE_FIELD_ITEMS UF_FLAG_PUBLIC, // CORPSE_FIELD_ITEMS UF_FLAG_PUBLIC, // CORPSE_FIELD_ITEMS UF_FLAG_PUBLIC, // CORPSE_FIELD_ITEMS UF_FLAG_PUBLIC, // CORPSE_FIELD_ITEMS UF_FLAG_PUBLIC, // CORPSE_FIELD_ITEMS UF_FLAG_PUBLIC, // CORPSE_FIELD_ITEMS UF_FLAG_PUBLIC, // CORPSE_FIELD_ITEMS UF_FLAG_PUBLIC, // CORPSE_FIELD_ITEMS UF_FLAG_PUBLIC, // CORPSE_FIELD_ITEMS UF_FLAG_PUBLIC, // CORPSE_FIELD_ITEMS UF_FLAG_PUBLIC, // CORPSE_FIELD_ITEMS UF_FLAG_PUBLIC, // CORPSE_FIELD_ITEMS UF_FLAG_PUBLIC, // CORPSE_FIELD_ITEMS UF_FLAG_PUBLIC, // CORPSE_FIELD_ITEMS UF_FLAG_PUBLIC, // CORPSE_FIELD_SKIN_ID UF_FLAG_PUBLIC, // CORPSE_FIELD_FACIAL_HAIR_STYLE_ID UF_FLAG_PUBLIC, // CORPSE_FIELD_FLAGS UF_FLAG_VIEWER_DEPENDENT, // CORPSE_FIELD_DYNAMIC_FLAGS }; // > Object > AreaTrigger uint32 AreaTriggerUpdateFieldFlags[AREATRIGGER_END] = { UF_FLAG_PUBLIC, // OBJECT_FIELD_GUID UF_FLAG_PUBLIC, // OBJECT_FIELD_GUID UF_FLAG_PUBLIC, // OBJECT_FIELD_DATA UF_FLAG_PUBLIC, // OBJECT_FIELD_DATA UF_FLAG_PUBLIC, // OBJECT_FIELD_TYPE UF_FLAG_VIEWER_DEPENDENT, // OBJECT_FIELD_ENTRY_ID UF_FLAG_VIEWER_DEPENDENT | UF_FLAG_URGENT, // OBJECT_FIELD_DYNAMIC_FLAGS UF_FLAG_PUBLIC, // OBJECT_FIELD_SCALE UF_FLAG_PUBLIC, // AREATRIGGER_FIELD_CASTER UF_FLAG_PUBLIC, // AREATRIGGER_FIELD_CASTER UF_FLAG_PUBLIC, // AREATRIGGER_FIELD_DURATION UF_FLAG_PUBLIC, // AREATRIGGER_FIELD_SPELL_ID UF_FLAG_VIEWER_DEPENDENT, // AREATRIGGER_FIELD_SPELL_VISUAL_ID UF_FLAG_PUBLIC | UF_FLAG_URGENT, // AREATRIGGER_FIELD_EXPLICIT_SCALE }; // > Object > SceneObject uint32 SceneObjectUpdateFieldFlags[SCENE_END] = { UF_FLAG_PUBLIC, // OBJECT_FIELD_GUID UF_FLAG_PUBLIC, // OBJECT_FIELD_GUID UF_FLAG_PUBLIC, // OBJECT_FIELD_DATA UF_FLAG_PUBLIC, // OBJECT_FIELD_DATA UF_FLAG_PUBLIC, // OBJECT_FIELD_TYPE UF_FLAG_VIEWER_DEPENDENT, // OBJECT_FIELD_ENTRY_ID UF_FLAG_VIEWER_DEPENDENT | UF_FLAG_URGENT, // OBJECT_FIELD_DYNAMIC_FLAGS UF_FLAG_PUBLIC, // OBJECT_FIELD_SCALE UF_FLAG_PUBLIC, // SCENEOBJECT_FIELD_SCRIPT_PACKAGE_ID UF_FLAG_PUBLIC, // SCENEOBJECT_FIELD_RND_SEED_VAL UF_FLAG_PUBLIC, // SCENEOBJECT_FIELD_CREATED_BY UF_FLAG_PUBLIC, // SCENEOBJECT_FIELD_CREATED_BY UF_FLAG_PUBLIC, // SCENEOBJECT_FIELD_SCENE_TYPE }; #endif
Java
package gitmad.bitter.ui; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import gitmad.bitter.R; import gitmad.bitter.model.Comment; import gitmad.bitter.model.User; import java.util.Map; /** * Created by prabh on 10/19/2015. */ public class CommentAdapter extends ArrayAdapter<Comment> { private Comment[] comments; private Map<Comment, User> commentAuthors; public CommentAdapter(Context context, Comment[] comments, Map<Comment, User> commentAuthors) { super(context, 0, comments); // TODO is the zero here correct? this.comments = comments; this.commentAuthors = commentAuthors; } public View getView(int position, View convertView, ViewGroup parent) { Comment comment = comments[position]; if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(R.layout .view_comment, parent, false); } TextView userText = (TextView) convertView.findViewById(R.id.user_text); TextView commentText = (TextView) convertView.findViewById(R.id .comment_text); userText.setText(commentAuthors.get(comment).getName()); commentText.setText(comment.getText()); return convertView; } }
Java
<?php if (!defined ('UPDRAFTPLUS_DIR')) die('No direct access allowed'); // Admin-area code lives here. This gets called in admin_menu, earlier than admin_init global $updraftplus_admin; if (!is_a($updraftplus_admin, 'UpdraftPlus_Admin')) $updraftplus_admin = new UpdraftPlus_Admin(); class UpdraftPlus_Admin { public $logged = array(); public function __construct() { $this->admin_init(); } private function setup_all_admin_notices_global($service){ if ('googledrive' === $service || (is_array($service) && in_array('googledrive', $service))) { $opts = UpdraftPlus_Options::get_updraft_option('updraft_googledrive'); if (empty($opts)) { $clientid = UpdraftPlus_Options::get_updraft_option('updraft_googledrive_clientid', ''); $token = UpdraftPlus_Options::get_updraft_option('updraft_googledrive_token', ''); } else { $clientid = $opts['clientid']; $token = (empty($opts['token'])) ? '' : $opts['token']; } if (!empty($clientid) && empty($token)) add_action('all_admin_notices', array($this,'show_admin_warning_googledrive')); } if ('googlecloud' === $service || (is_array($service) && in_array('googlecloud', $service))) { $opts = UpdraftPlus_Options::get_updraft_option('updraft_googlecloud'); if (!empty($opts)) { $clientid = $opts['clientid']; $token = (empty($opts['token'])) ? '' : $opts['token']; } if (!empty($clientid) && empty($token)) add_action('all_admin_notices', array($this,'show_admin_warning_googlecloud')); } if ('dropbox' === $service || (is_array($service) && in_array('dropbox', $service))) { $opts = UpdraftPlus_Options::get_updraft_option('updraft_dropbox'); if (empty($opts['tk_request_token'])) { add_action('all_admin_notices', array($this,'show_admin_warning_dropbox') ); } } if ('bitcasa' === $service || (is_array($service) && in_array('bitcasa', $service))) { $opts = UpdraftPlus_Options::get_updraft_option('updraft_bitcasa'); if (!empty($opts['clientid']) && !empty($opts['secret']) && empty($opts['token'])) add_action('all_admin_notices', array($this,'show_admin_warning_bitcasa') ); } if ('copycom' === $service || (is_array($service) && in_array('copycom', $service))) { $opts = UpdraftPlus_Options::get_updraft_option('updraft_copycom'); if (!empty($opts['clientid']) && !empty($opts['secret']) && empty($opts['token'])) add_action('all_admin_notices', array($this,'show_admin_warning_copycom') ); } if ('onedrive' === $service || (is_array($service) && in_array('onedrive', $service))) { $opts = UpdraftPlus_Options::get_updraft_option('updraft_onedrive'); if (!empty($opts['clientid']) && !empty($opts['secret']) && empty($opts['refresh_token'])) add_action('all_admin_notices', array($this,'show_admin_warning_onedrive') ); } if ('updraftvault' === $service || (is_array($service) && in_array('updraftvault', $service))) { $vault_settings = UpdraftPlus_Options::get_updraft_option('updraft_updraftvault'); $connected = (is_array($vault_settings) && !empty($vault_settings['token']) && !empty($vault_settings['email'])) ? true : false; if (!$connected) add_action('all_admin_notices', array($this,'show_admin_warning_updraftvault') ); } if ($this->disk_space_check(1048576*35) === false) add_action('all_admin_notices', array($this, 'show_admin_warning_diskspace')); } private function setup_all_admin_notices_udonly($service, $override = false){ global $wp_version; if (UpdraftPlus_Options::user_can_manage() && defined('DISABLE_WP_CRON') && DISABLE_WP_CRON == true) { add_action('all_admin_notices', array($this, 'show_admin_warning_disabledcron')); } if (UpdraftPlus_Options::get_updraft_option('updraft_debug_mode')) { @ini_set('display_errors',1); @error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED); add_action('all_admin_notices', array($this, 'show_admin_debug_warning')); } if (null === UpdraftPlus_Options::get_updraft_option('updraft_interval')) { add_action('all_admin_notices', array($this, 'show_admin_nosettings_warning')); $this->no_settings_warning = true; } # Avoid false positives, by attempting to raise the limit (as happens when we actually do a backup) @set_time_limit(UPDRAFTPLUS_SET_TIME_LIMIT); $max_execution_time = (int)@ini_get('max_execution_time'); if ($max_execution_time>0 && $max_execution_time<20) { add_action('all_admin_notices', array($this, 'show_admin_warning_execution_time')); } // LiteSpeed has a generic problem with terminating cron jobs if (isset($_SERVER['SERVER_SOFTWARE']) && strpos($_SERVER['SERVER_SOFTWARE'], 'LiteSpeed') !== false) { if (!is_file(ABSPATH.'.htaccess') || !preg_match('/noabort/i', file_get_contents(ABSPATH.'.htaccess'))) { add_action('all_admin_notices', array($this, 'show_admin_warning_litespeed')); } } if (version_compare($wp_version, '3.2', '<')) add_action('all_admin_notices', array($this, 'show_admin_warning_wordpressversion')); } /* private function reset_all_updraft_admin_notices() { $actions_to_remove = array('show_admin_warning_googledrive', 'show_admin_warning_googlecloud', 'show_admin_warning_dropbox', 'show_admin_warning_bitcasa', 'show_admin_warning_copycom', 'show_admin_warning_onedrive', 'show_admin_warning_updraftvault', 'show_admin_warning_diskspace', 'show_admin_warning_disabledcron', 'show_admin_debug_warning', 'show_admin_warning_execution_time', 'show_admin_warning_litespeed', 'show_admin_warning_wordpressversion'); foreach ($actions_to_remove as $action) { remove_action('all_admin_notices', $action); } } */ //Used to output the information for the next scheduled backup //**// moved to function for the ajax saves private function next_scheduled_backups_output() { // UNIX timestamp $next_scheduled_backup = wp_next_scheduled('updraft_backup'); if ($next_scheduled_backup) { // Convert to GMT $next_scheduled_backup_gmt = gmdate('Y-m-d H:i:s', $next_scheduled_backup); // Convert to blog time zone $next_scheduled_backup = get_date_from_gmt($next_scheduled_backup_gmt, 'D, F j, Y H:i'); // $next_scheduled_backup = date_i18n('D, F j, Y H:i', $next_scheduled_backup); } else { $next_scheduled_backup = __('Nothing currently scheduled', 'updraftplus'); $files_not_scheduled = true; } $next_scheduled_backup_database = wp_next_scheduled('updraft_backup_database'); if (UpdraftPlus_Options::get_updraft_option('updraft_interval_database',UpdraftPlus_Options::get_updraft_option('updraft_interval')) == UpdraftPlus_Options::get_updraft_option('updraft_interval')) { if (isset($files_not_scheduled)) { $next_scheduled_backup_database = $next_scheduled_backup; $database_not_scheduled = true; } else { $next_scheduled_backup_database = __("At the same time as the files backup", 'updraftplus'); $next_scheduled_backup_database_same_time = true; } } else { if ($next_scheduled_backup_database) { // Convert to GMT $next_scheduled_backup_database_gmt = gmdate('Y-m-d H:i:s', $next_scheduled_backup_database); // Convert to blog time zone $next_scheduled_backup_database = get_date_from_gmt($next_scheduled_backup_database_gmt, 'D, F j, Y H:i'); // $next_scheduled_backup_database = date_i18n('D, F j, Y H:i', $next_scheduled_backup_database); } else { $next_scheduled_backup_database = __('Nothing currently scheduled', 'updraftplus'); $database_not_scheduled = true; } } ?> <tr> <?php if (isset($files_not_scheduled) && isset($database_not_scheduled)) { ?> <td colspan="2" class="not-scheduled"><?php _e('Nothing currently scheduled','updraftplus'); ?></td> <?php } else { ?> <td class="updraft_scheduled"><?php echo empty($next_scheduled_backup_database_same_time) ? __('Files','updraftplus') : __('Files and database', 'updraftplus'); ?>:</td><td class="updraft_all-files"><?php echo $next_scheduled_backup; ?></td> </tr> <?php if (empty($next_scheduled_backup_database_same_time)) { ?> <tr> <td class="updraft_scheduled"><?php _e('Database','updraftplus');?>: </td><td class="updraft_all-files"><?php echo $next_scheduled_backup_database; ?></td> </tr> <?php } ?> <?php } } private function admin_init() { add_action('core_upgrade_preamble', array($this, 'core_upgrade_preamble')); add_action('admin_action_upgrade-plugin', array($this, 'admin_action_upgrade_pluginortheme')); add_action('admin_action_upgrade-theme', array($this, 'admin_action_upgrade_pluginortheme')); add_action('admin_head', array($this,'admin_head')); add_filter((is_multisite() ? 'network_admin_' : '').'plugin_action_links', array($this, 'plugin_action_links'), 10, 2); add_action('wp_ajax_updraft_download_backup', array($this, 'updraft_download_backup')); add_action('wp_ajax_updraft_ajax', array($this, 'updraft_ajax_handler')); add_action('wp_ajax_updraft_ajaxrestore', array($this, 'updraft_ajaxrestore')); add_action('wp_ajax_nopriv_updraft_ajaxrestore', array($this, 'updraft_ajaxrestore')); add_action('wp_ajax_plupload_action', array($this, 'plupload_action')); add_action('wp_ajax_plupload_action2', array($this, 'plupload_action2')); add_action('wp_before_admin_bar_render', array($this, 'wp_before_admin_bar_render')); // Add a new Ajax action for saving settings add_action('wp_ajax_updraft_savesettings', array($this, 'updraft_ajax_savesettings')); global $updraftplus, $wp_version, $pagenow; add_filter('updraftplus_dirlist_others', array($updraftplus, 'backup_others_dirlist')); add_filter('updraftplus_dirlist_uploads', array($updraftplus, 'backup_uploads_dirlist')); // First, the checks that are on all (admin) pages: $service = UpdraftPlus_Options::get_updraft_option('updraft_service'); if (UpdraftPlus_Options::user_can_manage()) { $this->print_restore_in_progress_box_if_needed(); // Main dashboard page advert // Since our nonce is printed, make sure they have sufficient credentials if (!file_exists(UPDRAFTPLUS_DIR.'/udaddons') && $pagenow == 'index.php' && current_user_can('update_plugins')) { $dismissed_until = UpdraftPlus_Options::get_updraft_option('updraftplus_dismisseddashnotice', 0); $backup_dir = $updraftplus->backups_dir_location(); // N.B. Not an exact proxy for the installed time; they may have tweaked the expert option to move the directory $installed = @filemtime($backup_dir.'/index.html'); $installed_for = time() - $installed; if (($installed && time() > $dismissed_until && $installed_for > 28*86400 && !defined('UPDRAFTPLUS_NOADS_B')) || (defined('UPDRAFTPLUS_FORCE_DASHNOTICE') && UPDRAFTPLUS_FORCE_DASHNOTICE)) { add_action('all_admin_notices', array($this, 'show_admin_notice_upgradead') ); } } //Moved out for use with Ajax saving $this->setup_all_admin_notices_global($service); } // Next, the actions that only come on the UpdraftPlus page if ($pagenow != UpdraftPlus_Options::admin_page() || empty($_REQUEST['page']) || 'updraftplus' != $_REQUEST['page']) return; $this->setup_all_admin_notices_udonly($service); add_action('admin_enqueue_scripts', array($this, 'admin_enqueue_scripts'), 99999); } public function updraft_ajaxrestore() { // TODO: All needs testing with restricted filesystem permissions. Those credentials need to be POST-ed too - currently not. // TODO // error_log(serialize($_POST)); if (empty($_POST['subaction']) || 'restore' != $_POST['subaction']) { echo json_encode(array('e' => 'Illegitimate data sent (0)')); die(); } if (empty($_POST['restorenonce'])) { echo json_encode(array('e' => 'Illegitimate data sent (1)')); die(); } $restore_nonce = (string)$_POST['restorenonce']; if (empty($_POST['ajaxauth'])) { echo json_encode(array('e' => 'Illegitimate data sent (2)')); die(); } global $updraftplus; $ajax_auth = get_site_option('updraft_ajax_restore_'.$restore_nonce); if (!$ajax_auth) { echo json_encode(array('e' => 'Illegitimate data sent (3)')); die(); } if (!preg_match('/^([0-9a-f]+):(\d+)/i', $ajax_auth, $matches)) { echo json_encode(array('e' => 'Illegitimate data sent (4)')); die(); } $nonce_time = $matches[2]; $auth_code_sent = $matches[1]; if (time() > $nonce_time + 600) { echo json_encode(array('e' => 'Illegitimate data sent (5)')); die(); } // TODO: Deactivate the auth code whilst the operation is underway $last_one = empty($_POST['lastone']) ? false : true; @set_time_limit(UPDRAFTPLUS_SET_TIME_LIMIT); $updraftplus->backup_time_nonce($restore_nonce); $updraftplus->logfile_open($restore_nonce); $timestamp = empty($_POST['timestamp']) ? false : (int)$_POST['timestamp']; $multisite = empty($_POST['multisite']) ? false : (bool)$_POST['multisite']; $created_by_version = empty($_POST['created_by_version']) ? false : (int)$_POST['created_by_version']; // TODO: We need to know about first_one (not yet sent), as well as last_one // TODO: Verify the values of these $type = empty($_POST['type']) ? false : (int)$_POST['type']; $backupfile = empty($_POST['backupfile']) ? false : (string)$_POST['backupfile']; $updraftplus->log("Deferred restore resumption: $type: $backupfile (timestamp=$timestamp, last_one=$last_one)"); $backupable_entities = $updraftplus->get_backupable_file_entities(true); if (!isset($backupable_entities[$type])) { echo json_encode(array('e' => 'Illegitimate data sent (6 - no such entity)', 'data' => $type)); die(); } if ($last_one) { // Remove the auth nonce from the DB to prevent abuse delete_site_option('updraft_ajax_restore_'.$restore_nonce); } else { // Reset the counter after a successful operation update_site_option('updraft_ajax_restore_'.$restore_nonce, $auth_code_sent.':'.time()); } echo json_encode(array('e' => 'TODO', 'd' => $_POST)); die; } public function wp_before_admin_bar_render() { global $wp_admin_bar; if (!UpdraftPlus_Options::user_can_manage()) return; if (defined('UPDRAFTPLUS_ADMINBAR_DISABLE') && UPDRAFTPLUS_ADMINBAR_DISABLE) return; if (false == apply_filters('updraftplus_settings_page_render', true)) return; $option_location = UpdraftPlus_Options::admin_page_url(); $args = array( 'id' => 'updraft_admin_node', 'title' => 'UpdraftPlus' ); $wp_admin_bar->add_node($args); $args = array( 'id' => 'updraft_admin_node_status', 'title' => __('Current Status', 'updraftplus').' / '.__('Backup Now', 'updraftplus'), 'parent' => 'updraft_admin_node', 'href' => $option_location.'?page=updraftplus&tab=status' ); $wp_admin_bar->add_node($args); $args = array( 'id' => 'updraft_admin_node_backups', 'title' => __('Existing Backups', 'updraftplus'), 'parent' => 'updraft_admin_node', 'href' => $option_location.'?page=updraftplus&tab=backups' ); $wp_admin_bar->add_node($args); $args = array( 'id' => 'updraft_admin_node_settings', 'title' => __('Settings', 'updraftplus'), 'parent' => 'updraft_admin_node', 'href' => $option_location.'?page=updraftplus&tab=settings' ); $wp_admin_bar->add_node($args); $args = array( 'id' => 'updraft_admin_node_expert_content', 'title' => __('Advanced Tools', 'updraftplus'), 'parent' => 'updraft_admin_node', 'href' => $option_location.'?page=updraftplus&tab=expert' ); $wp_admin_bar->add_node($args); $args = array( 'id' => 'updraft_admin_node_addons', 'title' => __('Extensions', 'updraftplus'), 'parent' => 'updraft_admin_node', 'href' => $option_location.'?page=updraftplus&tab=addons' ); $wp_admin_bar->add_node($args); global $updraftplus; if (!$updraftplus->have_addons) { $args = array( 'id' => 'updraft_admin_node_premium', 'title' => 'UpdraftPlus Premium', 'parent' => 'updraft_admin_node', 'href' => 'https://updraftplus.com/shop/updraftplus-premium/' ); $wp_admin_bar->add_node($args); } } // // Defeat other plugins/themes which dump their jQuery UI CSS onto our settings page // public function style_loader_tag($link, $handle) { // if ('jquery-ui' != $handle || false === strpos) return $link; // return "<link rel='stylesheet' id='$handle-css' $title href='$href' type='text/css' media='$media' />\n"; // } public function show_admin_notice_upgradead() { ?> <div id="updraft-dashnotice" class="updated"> <div style="float:right;"><a href="#" onclick="jQuery('#updraft-dashnotice').slideUp(); jQuery.post(ajaxurl, {action: 'updraft_ajax', subaction: 'dismissdashnotice', nonce: '<?php echo wp_create_nonce('updraftplus-credentialtest-nonce');?>' });"><?php echo sprintf(__('Dismiss (for %s months)', 'updraftplus'), 12); ?></a></div> <h3 class="thank-you"><?php _e('Thank you for backing up with UpdraftPlus!', 'updraftplus');?></h3> <a href="https://updraftplus.com/"><img class="udp-logo" alt="UpdraftPlus" src="<?php echo UPDRAFTPLUS_URL.'/images/ud-logo-150.png' ?>"></a> <?php echo '<p><strong>'.__('Free Newsletter', 'updraftplus').'</strong> <br>'.__('UpdraftPlus news, high-quality training materials for WordPress developers and site-owners, and general WordPress news. You can de-subscribe at any time.', 'updraftplus').' <a href="https://updraftplus.com/newsletter-signup">'.__('Follow this link to sign up.', 'updraftplus').'</a></p>'; echo '<p><strong>'.__('UpdraftPlus Premium', 'updraftplus').'</strong> <br>'.__('For personal support, the ability to copy sites, more storage destinations, encrypted backups for security, multiple backup destinations, better reporting, no adverts and plenty more, take a look at the premium version of UpdraftPlus - the world’s most popular backup plugin.', 'updraftplus').' <a href="https://updraftplus.com/comparison-updraftplus-free-updraftplus-premium/">'.__('Compare with the free version', 'updraftplus').'</a> / <a href="https://updraftplus.com/shop/updraftplus-premium/">'.__('Go to the shop.', 'updraftplus').'</a></p>'; echo '<p><strong>'.__('More Quality Plugins', 'updraftplus').'</strong> <br> <a href="https://wordpress.org/plugins/two-factor-authentication/">'.__('Free two-factor security plugin', 'updraftplus').'</a> | <a href="https://www.simbahosting.co.uk/s3/shop/">'.__('Premium WooCommerce plugins', 'updraftplus').'</a></p>'; ?> <div class="dismiss-dash-notice"><a href="#" onclick="jQuery('#updraft-dashnotice').slideUp(); jQuery.post(ajaxurl, {action: 'updraft_ajax', subaction: 'dismissdashnotice', nonce: '<?php echo wp_create_nonce('updraftplus-credentialtest-nonce');?>' });"><?php echo sprintf(__('Dismiss (for %s months)', 'updraftplus'), 12); ?></a></div> </div> <?php } private function ensure_sufficient_jquery_and_enqueue() { global $updraftplus, $wp_version; $enqueue_version = @constant('WP_DEBUG') ? $updraftplus->version.'-'.time() : $updraftplus->version; if (version_compare($wp_version, '3.3', '<')) { // Require a newer jQuery (3.2.1 has 1.6.1, so we go for something not too much newer). We use .on() in a way that is incompatible with < 1.7 wp_deregister_script('jquery'); wp_register_script('jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js', false, '1.7.2', false); wp_enqueue_script('jquery'); // No plupload until 3.3 wp_enqueue_script('updraftplus-admin-ui', UPDRAFTPLUS_URL.'/includes/updraft-admin-ui.js', array('jquery', 'jquery-ui-dialog'), $enqueue_version, true); } else { wp_enqueue_script('updraftplus-admin-ui', UPDRAFTPLUS_URL.'/includes/updraft-admin-ui.js', array('jquery', 'jquery-ui-dialog', 'plupload-all'), $enqueue_version); } } // This is also called directly from the auto-backup add-on public function admin_enqueue_scripts() { global $updraftplus, $wp_locale; // Defeat other plugins/themes which dump their jQuery UI CSS onto our settings page wp_deregister_style('jquery-ui'); wp_enqueue_style('jquery-ui', UPDRAFTPLUS_URL.'/includes/jquery-ui.custom.css', array(), '1.11.4'); $our_version = @constant('SCRIPT_DEBUG') ? $updraftplus->version.'.'.time() : $updraftplus->version; wp_enqueue_style('updraft-admin-css', UPDRAFTPLUS_URL.'/css/admin.css', array(), $our_version); // add_filter('style_loader_tag', array($this, 'style_loader_tag'), 10, 2); $this->ensure_sufficient_jquery_and_enqueue(); wp_enqueue_script('jquery-blockui', UPDRAFTPLUS_URL.'/includes/jquery.blockUI.js', array('jquery'), '2.70.0'); wp_enqueue_script('jquery-labelauty', UPDRAFTPLUS_URL.'/includes/labelauty/jquery-labelauty.js', array('jquery'), '20160622-ud'); wp_enqueue_style('jquery-labelauty', UPDRAFTPLUS_URL.'/includes/labelauty/jquery-labelauty.css', array(), '20150925'); do_action('updraftplus_admin_enqueue_scripts'); $day_selector = ''; for ($day_index = 0; $day_index <= 6; $day_index++) { // $selected = ($opt == $day_index) ? 'selected="selected"' : ''; $selected = ''; $day_selector .= "\n\t<option value='" . $day_index . "' $selected>" . $wp_locale->get_weekday($day_index) . '</option>'; } $mday_selector = ''; for ($mday_index = 1; $mday_index <= 28; $mday_index++) { // $selected = ($opt == $mday_index) ? 'selected="selected"' : ''; $selected = ''; $mday_selector .= "\n\t<option value='" . $mday_index . "' $selected>" . $mday_index . '</option>'; } wp_localize_script('updraftplus-admin-ui', 'updraftlion', array( 'sendonlyonwarnings' => __('Send a report only when there are warnings/errors', 'updraftplus'), 'wholebackup' => __('When the Email storage method is enabled, also send the entire backup', 'updraftplus'), 'emailsizelimits' => esc_attr(sprintf(__('Be aware that mail servers tend to have size limits; typically around %s Mb; backups larger than any limits will likely not arrive.','updraftplus'), '10-20')), 'rescanning' => __('Rescanning (looking for backups that you have uploaded manually into the internal backup store)...','updraftplus'), 'rescanningremote' => __('Rescanning remote and local storage for backup sets...','updraftplus'), 'enteremailhere' => esc_attr(__('To send to more than one address, separate each address with a comma.', 'updraftplus')), 'excludedeverything' => __('If you exclude both the database and the files, then you have excluded everything!', 'updraftplus'), 'nofileschosen' => __('You have chosen to backup files, but no file entities have been selected', 'updraftplus'), 'restoreproceeding' => __('The restore operation has begun. Do not press stop or close your browser until it reports itself as having finished.', 'updraftplus'), 'unexpectedresponse' => __('Unexpected response:','updraftplus'), 'servererrorcode' => __('The web server returned an error code (try again, or check your web server logs)', 'updraftplus'), 'newuserpass' => __("The new user's RackSpace console password is (this will not be shown again):", 'updraftplus'), 'trying' => __('Trying...', 'updraftplus'), 'fetching' => __('Fetching...', 'updraftplus'), 'calculating' => __('calculating...','updraftplus'), 'begunlooking' => __('Begun looking for this entity','updraftplus'), 'stilldownloading' => __('Some files are still downloading or being processed - please wait.', 'updraftplus'), 'processing' => __('Processing files - please wait...', 'updraftplus'), 'emptyresponse' => __('Error: the server sent an empty response.', 'updraftplus'), 'warnings' => __('Warnings:','updraftplus'), 'errors' => __('Errors:','updraftplus'), 'jsonnotunderstood' => __('Error: the server sent us a response which we did not understand.', 'updraftplus'), 'errordata' => __('Error data:', 'updraftplus'), 'error' => __('Error:','updraftplus'), 'errornocolon' => __('Error','updraftplus'), 'fileready' => __('File ready.','updraftplus'), 'youshould' => __('You should:','updraftplus'), 'deletefromserver' => __('Delete from your web server','updraftplus'), 'downloadtocomputer' => __('Download to your computer','updraftplus'), 'andthen' => __('and then, if you wish,', 'updraftplus'), 'notunderstood' => __('Download error: the server sent us a response which we did not understand.', 'updraftplus'), 'requeststart' => __('Requesting start of backup...', 'updraftplus'), 'phpinfo' => __('PHP information', 'updraftplus'), 'delete_old_dirs' => __('Delete Old Directories', 'updraftplus'), 'raw' => __('Raw backup history', 'updraftplus'), 'notarchive' => __('This file does not appear to be an UpdraftPlus backup archive (such files are .zip or .gz files which have a name like: backup_(time)_(site name)_(code)_(type).(zip|gz)).', 'updraftplus').' '.__('However, UpdraftPlus archives are standard zip/SQL files - so if you are sure that your file has the right format, then you can rename it to match that pattern.','updraftplus'), 'notarchive2' => '<p>'.__('This file does not appear to be an UpdraftPlus backup archive (such files are .zip or .gz files which have a name like: backup_(time)_(site name)_(code)_(type).(zip|gz)).', 'updraftplus').'</p> '.apply_filters('updraftplus_if_foreign_then_premium_message', '<p><a href="https://updraftplus.com/shop/updraftplus-premium/">'.__('If this is a backup created by a different backup plugin, then UpdraftPlus Premium may be able to help you.', 'updraftplus').'</a></p>'), 'makesure' => __('(make sure that you were trying to upload a zip file previously created by UpdraftPlus)','updraftplus'), 'uploaderror' => __('Upload error:','updraftplus'), 'notdba' => __('This file does not appear to be an UpdraftPlus encrypted database archive (such files are .gz.crypt files which have a name like: backup_(time)_(site name)_(code)_db.crypt.gz).','updraftplus'), 'uploaderr' => __('Upload error', 'updraftplus'), 'followlink' => __('Follow this link to attempt decryption and download the database file to your computer.','updraftplus'), 'thiskey' => __('This decryption key will be attempted:','updraftplus'), 'unknownresp' => __('Unknown server response:','updraftplus'), 'ukrespstatus' => __('Unknown server response status:','updraftplus'), 'uploaded' => __('The file was uploaded.','updraftplus'), 'backupnow' => __('Backup Now', 'updraftplus'), 'cancel' => __('Cancel', 'updraftplus'), 'deletebutton' => __('Delete', 'updraftplus'), 'createbutton' => __('Create', 'updraftplus'), 'youdidnotselectany' => __('You did not select any components to restore. Please select at least one, and then try again.', 'updraftplus'), 'proceedwithupdate' => __('Proceed with update', 'updraftplus'), 'close' => __('Close', 'updraftplus'), 'restore' => __('Restore', 'updraftplus'), 'downloadlogfile' => __('Download log file', 'updraftplus'), 'automaticbackupbeforeupdate' => __('Automatic backup before update', 'updraftplus'), 'unsavedsettings' => __('You have made changes to your settings, and not saved.', 'updraftplus'), 'saving' => __('Saving...', 'updraftplus'), 'connect' => __('Connect', 'updraftplus'), 'connecting' => __('Connecting...', 'updraftplus'), 'disconnect' => __('Disconnect', 'updraftplus'), 'disconnecting' => __('Disconnecting...', 'updraftplus'), 'counting' => __('Counting...', 'updraftplus'), 'updatequotacount' => __('Update quota count', 'updraftplus'), 'addingsite' => __('Adding...', 'updraftplus'), 'addsite' => __('Add site', 'updraftplus'), // 'resetting' => __('Resetting...', 'updraftplus'), 'creating' => __('Creating...', 'updraftplus'), 'sendtosite' => __('Send to site:', 'updraftplus'), 'checkrpcsetup' => sprintf(__('You should check that the remote site is online, not firewalled, does not have security modules that may be blocking access, has UpdraftPlus version %s or later active and that the keys have been entered correctly.', 'updraftplus'), '2.10.3'), 'pleasenamekey' => __('Please give this key a name (e.g. indicate the site it is for):', 'updraftplus'), 'key' => __('Key', 'updraftplus'), 'nokeynamegiven' => sprintf(__("Failure: No %s was given.",'updraftplus'), __('key name','updraftplus')), 'deleting' => __('Deleting...', 'updraftplus'), 'enter_mothership_url' => __('Please enter a valid URL', 'updraftplus'), 'delete_response_not_understood' => __("We requested to delete the file, but could not understand the server's response", 'updraftplus'), 'testingconnection' => __('Testing connection...', 'updraftplus'), 'send' => __('Send', 'updraftplus'), 'migratemodalheight' => class_exists('UpdraftPlus_Addons_Migrator') ? 555 : 300, 'migratemodalwidth' => class_exists('UpdraftPlus_Addons_Migrator') ? 770 : 500, 'download' => _x('Download', '(verb)', 'updraftplus'), 'unsavedsettingsbackup' => __('You have made changes to your settings, and not saved.', 'updraftplus')."\n".__('You should save your changes to ensure that they are used for making your backup.','updraftplus'), 'dayselector' => $day_selector, 'mdayselector' => $mday_selector, 'day' => __('day', 'updraftplus'), 'inthemonth' => __('in the month', 'updraftplus'), 'days' => __('day(s)', 'updraftplus'), 'hours' => __('hour(s)', 'updraftplus'), 'weeks' => __('week(s)', 'updraftplus'), 'forbackupsolderthan' => __('For backups older than', 'updraftplus'), 'ud_url' => UPDRAFTPLUS_URL, 'processing' => __('Processing...', 'updraftplus'), 'pleasefillinrequired' => __('Please fill in the required information.', 'updraftplus'), 'test_settings' => __('Test %s Settings', 'updraftplus'), 'testing_settings' => __('Testing %s Settings...', 'updraftplus'), 'settings_test_result' => __('%s settings test result:', 'updraftplus'), 'nothing_yet_logged' => __('Nothing yet logged', 'updraftplus'), ) ); } // Despite the name, this fires irrespective of what capabilities the user has (even none - so be careful) public function core_upgrade_preamble() { // They need to be able to perform backups, and to perform updates if (!UpdraftPlus_Options::user_can_manage() || (!current_user_can('update_core') && !current_user_can('update_plugins') && !current_user_can('update_themes'))) return; if (!class_exists('UpdraftPlus_Addon_Autobackup')) { if (defined('UPDRAFTPLUS_NOADS_B')) return; $dismissed_until = UpdraftPlus_Options::get_updraft_option('updraftplus_dismissedautobackup', 0); if ($dismissed_until > time()) return; } ?> <div id="updraft-autobackup" class="updated autobackup"> <?php if (!class_exists('UpdraftPlus_Addon_Autobackup')) { ?> <div style="float:right;"><a href="#" onclick="jQuery('#updraft-autobackup').slideUp(); jQuery.post(ajaxurl, {action: 'updraft_ajax', subaction: 'dismissautobackup', nonce: '<?php echo wp_create_nonce('updraftplus-credentialtest-nonce');?>' });"><?php echo sprintf(__('Dismiss (for %s weeks)', 'updraftplus'), 12); ?></a></div> <?php } ?> <h3 style="margin-top: 2px;"><?php _e('Be safe with an automatic backup','updraftplus');?></h3> <?php echo apply_filters('updraftplus_autobackup_blurb', $this->autobackup_ad_content()); ?> </div> <script> jQuery(document).ready(function() { jQuery('#updraft-autobackup').appendTo('.wrap p:first'); }); </script> <?php } private function autobackup_ad_content(){ global $updraftplus; $our_version = @constant('SCRIPT_DEBUG') ? $updraftplus->version.'.'.time() : $updraftplus->version; wp_enqueue_style('updraft-admin-css', UPDRAFTPLUS_URL.'/css/admin.css', array(), $our_version); $ret = '<div class="autobackup-description"><img class="autobackup-image" src="'.UPDRAFTPLUS_URL.'/images/automaticbackup.png" class="automation-icon"/>'; $ret .= '<div class="advert-description">'.__('UpdraftPlus Premium can automatically take a backup of your plugins or themes and database before you update. <a href="https://updraftplus.com/shop/autobackup/" target="_blank">Be safe every time, without needing to remember - follow this link to learn more</a>', 'updraftplus').'</div></div>'; $ret .= '<div class="advert-btn"><a href="https://updraftplus.com/shop/autobackup/" class="btn btn-get-started">'.__('Just this add-on', 'updraftplus').' <span class="circle-dblarrow">&raquo;</span></a></div>'; $ret .= '<div class="advert-btn"><a href="https://updraftplus.com/shop/updraftplus-premium/" class="btn btn-get-started">'.__('Full Premium plugin', 'updraftplus').' <span class="circle-dblarrow">&raquo;</span></a></div>'; return $ret; } public function admin_head() { global $pagenow; if ($pagenow != UpdraftPlus_Options::admin_page() || !isset($_REQUEST['page']) || 'updraftplus' != $_REQUEST['page'] || !UpdraftPlus_Options::user_can_manage()) return; $chunk_size = min(wp_max_upload_size()-1024, 1048576*2); # The multiple_queues argument is ignored in plupload 2.x (WP3.9+) - http://make.wordpress.org/core/2014/04/11/plupload-2-x-in-wordpress-3-9/ # max_file_size is also in filters as of plupload 2.x, but in its default position is still supported for backwards-compatibility. Likewise, our use of filters.extensions below is supported by a backwards-compatibility option (the current way is filters.mime-types.extensions $plupload_init = array( 'runtimes' => 'html5,flash,silverlight,html4', 'browse_button' => 'plupload-browse-button', 'container' => 'plupload-upload-ui', 'drop_element' => 'drag-drop-area', 'file_data_name' => 'async-upload', 'multiple_queues' => true, 'max_file_size' => '100Gb', 'chunk_size' => $chunk_size.'b', 'url' => admin_url('admin-ajax.php', 'relative'), 'multipart' => true, 'multi_selection' => true, 'urlstream_upload' => true, // additional post data to send to our ajax hook 'multipart_params' => array( '_ajax_nonce' => wp_create_nonce('updraft-uploader'), 'action' => 'plupload_action' ) ); // 'flash_swf_url' => includes_url('js/plupload/plupload.flash.swf'), // 'silverlight_xap_url' => includes_url('js/plupload/plupload.silverlight.xap'), // We want to receive -db files also... // if (1) { // $plupload_init['filters'] = array(array('title' => __('Allowed Files'), 'extensions' => 'zip,tar,gz,bz2,crypt,sql,txt')); // } else { // } # WP 3.9 updated to plupload 2.0 - https://core.trac.wordpress.org/ticket/25663 if (is_file(ABSPATH.WPINC.'/js/plupload/Moxie.swf')) { $plupload_init['flash_swf_url'] = includes_url('js/plupload/Moxie.swf'); } else { $plupload_init['flash_swf_url'] = includes_url('js/plupload/plupload.flash.swf'); } if (is_file(ABSPATH.WPINC.'/js/plupload/Moxie.xap')) { $plupload_init['silverlight_xap_url'] = includes_url('js/plupload/Moxie.xap'); } else { $plupload_init['silverlight_xap_url'] = includes_url('js/plupload/plupload.silverlight.swf'); } ?><script type="text/javascript"> var updraft_credentialtest_nonce='<?php echo wp_create_nonce('updraftplus-credentialtest-nonce');?>'; var updraftplus_settings_nonce='<?php echo wp_create_nonce('updraftplus-settings-nonce');?>'; var updraft_siteurl = '<?php echo esc_js(site_url('', 'relative'));?>'; var updraft_plupload_config=<?php echo json_encode($plupload_init); ?>; var updraft_download_nonce='<?php echo wp_create_nonce('updraftplus_download');?>'; var updraft_accept_archivename = <?php echo apply_filters('updraftplus_accept_archivename_js', "[]");?>; <?php $plupload_init['browse_button'] = 'plupload-browse-button2'; $plupload_init['container'] = 'plupload-upload-ui2'; $plupload_init['drop_element'] = 'drag-drop-area2'; $plupload_init['multipart_params']['action'] = 'plupload_action2'; $plupload_init['filters'] = array(array('title' => __('Allowed Files'), 'extensions' => 'crypt')); ?> var updraft_plupload_config2=<?php echo json_encode($plupload_init); ?>; var updraft_downloader_nonce = '<?php wp_create_nonce("updraftplus_download"); ?>' <?php $overdue = $this->howmany_overdue_crons(); if ($overdue >= 4) { ?> jQuery(document).ready(function(){ setTimeout(function(){updraft_check_overduecrons();}, 11000); function updraft_check_overduecrons() { jQuery.get(ajaxurl, { action: 'updraft_ajax', subaction: 'checkoverduecrons', nonce: updraft_credentialtest_nonce }, function(data, response) { if ('success' == response) { try { resp = jQuery.parseJSON(data); if (resp.m) { jQuery('#updraft-insert-admin-warning').html(resp.m); } } catch(err) { console.log(data); } } }); } }); <?php } ?> </script> <?php } private function disk_space_check($space) { global $updraftplus; $updraft_dir = $updraftplus->backups_dir_location(); $disk_free_space = @disk_free_space($updraft_dir); if ($disk_free_space == false) return -1; return ($disk_free_space > $space) ? true : false; } # Adds the settings link under the plugin on the plugin screen. public function plugin_action_links($links, $file) { if (is_array($links) && $file == 'updraftplus/updraftplus.php'){ $settings_link = '<a href="'.UpdraftPlus_Options::admin_page_url().'?page=updraftplus">'.__("Settings", "updraftplus").'</a>'; array_unshift($links, $settings_link); // $settings_link = '<a href="http://david.dw-perspective.org.uk/donate">'.__("Donate","UpdraftPlus").'</a>'; // array_unshift($links, $settings_link); $settings_link = '<a href="https://updraftplus.com">'.__("Add-Ons / Pro Support","updraftplus").'</a>'; array_unshift($links, $settings_link); } return $links; } public function admin_action_upgrade_pluginortheme() { if (isset($_GET['action']) && ($_GET['action'] == 'upgrade-plugin' || $_GET['action'] == 'upgrade-theme') && !class_exists('UpdraftPlus_Addon_Autobackup') && !defined('UPDRAFTPLUS_NOADS_B')) { if ($_GET['action'] == 'upgrade-plugin') { if (!current_user_can('update_plugins')) return; } else { if (!current_user_can('update_themes')) return; } $dismissed_until = UpdraftPlus_Options::get_updraft_option('updraftplus_dismissedautobackup', 0); if ($dismissed_until > time()) return; if ( 'upgrade-plugin' == $_GET['action'] ) { $title = __('Update Plugin'); $parent_file = 'plugins.php'; $submenu_file = 'plugins.php'; } else { $title = __('Update Theme'); $parent_file = 'themes.php'; $submenu_file = 'themes.php'; } require_once(ABSPATH.'wp-admin/admin-header.php'); ?> <div id="updraft-autobackup" class="updated" style="float:left; padding: 6px; margin:8px 0px;"> <div style="float: right;"><a href="#" onclick="jQuery('#updraft-autobackup').slideUp(); jQuery.post(ajaxurl, {action: 'updraft_ajax', subaction: 'dismissautobackup', nonce: '<?php echo wp_create_nonce('updraftplus-credentialtest-nonce');?>' });"><?php echo sprintf(__('Dismiss (for %s weeks)', 'updraftplus'), 10); ?></a></div> <h3 style="margin-top: 0px;"><?php _e('Be safe with an automatic backup','updraftplus');?></h3> <p><?php echo $this->autobackup_ad_content(); ?></p> </div> <?php } } public function show_admin_warning($message, $class = "updated") { echo '<div class="updraftmessage '.$class.'">'."<p>$message</p></div>"; } // public function show_admin_warning_unwritable(){ $unwritable_mess = htmlspecialchars(__("The 'Backup Now' button is disabled as your backup directory is not writable (go to the 'Settings' tab and find the relevant option).", 'updraftplus')); $this->show_admin_warning($unwritable_mess, "error"); } public function show_admin_nosettings_warning() { $this->show_admin_warning('<strong>'.__('Welcome to UpdraftPlus!', 'updraftplus').'</strong> '.__('To make a backup, just press the Backup Now button.', 'updraftplus').' <a href="#" id="updraft-navtab-settings2">'.__('To change any of the default settings of what is backed up, to configure scheduled backups, to send your backups to remote storage (recommended), and more, go to the settings tab.', 'updraftplus').'</a>', 'updated notice is-dismissible'); } public function show_admin_warning_execution_time() { $this->show_admin_warning('<strong>'.__('Warning','updraftplus').':</strong> '.sprintf(__('The amount of time allowed for WordPress plugins to run is very low (%s seconds) - you should increase it to avoid backup failures due to time-outs (consult your web hosting company for more help - it is the max_execution_time PHP setting; the recommended value is %s seconds or more)', 'updraftplus'), (int)@ini_get('max_execution_time'), 90)); } public function show_admin_warning_disabledcron() { $this->show_admin_warning('<strong>'.__('Warning','updraftplus').':</strong> '.__('The scheduler is disabled in your WordPress install, via the DISABLE_WP_CRON setting. No backups can run (even &quot;Backup Now&quot;) unless either you have set up a facility to call the scheduler manually, or until it is enabled.','updraftplus').' <a href="https://updraftplus.com/faqs/my-scheduled-backups-and-pressing-backup-now-does-nothing-however-pressing-debug-backup-does-produce-a-backup/#disablewpcron">'.__('Go here for more information.','updraftplus').'</a>', 'updated updraftplus-disable-wp-cron-warning'); } public function show_admin_warning_diskspace() { $this->show_admin_warning('<strong>'.__('Warning','updraftplus').':</strong> '.sprintf(__('You have less than %s of free disk space on the disk which UpdraftPlus is configured to use to create backups. UpdraftPlus could well run out of space. Contact your the operator of your server (e.g. your web hosting company) to resolve this issue.','updraftplus'),'35 MB')); } public function show_admin_warning_wordpressversion() { $this->show_admin_warning('<strong>'.__('Warning','updraftplus').':</strong> '.sprintf(__('UpdraftPlus does not officially support versions of WordPress before %s. It may work for you, but if it does not, then please be aware that no support is available until you upgrade WordPress.', 'updraftplus'), '3.2')); } public function show_admin_warning_litespeed() { $this->show_admin_warning('<strong>'.__('Warning','updraftplus').':</strong> '.sprintf(__('Your website is hosted using the %s web server.','updraftplus'),'LiteSpeed').' <a href="https://updraftplus.com/faqs/i-am-having-trouble-backing-up-and-my-web-hosting-company-uses-the-litespeed-webserver/">'.__('Please consult this FAQ if you have problems backing up.', 'updraftplus').'</a>'); } public function show_admin_debug_warning() { $this->show_admin_warning('<strong>'.__('Notice','updraftplus').':</strong> '.__('UpdraftPlus\'s debug mode is on. You may see debugging notices on this page not just from UpdraftPlus, but from any other plugin installed. Please try to make sure that the notice you are seeing is from UpdraftPlus before you raise a support request.', 'updraftplus').'</a>'); } public function show_admin_warning_overdue_crons($howmany) { $ret = '<div class="updraftmessage updated"><p>'; $ret .= '<strong>'.__('Warning','updraftplus').':</strong> '.sprintf(__('WordPress has a number (%d) of scheduled tasks which are overdue. Unless this is a development site, this probably means that the scheduler in your WordPress install is not working.', 'updraftplus'), $howmany).' <a href="https://updraftplus.com/faqs/scheduler-wordpress-installation-working/">'.__('Read this page for a guide to possible causes and how to fix it.', 'updraftplus').'</a>'; $ret .= '</p></div>'; return $ret; } public function show_admin_warning_dropbox() { $this->show_admin_warning('<strong>'.__('UpdraftPlus notice:','updraftplus').'</strong> <a class="updraft_authlink" href="'.UpdraftPlus_Options::admin_page_url().'?page=updraftplus&action=updraftmethod-dropbox-auth&updraftplus_dropboxauth=doit">'.sprintf(__('Click here to authenticate your %s account (you will not be able to back up to %s without it).','updraftplus'), 'Dropbox', 'Dropbox').'</a>'); } public function show_admin_warning_bitcasa() { $this->show_admin_warning('<strong>'.__('UpdraftPlus notice:','updraftplus').'</strong> <a class="updraft_authlink" href="'.UpdraftPlus_Options::admin_page_url().'?page=updraftplus&action=updraftmethod-bitcasa-auth&updraftplus_bitcasaauth=doit">'.sprintf(__('Click here to authenticate your %s account (you will not be able to back up to %s without it).','updraftplus'), 'Bitcasa', 'Bitcasa').'</a>'); } public function show_admin_warning_copycom() { $this->show_admin_warning('<strong>'.__('UpdraftPlus notice:','updraftplus').'</strong> <a class="updraft_authlink" href="'.UpdraftPlus_Options::admin_page_url().'?page=updraftplus&action=updraftmethod-copycom-auth&updraftplus_copycomauth=doit">'.sprintf(__('Click here to authenticate your %s account (you will not be able to back up to %s without it).','updraftplus'), 'Copy.Com', 'Copy').'</a>'); } public function show_admin_warning_onedrive() { $this->show_admin_warning('<strong>'.__('UpdraftPlus notice:','updraftplus').'</strong> <a class="updraft_authlink" href="'.UpdraftPlus_Options::admin_page_url().'?page=updraftplus&action=updraftmethod-onedrive-auth&updraftplus_onedriveauth=doit">'.sprintf(__('Click here to authenticate your %s account (you will not be able to back up to %s without it).','updraftplus'), 'OneDrive', 'OneDrive').'</a>'); } public function show_admin_warning_updraftvault() { $this->show_admin_warning('<strong>'.__('UpdraftPlus notice:','updraftplus').'</strong> '.sprintf(__('%s has been chosen for remote storage, but you are not currently connected.', 'updraftplus'), 'UpdraftPlus Vault').' '.__('Go to the remote storage settings in order to connect.', 'updraftplus')); } public function show_admin_warning_googledrive() { $this->show_admin_warning('<strong>'.__('UpdraftPlus notice:','updraftplus').'</strong> <a class="updraft_authlink" href="'.UpdraftPlus_Options::admin_page_url().'?page=updraftplus&action=updraftmethod-googledrive-auth&updraftplus_googleauth=doit">'.sprintf(__('Click here to authenticate your %s account (you will not be able to back up to %s without it).','updraftplus'), 'Google Drive', 'Google Drive').'</a>'); } public function show_admin_warning_googlecloud() { $this->show_admin_warning('<strong>'.__('UpdraftPlus notice:','updraftplus').'</strong> <a class="updraft_authlink" href="'.UpdraftPlus_Options::admin_page_url().'?page=updraftplus&action=updraftmethod-googlecloud-auth&updraftplus_googleauth=doit">'.sprintf(__('Click here to authenticate your %s account (you will not be able to back up to %s without it).','updraftplus'), 'Google Cloud', 'Google Cloud').'</a>'); } // This options filter removes ABSPATH off the front of updraft_dir, if it is given absolutely and contained within it public function prune_updraft_dir_prefix($updraft_dir) { if ('/' == substr($updraft_dir, 0, 1) || "\\" == substr($updraft_dir, 0, 1) || preg_match('/^[a-zA-Z]:/', $updraft_dir)) { $wcd = trailingslashit(WP_CONTENT_DIR); if (strpos($updraft_dir, $wcd) === 0) { $updraft_dir = substr($updraft_dir, strlen($wcd)); } # Legacy // if (strpos($updraft_dir, ABSPATH) === 0) { // $updraft_dir = substr($updraft_dir, strlen(ABSPATH)); // } } return $updraft_dir; } public function updraft_download_backup() { if (empty($_REQUEST['_wpnonce']) || !wp_verify_nonce($_REQUEST['_wpnonce'], 'updraftplus_download')) die; if (empty($_REQUEST['timestamp']) || !is_numeric($_REQUEST['timestamp']) || empty($_REQUEST['type'])) exit; $findex = empty($_REQUEST['findex']) ? 0 : (int)$_REQUEST['findex']; $stage = empty($_REQUEST['stage']) ? '' : $_REQUEST['stage']; // This call may not actually return, depending upon what mode it is called in echo json_encode($this->do_updraft_download_backup($findex, $_REQUEST['type'], $_REQUEST['timestamp'], $stage)); die(); } // This function may die(), depending on the request being made in $stage public function do_updraft_download_backup($findex, $type, $timestamp, $stage, $close_connection_callable = false) { @set_time_limit(UPDRAFTPLUS_SET_TIME_LIMIT); global $updraftplus; // This is a bit ugly; these variables get placed back into $_POST (where they may possibly have come from), so that UpdraftPlus::log() can detect exactly where to log the download status. $_POST['findex'] = $findex; $_POST['type'] = $type; $_POST['timestamp'] = $timestamp; // Check that it is a known entity type; if not, die if ('db' != substr($type, 0, 2)) { $backupable_entities = $updraftplus->get_backupable_file_entities(true); foreach ($backupable_entities as $t => $info) { if ($type == $t) $type_match = true; } if (empty($type_match)) return array('result' => 'error', 'code' => 'no_such_type'); } // We already know that no possible entities have an MD5 clash (even after 2 characters) // Also, there's nothing enforcing a requirement that nonces are hexadecimal $job_nonce = dechex($timestamp).$findex.substr(md5($type), 0, 3); // You need a nonce before you can set job data. And we certainly don't yet have one. $updraftplus->backup_time_nonce($job_nonce); $debug_mode = UpdraftPlus_Options::get_updraft_option('updraft_debug_mode'); // Set the job type before logging, as there can be different logging destinations $updraftplus->jobdata_set('job_type', 'download'); $updraftplus->jobdata_set('job_time_ms', $updraftplus->job_time_ms); // Retrieve the information from our backup history $backup_history = $updraftplus->get_backup_history(); // Base name $file = $backup_history[$timestamp][$type]; // Deal with multi-archive sets if (is_array($file)) $file=$file[$findex]; // Where it should end up being downloaded to $fullpath = $updraftplus->backups_dir_location().'/'.$file; if (2 == $stage) { $updraftplus->spool_file($fullpath); // Do not return - we do not want the caller to add any output die; } if ('delete' == $stage) { @unlink($fullpath); $updraftplus->log("The file has been deleted ($file)"); return array('result' => 'deleted'); } // TODO: FIXME: Failed downloads may leave log files forever (though they are small) if ($debug_mode) $updraftplus->logfile_open($updraftplus->nonce); set_error_handler(array($updraftplus, 'php_error'), E_ALL & ~E_STRICT); $updraftplus->log("Requested to obtain file: timestamp=$timestamp, type=$type, index=$findex"); $itext = empty($findex) ? '' : $findex; $known_size = isset($backup_history[$timestamp][$type.$itext.'-size']) ? $backup_history[$timestamp][$type.$itext.'-size'] : 0; $services = (isset($backup_history[$timestamp]['service'])) ? $backup_history[$timestamp]['service'] : false; if (is_string($services)) $services = array($services); $updraftplus->jobdata_set('service', $services); // Fetch it from the cloud, if we have not already got it $needs_downloading = false; if (!file_exists($fullpath)) { //if the file doesn't exist and they're using one of the cloud options, fetch it down from the cloud. $needs_downloading = true; $updraftplus->log('File does not yet exist locally - needs downloading'); } elseif ($known_size > 0 && filesize($fullpath) < $known_size) { $updraftplus->log("The file was found locally (".filesize($fullpath).") but did not match the size in the backup history ($known_size) - will resume downloading"); $needs_downloading = true; } elseif ($known_size > 0) { $updraftplus->log('The file was found locally and matched the recorded size from the backup history ('.round($known_size/1024,1).' KB)'); } else { $updraftplus->log('No file size was found recorded in the backup history. We will assume the local one is complete.'); $known_size = filesize($fullpath); } // The AJAX responder that updates on progress wants to see this $updraftplus->jobdata_set('dlfile_'.$timestamp.'_'.$type.'_'.$findex, "downloading:$known_size:$fullpath"); if ($needs_downloading) { $msg = array( 'result' => 'needs_download' ); if ($close_connection_callable && is_callable($close_connection_callable)) { call_user_func($close_connection_callable, $msg); } else { $updraftplus->close_browser_connection(json_encode($msg)); } $is_downloaded = false; add_action('http_request_args', array($updraftplus, 'modify_http_options')); foreach ($services as $service) { if ($is_downloaded) continue; $download = $this->download_file($file, $service); if (is_readable($fullpath) && $download !== false) { clearstatcache(); $updraftplus->log('Remote fetch was successful (file size: '.round(filesize($fullpath)/1024,1).' KB)'); $is_downloaded = true; } else { clearstatcache(); if (0 === @filesize($fullpath)) @unlink($fullpath); $updraftplus->log('Remote fetch failed'); } } remove_action('http_request_args', array($updraftplus, 'modify_http_options')); } // Now, be ready to spool the thing to the browser if (is_file($fullpath) && is_readable($fullpath)) { // That message is then picked up by the AJAX listener $updraftplus->jobdata_set('dlfile_'.$timestamp.'_'.$type.'_'.$findex, 'downloaded:'.filesize($fullpath).":$fullpath"); $result = 'downloaded'; } else { $updraftplus->jobdata_set('dlfile_'.$timestamp.'_'.$type.'_'.$findex, 'failed'); $updraftplus->jobdata_set('dlerrors_'.$timestamp.'_'.$type.'_'.$findex, $updraftplus->errors); $updraftplus->log('Remote fetch failed. File '.$fullpath.' did not exist or was unreadable. If you delete local backups then remote retrieval may have failed.'); $result = 'download_failed'; } restore_error_handler(); @fclose($updraftplus->logfile_handle); if (!$debug_mode) @unlink($updraftplus->logfile_name); // The browser connection was possibly already closed, but not necessarily return array('result' => $result); } # Pass only a single service, as a string, into this function private function download_file($file, $service) { global $updraftplus; @set_time_limit(UPDRAFTPLUS_SET_TIME_LIMIT); $updraftplus->log("Requested file from remote service: $service: $file"); $method_include = UPDRAFTPLUS_DIR.'/methods/'.$service.'.php'; if (file_exists($method_include)) require_once($method_include); $objname = "UpdraftPlus_BackupModule_${service}"; if (method_exists($objname, "download")) { $remote_obj = new $objname; return $remote_obj->download($file); } else { $updraftplus->log("Automatic backup restoration is not available with the method: $service."); $updraftplus->log("$file: ".sprintf(__("The backup archive for this file could not be found. The remote storage method in use (%s) does not allow us to retrieve files. To perform any restoration using UpdraftPlus, you will need to obtain a copy of this file and place it inside UpdraftPlus's working folder", 'updraftplus'), $service)." (".$this->prune_updraft_dir_prefix($updraftplus->backups_dir_location()).")", 'error'); return false; } } public function updraft_ajax_handler() { global $updraftplus; $nonce = (empty($_REQUEST['nonce'])) ? "" : $_REQUEST['nonce']; if (!wp_verify_nonce($nonce, 'updraftplus-credentialtest-nonce') || empty($_REQUEST['subaction'])) die('Security check'); // Mitigation in case the nonce leaked to an unauthorised user if (isset($_REQUEST['subaction']) && 'dismissautobackup' == $_REQUEST['subaction']) { if (!current_user_can('update_plugins') && !current_user_can('update_themes')) return; } elseif (isset($_REQUEST['subaction']) && ('dismissexpiry' == $_REQUEST['subaction'] || 'dismissdashnotice' == $_REQUEST['subaction'])) { if (!current_user_can('update_plugins')) return; } else { if (!UpdraftPlus_Options::user_can_manage()) return; } // Some of this checks that _REQUEST['subaction'] is set, which is redundant (done already in the nonce check) /* // This one is no longer used anywhere if (isset($_REQUEST['subaction']) && 'lastlog' == $_REQUEST['subaction']) { $last_message = UpdraftPlus_Options::get_updraft_option('updraft_lastmessage'); echo htmlspecialchars( '('.__('Nothing yet logged', 'updraftplus').')')); } else */ if ('forcescheduledresumption' == $_REQUEST['subaction'] && !empty($_REQUEST['resumption']) && !empty($_REQUEST['job_id']) && is_numeric($_REQUEST['resumption'])) { // Casting $resumption to int is absolutely necessary, as the WP cron system uses a hashed serialisation of the parameters for identifying jobs. Different type => different hash => does not match $resumption = (int)$_REQUEST['resumption']; $job_id = $_REQUEST['job_id']; $get_cron = $this->get_cron($job_id); if (!is_array($get_cron)) { echo json_encode(array('r' => false)); } else { $updraftplus->log("Forcing resumption: job id=$job_id, resumption=$resumption"); $time = $get_cron[0]; // wp_unschedule_event($time, 'updraft_backup_resume', array($resumption, $job_id)); wp_clear_scheduled_hook('updraft_backup_resume', array($resumption, $job_id)); $updraftplus->close_browser_connection(json_encode(array('r' => true))); $updraftplus->jobdata_set_from_array($get_cron[1]); $updraftplus->backup_resume($resumption, $job_id); } } elseif (isset($_GET['subaction']) && 'activejobs_list' == $_GET['subaction']) { echo json_encode($this->get_activejobs_list($_GET)); } elseif (isset($_REQUEST['subaction']) && 'updraftcentral_delete_key' == $_REQUEST['subaction'] && isset($_REQUEST['key_id'])) { global $updraftplus_updraftcentral_main; if (!is_a($updraftplus_updraftcentral_main, 'UpdraftPlus_UpdraftCentral_Main')) { echo json_encode(array('error' => 'UpdraftPlus_UpdraftCentral_Main object not found')); die; } echo json_encode($updraftplus_updraftcentral_main->delete_key($_REQUEST['key_id'])); die; } elseif (isset($_REQUEST['subaction']) && ('updraftcentral_create_key' == $_REQUEST['subaction'] || 'updraftcentral_get_log' == $_REQUEST['subaction'])) { global $updraftplus_updraftcentral_main; if (!is_a($updraftplus_updraftcentral_main, 'UpdraftPlus_UpdraftCentral_Main')) { echo json_encode(array('error' => 'UpdraftPlus_UpdraftCentral_Main object not found')); die; } $call_method = substr($_REQUEST['subaction'], 15); echo json_encode(call_user_func(array($updraftplus_updraftcentral_main, $call_method), $_REQUEST)); die; } elseif (isset($_REQUEST['subaction']) && 'callwpaction' == $_REQUEST['subaction'] && !empty($_REQUEST['wpaction'])) { ob_start(); $res = '<em>Request received: </em>'; if (preg_match('/^([^:]+)+:(.*)$/', stripslashes($_REQUEST['wpaction']), $matches)) { $action = $matches[1]; if (null === ($args = json_decode($matches[2], true))) { $res .= "The parameters (should be JSON) could not be decoded"; $action = false; } else { $res .= "Will despatch action: ".htmlspecialchars($action).", parameters: ".htmlspecialchars(implode(',', $args)); } } else { $action = $_REQUEST['wpaction']; $res .= "Will despatch action: ".htmlspecialchars($action).", no parameters"; } echo json_encode(array('r' => $res)); $ret = ob_get_clean(); $updraftplus->close_browser_connection($ret); if (!empty($action)) { if (!empty($args)) { do_action_ref_array($action, $args); } else { do_action($action); } } die; } elseif (isset($_REQUEST['subaction']) && 'whichdownloadsneeded' == $_REQUEST['subaction'] && is_array($_REQUEST['downloads']) && isset($_REQUEST['timestamp']) && is_numeric($_REQUEST['timestamp'])) { // The purpose of this is to look at the list of indicated downloads, and indicate which are not already fully downloaded. i.e. Which need further action. $send_back = array(); $backup = $updraftplus->get_backup_history($_REQUEST['timestamp']); $updraft_dir = $updraftplus->backups_dir_location(); $backupable_entities = $updraftplus->get_backupable_file_entities(); if (empty($backup)) { echo json_encode(array('result' => 'asyouwere')); } else { foreach ($_REQUEST['downloads'] as $i => $download) { if (is_array($download) && 2 == count($download) && isset($download[0]) && isset($download[1])) { $entity = $download[0]; if (('db' == $entity || isset($backupable_entities[$entity])) && isset($backup[$entity])) { $indexes = explode(',', $download[1]); $retain_string = ''; foreach ($indexes as $index) { $retain = true; // default $findex = (0 == $index) ? '' : (string)$index; $files = $backup[$entity]; if (!is_array($files)) $files = array($files); $size_key = $entity.$findex.'-size'; if (isset($files[$index]) && isset($backup[$size_key])) { $file = $updraft_dir.'/'.$files[$index]; if (file_exists($file) && filesize($file) >= $backup[$size_key]) { $retain = false; } } if ($retain) { $retain_string .= ('' === $retain_string) ? $index : ','.$index; $send_back[$i][0] = $entity; $send_back[$i][1] = $retain_string; } } } else { $send_back[$i][0] = $entity; $send_back[$i][1] = $download[$i][1]; } } else { // Format not understood. Just send it back as-is. $send_back[$i] = $download[$i]; } } // Finally, renumber the keys (to usual PHP style - 0, 1, ...). Otherwise, in order to preserve the indexes, json_encode() will create an object instead of an array in the case where $send_back only has one element (and is indexed with an index > 0) $send_back = array_values($send_back); echo json_encode(array('downloads' => $send_back)); } } elseif (isset($_REQUEST['subaction']) && 'httpget' == $_REQUEST['subaction']) { if (empty($_REQUEST['uri'])) { echo json_encode(array('r' => '')); die; } $uri = $_REQUEST['uri']; if (!empty($_REQUEST['curl'])) { if (!function_exists('curl_exec')) { echo json_encode(array('e' => 'No Curl installed')); die; } $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $uri); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_FAILONERROR, true); curl_setopt($ch, CURLOPT_HEADER, true); curl_setopt($ch, CURLOPT_VERBOSE, true); curl_setopt($ch, CURLOPT_STDERR, $output=fopen('php://temp', "w+")); $response = curl_exec($ch); $error = curl_error($ch); $getinfo = curl_getinfo($ch); curl_close($ch); $resp = array(); if (false === $response) { $resp['e'] = htmlspecialchars($error); # json_encode(array('e' => htmlspecialchars($error))); } $resp['r'] = (empty($response)) ? '' : htmlspecialchars(substr($response, 0, 2048)); rewind($output); $verb = stream_get_contents($output); if (!empty($verb)) $resp['r'] = htmlspecialchars($verb)."\n\n".$resp['r']; echo json_encode($resp); // echo json_encode(array('r' => htmlspecialchars(substr($response, 0, 2048)))); } else { $response = wp_remote_get($uri, array('timeout' => 10)); if (is_wp_error($response)) { echo json_encode(array('e' => htmlspecialchars($response->get_error_message()))); die; } echo json_encode(array('r' => wp_remote_retrieve_response_code($response).': '.htmlspecialchars(substr(wp_remote_retrieve_body($response), 0, 2048)))); } die; } elseif (isset($_REQUEST['subaction']) && 'dismissautobackup' == $_REQUEST['subaction']) { UpdraftPlus_Options::update_updraft_option('updraftplus_dismissedautobackup', time() + 84*86400); } elseif (isset($_REQUEST['subaction']) && 'set_autobackup_default' == $_REQUEST['subaction']) { // This option when set should have integers, not bools $default = empty($_REQUEST['default']) ? 0 : 1; UpdraftPlus_Options::update_updraft_option('updraft_autobackup_default', $default); } elseif (isset($_REQUEST['subaction']) && 'dismissexpiry' == $_REQUEST['subaction']) { UpdraftPlus_Options::update_updraft_option('updraftplus_dismissedexpiry', time() + 14*86400); } elseif (isset($_REQUEST['subaction']) && 'dismissdashnotice' == $_REQUEST['subaction']) { UpdraftPlus_Options::update_updraft_option('updraftplus_dismisseddashnotice', time() + 366*86400); } elseif (isset($_REQUEST['subaction']) && 'poplog' == $_REQUEST['subaction']){ echo json_encode($this->fetch_log($_REQUEST['backup_nonce'])); } elseif (isset($_REQUEST['subaction']) && 'restore_alldownloaded' == $_REQUEST['subaction'] && isset($_REQUEST['restoreopts']) && isset($_REQUEST['timestamp'])) { $backups = $updraftplus->get_backup_history(); $updraft_dir = $updraftplus->backups_dir_location(); $timestamp = (int)$_REQUEST['timestamp']; if (!isset($backups[$timestamp])) { echo json_encode(array('m' => '', 'w' => '', 'e' => __('No such backup set exists', 'updraftplus'))); die; } $mess = array(); parse_str(stripslashes($_REQUEST['restoreopts']), $res); if (isset($res['updraft_restore'])) { set_error_handler(array($this, 'get_php_errors'), E_ALL & ~E_STRICT); $elements = array_flip($res['updraft_restore']); $warn = array(); $err = array(); @set_time_limit(UPDRAFTPLUS_SET_TIME_LIMIT); $max_execution_time = (int)@ini_get('max_execution_time'); if ($max_execution_time>0 && $max_execution_time<61) { $warn[] = sprintf(__('The PHP setup on this webserver allows only %s seconds for PHP to run, and does not allow this limit to be raised. If you have a lot of data to import, and if the restore operation times out, then you will need to ask your web hosting company for ways to raise this limit (or attempt the restoration piece-by-piece).', 'updraftplus'), $max_execution_time); } if (isset($backups[$timestamp]['native']) && false == $backups[$timestamp]['native']) { $warn[] = __('This backup set was not known by UpdraftPlus to be created by the current WordPress installation, but was either found in remote storage, or was sent from a remote site.', 'updraftplus').' '.__('You should make sure that this really is a backup set intended for use on this website, before you restore (rather than a backup set of an unrelated website).', 'updraftplus'); } if (isset($elements['db'])) { // Analyse the header of the database file + display results list ($mess2, $warn2, $err2, $info) = $updraftplus->analyse_db_file($timestamp, $res); $mess = array_merge($mess, $mess2); $warn = array_merge($warn, $warn2); $err = array_merge($err, $err2); foreach ($backups[$timestamp] as $bid => $bval) { if ('db' != $bid && 'db' == substr($bid, 0, 2) && '-size' != substr($bid, -5, 5)) { $warn[] = __('Only the WordPress database can be restored; you will need to deal with the external database manually.', 'updraftplus'); break; } } } $backupable_entities = $updraftplus->get_backupable_file_entities(true, true); $backupable_plus_db = $backupable_entities; $backupable_plus_db['db'] = array('path' => 'path-unused', 'description' => __('Database', 'updraftplus')); if (!empty($backups[$timestamp]['meta_foreign'])) { $foreign_known = apply_filters('updraftplus_accept_archivename', array()); if (!is_array($foreign_known) || empty($foreign_known[$backups[$timestamp]['meta_foreign']])) { $err[] = sprintf(__('Backup created by unknown source (%s) - cannot be restored.', 'updraftplus'), $backups[$timestamp]['meta_foreign']); } else { // For some reason, on PHP 5.5 passing by reference in a single array stopped working with apply_filters_ref_array (though not with do_action_ref_array). $backupable_plus_db = apply_filters_ref_array("updraftplus_importforeign_backupable_plus_db", array($backupable_plus_db, array($foreign_known[$backups[$timestamp]['meta_foreign']], &$mess, &$warn, &$err))); } } foreach ($backupable_plus_db as $type => $entity_info) { if (!isset($elements[$type])) continue; $whatwegot = $backups[$timestamp][$type]; if (is_string($whatwegot)) $whatwegot = array($whatwegot); $expected_index = 0; $missing = ''; ksort($whatwegot); $outof = false; foreach ($whatwegot as $index => $file) { if (preg_match('/\d+of(\d+)\.zip/', $file, $omatch)) { $outof = max($matches[1], 1); } if ($index != $expected_index) { $missing .= ($missing == '') ? (1+$expected_index) : ",".(1+$expected_index); } if (!file_exists($updraft_dir.'/'.$file)) { $err[] = sprintf(__('File not found (you need to upload it): %s', 'updraftplus'), $updraft_dir.'/'.$file); } elseif (filesize($updraft_dir.'/'.$file) == 0) { $err[] = sprintf(__('File was found, but is zero-sized (you need to re-upload it): %s', 'updraftplus'), $file); } else { $itext = (0 == $index) ? '' : $index; if (!empty($backups[$timestamp][$type.$itext.'-size']) && $backups[$timestamp][$type.$itext.'-size'] != filesize($updraft_dir.'/'.$file)) { if (empty($warn['doublecompressfixed'])) { $warn[] = sprintf(__('File (%s) was found, but has a different size (%s) from what was expected (%s) - it may be corrupt.', 'updraftplus'), $file, filesize($updraft_dir.'/'.$file), $backups[$timestamp][$type.$itext.'-size']); } } do_action_ref_array("updraftplus_checkzip_$type", array($updraft_dir.'/'.$file, &$mess, &$warn, &$err)); } $expected_index++; } do_action_ref_array("updraftplus_checkzip_end_$type", array(&$mess, &$warn, &$err)); // Detect missing archives where they are missing from the end of the set if ($outof>0 && $expected_index < $outof) { for ($j = $expected_index; $j<$outof; $j++) { $missing .= ($missing == '') ? (1+$j) : ",".(1+$j); } } if ('' != $missing) { $warn[] = sprintf(__("This multi-archive backup set appears to have the following archives missing: %s", 'updraftplus'), $missing.' ('.$entity_info['description'].')'); } } if (0 == count($err) && 0 == count($warn)) { $mess_first = __('The backup archive files have been successfully processed. Now press Restore again to proceed.', 'updraftplus'); } elseif (0 == count($err)) { $mess_first = __('The backup archive files have been processed, but with some warnings. If all is well, then now press Restore again to proceed. Otherwise, cancel and correct any problems first.', 'updraftplus'); } else { $mess_first = __('The backup archive files have been processed, but with some errors. You will need to cancel and correct any problems before retrying.', 'updraftplus'); } if (count($this->logged) >0) { foreach ($this->logged as $lwarn) $warn[] = $lwarn; } restore_error_handler(); // Get the info if it hasn't already come from the DB scan if (!isset($info) || !is_array($info)) $info = array(); // Not all chracters can be json-encoded, and we don't need this potentially-arbitrary user-supplied info. unset($info['label']); if (!isset($info['created_by_version']) && !empty($backups[$timestamp]['created_by_version'])) $info['created_by_version'] = $backups[$timestamp]['created_by_version']; if (!isset($info['multisite']) && !empty($backups[$timestamp]['is_multisite'])) $info['multisite'] = $backups[$timestamp]['is_multisite']; do_action_ref_array('updraftplus_restore_all_downloaded_postscan', array($backups, $timestamp, $elements, &$info, &$mess, &$warn, &$err)); echo json_encode(array('m' => '<p>'.$mess_first.'</p>'.implode('<br>', $mess), 'w' => implode('<br>', $warn), 'e' => implode('<br>', $err), 'i' => json_encode($info))); } } elseif ('sid_reset' == $_REQUEST['subaction']) { delete_site_option('updraftplus-addons_siteid'); echo json_encode(array('newsid' => $updraftplus->siteid())); } elseif (('vault_connect' == $_REQUEST['subaction'] && isset($_REQUEST['email']) && isset($_REQUEST['pass'])) || 'vault_disconnect' == $_REQUEST['subaction'] || 'vault_recountquota' == $_REQUEST['subaction']) { require_once(UPDRAFTPLUS_DIR.'/methods/updraftvault.php'); $vault = new UpdraftPlus_BackupModule_updraftvault(); call_user_func(array($vault, 'ajax_'.$_REQUEST['subaction'])); } elseif (isset($_POST['backup_timestamp']) && 'deleteset' == $_REQUEST['subaction']) { echo json_encode($this->delete_set($_POST)); } elseif ('rawbackuphistory' == $_REQUEST['subaction']) { echo '<h3 id="ud-debuginfo-rawbackups">'.__('Known backups (raw)', 'updraftplus').'</h3><pre>'; var_dump($updraftplus->get_backup_history()); echo '</pre>'; echo '<h3 id="ud-debuginfo-files">Files</h3><pre>'; $updraft_dir = $updraftplus->backups_dir_location(); $raw_output = array(); $d = dir($updraft_dir); while (false !== ($entry = $d->read())) { $fp = $updraft_dir.'/'.$entry; $mtime = filemtime($fp); if (is_dir($fp)) { $size = ' d'; } elseif (is_link($fp)) { $size = ' l'; } elseif (is_file($fp)) { $size = sprintf("%8.1f", round(filesize($fp)/1024, 1)).' '.gmdate('r', $mtime); } else { $size = ' ?'; } if (preg_match('/^log\.(.*)\.txt$/', $entry, $lmatch)) $entry = '<a target="_top" href="?action=downloadlog&page=updraftplus&updraftplus_backup_nonce='.htmlspecialchars($lmatch[1]).'">'.$entry.'</a>'; $raw_output[$mtime] = empty($raw_output[$mtime]) ? sprintf("%s %s\n", $size, $entry) : $raw_output[$mtime].sprintf("%s %s\n", $size, $entry); } @$d->close(); krsort($raw_output, SORT_NUMERIC); foreach ($raw_output as $line) echo $line; echo '</pre>'; echo '<h3 id="ud-debuginfo-options">'.__('Options (raw)', 'updraftplus').'</h3>'; $opts = $updraftplus->get_settings_keys(); asort($opts); // <tr><th>'.__('Key','updraftplus').'</th><th>'.__('Value','updraftplus').'</th></tr> echo '<table><thead></thead><tbody>'; foreach ($opts as $opt) { echo '<tr><td>'.htmlspecialchars($opt).'</td><td>'.htmlspecialchars(print_r(UpdraftPlus_Options::get_updraft_option($opt), true)).'</td>'; } echo '</tbody></table>'; do_action('updraftplus_showrawinfo'); } elseif ('countbackups' == $_REQUEST['subaction']) { $backup_history = UpdraftPlus_Options::get_updraft_option('updraft_backup_history'); $backup_history = (is_array($backup_history))?$backup_history:array(); #echo sprintf(__('%d set(s) available', 'updraftplus'), count($backup_history)); echo __('Existing Backups', 'updraftplus').' ('.count($backup_history).')'; } elseif ('ping' == $_REQUEST['subaction']) { // The purpose of this is to detect brokenness caused by extra line feeds in plugins/themes - before it breaks other AJAX operations and leads to support requests echo 'pong'; } elseif ('checkoverduecrons' == $_REQUEST['subaction']) { $how_many_overdue = $this->howmany_overdue_crons(); if ($how_many_overdue >= 4) echo json_encode(array('m' => $this->show_admin_warning_overdue_crons($how_many_overdue))); } elseif ('delete_old_dirs' == $_REQUEST['subaction']) { $this->delete_old_dirs_go(false); } elseif ('phpinfo' == $_REQUEST['subaction']) { phpinfo(INFO_ALL ^ (INFO_CREDITS | INFO_LICENSE)); echo '<h3 id="ud-debuginfo-constants">'.__('Constants', 'updraftplus').'</h3>'; $opts = @get_defined_constants(); ksort($opts); // <tr><th>'.__('Key','updraftplus').'</th><th>'.__('Value','updraftplus').'</th></tr> echo '<table><thead></thead><tbody>'; foreach ($opts as $key => $opt) { echo '<tr><td>'.htmlspecialchars($key).'</td><td>'.htmlspecialchars(print_r($opt, true)).'</td>'; } echo '</tbody></table>'; } elseif ('doaction' == $_REQUEST['subaction'] && !empty($_REQUEST['subsubaction']) && 'updraft_' == substr($_REQUEST['subsubaction'], 0, 8)) { do_action($_REQUEST['subsubaction']); } elseif ('backupnow' == $_REQUEST['subaction']) { $this->request_backupnow($_REQUEST); # Old-style: schedule an event in 5 seconds time. This has the advantage of testing out the scheduler, and alerting the user if it doesn't work... but has the disadvantage of not working in that case. # I don't think the </div>s should be here - in case this is ever re-activated // if (wp_schedule_single_event(time()+5, $event, array($backupnow_nocloud)) === false) { // $updraftplus->log("A backup run failed to schedule"); // echo __("Failed.", 'updraftplus'); // } else { // echo htmlspecialchars(__('OK. You should soon see activity in the "Last log message" field below.','updraftplus'))." <a href=\"https://updraftplus.com/faqs/my-scheduled-backups-and-pressing-backup-now-does-nothing-however-pressing-debug-backup-does-produce-a-backup/\"><br>".__('Nothing happening? Follow this link for help.','updraftplus')."</a>"; // $updraftplus->log("A backup run has been scheduled"); // } } elseif (isset($_GET['subaction']) && 'lastbackup' == $_GET['subaction']) { echo $this->last_backup_html(); } elseif (isset($_GET['subaction']) && 'activejobs_delete' == $_GET['subaction'] && isset($_GET['jobid'])) { echo json_encode($this->activejobs_delete((string)$_GET['jobid'])); } elseif (isset($_GET['subaction']) && 'diskspaceused' == $_GET['subaction'] && isset($_GET['entity'])) { $entity = $_GET['entity']; // This can count either the size of the Updraft directory, or of the data to be backed up echo $this->get_disk_space_used($entity); } elseif (isset($_GET['subaction']) && 'historystatus' == $_GET['subaction']) { $remotescan = !empty($_GET['remotescan']); $rescan = ($remotescan || !empty($_GET['rescan'])); $history_status = $this->get_history_status($rescan, $remotescan); echo @json_encode($history_status); } elseif (isset($_POST['subaction']) && $_POST['subaction'] == 'credentials_test') { $this->do_credentials_test($_POST); die; } die; } // This echoes output; so, you will need to do output buffering if you want to capture it public function do_credentials_test($test_settings) { $method = (!empty($test_settings['method']) && preg_match("/^[a-z0-9]+$/", $test_settings['method'])) ? $test_settings['method'] : ""; $objname = "UpdraftPlus_BackupModule_$method"; $this->logged = array(); # TODO: Add action for WP HTTP SSL stuff set_error_handler(array($this, 'get_php_errors'), E_ALL & ~E_STRICT); if (!class_exists($objname)) include_once(UPDRAFTPLUS_DIR."/methods/$method.php"); # TODO: Add action for WP HTTP SSL stuff if (method_exists($objname, "credentials_test")) { $obj = new $objname; $obj->credentials_test($test_settings); } if (count($this->logged) >0) { echo "\n\n".__('Messages:', 'updraftplus')."\n"; foreach ($this->logged as $err) { echo "* $err\n"; } } restore_error_handler(); } // Relevant options (array keys): backup_timestamp, delete_remote, public function delete_set($opts) { global $updraftplus; $backups = $updraftplus->get_backup_history(); $timestamps = (string)$opts['backup_timestamp']; $timestamps = explode(',', $timestamps); $delete_remote = empty($opts['delete_remote']) ? false : true; // You need a nonce before you can set job data. And we certainly don't yet have one. $updraftplus->backup_time_nonce(); // Set the job type before logging, as there can be different logging destinations $updraftplus->jobdata_set('job_type', 'delete'); $updraftplus->jobdata_set('job_time_ms', $updraftplus->job_time_ms); if (UpdraftPlus_Options::get_updraft_option('updraft_debug_mode')) { $updraftplus->logfile_open($updraftplus->nonce); set_error_handler(array($updraftplus, 'php_error'), E_ALL & ~E_STRICT); } $updraft_dir = $updraftplus->backups_dir_location(); $backupable_entities = $updraftplus->get_backupable_file_entities(true, true); $local_deleted = 0; $remote_deleted = 0; $sets_removed = 0; foreach ($timestamps as $i => $timestamp) { if (!isset($backups[$timestamp])) { echo json_encode(array('result' => 'error', 'message' => __('Backup set not found', 'updraftplus'))); die; } $nonce = isset($backups[$timestamp]['nonce']) ? $backups[$timestamp]['nonce'] : ''; $delete_from_service = array(); if ($delete_remote) { // Locate backup set if (isset($backups[$timestamp]['service'])) { $services = is_string($backups[$timestamp]['service']) ? array($backups[$timestamp]['service']) : $backups[$timestamp]['service']; if (is_array($services)) { foreach ($services as $service) { if ($service && $service != 'none' && $service != 'email') $delete_from_service[] = $service; } } } } $files_to_delete = array(); foreach ($backupable_entities as $key => $ent) { if (isset($backups[$timestamp][$key])) { $files_to_delete[$key] = $backups[$timestamp][$key]; } } // Delete DB if (isset($backups[$timestamp]['db'])) $files_to_delete['db'] = $backups[$timestamp]['db']; // Also delete the log if ($nonce && !UpdraftPlus_Options::get_updraft_option('updraft_debug_mode')) { $files_to_delete['log'] = "log.$nonce.txt"; } unset($backups[$timestamp]); $sets_removed++; UpdraftPlus_Options::update_updraft_option('updraft_backup_history', $backups); add_action('http_request_args', array($updraftplus, 'modify_http_options')); foreach ($files_to_delete as $key => $files) { # Local deletion if (is_string($files)) $files=array($files); foreach ($files as $file) { if (is_file($updraft_dir.'/'.$file)) { if (@unlink($updraft_dir.'/'.$file)) $local_deleted++; } } if ('log' != $key && count($delete_from_service) > 0) { foreach ($delete_from_service as $service) { if ('email' == $service) continue; if (file_exists(UPDRAFTPLUS_DIR."/methods/$service.php")) require_once(UPDRAFTPLUS_DIR."/methods/$service.php"); $objname = "UpdraftPlus_BackupModule_".$service; $deleted = -1; if (class_exists($objname)) { # TODO: Re-use the object (i.e. prevent repeated connection setup/teardown) $remote_obj = new $objname; $deleted = $remote_obj->delete($files); } if ($deleted === -1) { //echo __('Did not know how to delete from this cloud service.', 'updraftplus'); } elseif ($deleted !== false) { $remote_deleted = $remote_deleted + count($files); } else { // Do nothing } } } } remove_action('http_request_args', array($updraftplus, 'modify_http_options')); } $message = sprintf(__('Backup sets removed: %d', 'updraftplus'),$sets_removed)."\n"; $message .= sprintf(__('Local archives deleted: %d', 'updraftplus'),$local_deleted)."\n"; $message .= sprintf(__('Remote archives deleted: %d', 'updraftplus'),$remote_deleted)."\n"; $updraftplus->log("Local archives deleted: ".$local_deleted); $updraftplus->log("Remote archives deleted: ".$remote_deleted); if (UpdraftPlus_Options::get_updraft_option('updraft_debug_mode')) { restore_error_handler(); } return array('result' => 'success', 'message' => $message, 'removed' => array('sets' => $sets_removed, 'local' => $local_deleted, 'remote' => $remote_deleted)); } public function get_history_status($rescan, $remotescan) { global $updraftplus; if ($rescan) $messages = $updraftplus->rebuild_backup_history($remotescan); $backup_history = UpdraftPlus_Options::get_updraft_option('updraft_backup_history'); $backup_history = (is_array($backup_history)) ? $backup_history : array(); $output = $this->existing_backup_table($backup_history); if (!empty($messages) && is_array($messages)) { $noutput = '<div style="margin-left: 100px; margin-top: 10px;"><ul style="list-style: disc inside;">'; foreach ($messages as $msg) { $noutput .= '<li>'.(($msg['desc']) ? $msg['desc'].': ' : '').'<em>'.$msg['message'].'</em></li>'; } $noutput .= '</ul></div>'; $output = $noutput.$output; } $logs_exist = (false !== strpos($output, 'downloadlog')); if (!$logs_exist) { list($mod_time, $log_file, $nonce) = $updraftplus->last_modified_log(); if ($mod_time) $logs_exist = true; } return apply_filters('updraftplus_get_history_status_result', array( 'n' => sprintf(__('Existing Backups', 'updraftplus').' (%d)', count($backup_history)), 't' => $output, 'cksum' => md5($output), 'logs_exist' => $logs_exist, )); } public function get_disk_space_used($entity) { global $updraftplus; if ('updraft' == $entity) { return $this->recursive_directory_size($updraftplus->backups_dir_location()); } else { $backupable_entities = $updraftplus->get_backupable_file_entities(true, false); if ('all' == $entity) { $total_size = 0; foreach ($backupable_entities as $entity => $data) { # Might be an array $basedir = $backupable_entities[$entity]; $dirs = apply_filters('updraftplus_dirlist_'.$entity, $basedir); $size = $this->recursive_directory_size($dirs, $updraftplus->get_exclude($entity), $basedir, 'numeric'); if (is_numeric($size) && $size>0) $total_size += $size; } return $updraftplus->convert_numeric_size_to_text($total_size); } elseif (!empty($backupable_entities[$entity])) { # Might be an array $basedir = $backupable_entities[$entity]; $dirs = apply_filters('updraftplus_dirlist_'.$entity, $basedir); return $this->recursive_directory_size($dirs, $updraftplus->get_exclude($entity), $basedir); } } return __('Error', 'updraftplus'); } public function activejobs_delete($job_id) { if (preg_match("/^[0-9a-f]{12}$/", $job_id)) { global $updraftplus; $cron = get_option('cron'); $found_it = false; $updraft_dir = $updraftplus->backups_dir_location(); if (file_exists($updraft_dir.'/log.'.$job_id.'.txt')) touch($updraft_dir.'/deleteflag-'.$job_id.'.txt'); foreach ($cron as $time => $job) { if (isset($job['updraft_backup_resume'])) { foreach ($job['updraft_backup_resume'] as $hook => $info) { if (isset($info['args'][1]) && $info['args'][1] == $job_id) { $args = $cron[$time]['updraft_backup_resume'][$hook]['args']; wp_unschedule_event($time, 'updraft_backup_resume', $args); if (!$found_it) return array('ok' => 'Y', 'c' => 'deleted', 'm' => __('Job deleted', 'updraftplus')); $found_it = true; } } } } } if (!$found_it) return array('ok' => 'N', 'c' => 'not_found', 'm' => __('Could not find that job - perhaps it has already finished?', 'updraftplus')); } // Input: an array of items // Each item is in the format: <base>,<timestamp>,<type>(,<findex>) // The 'base' is not for us: we just pass it straight back public function get_download_statuses($downloaders) { global $updraftplus; $download_status = array(); foreach ($downloaders as $downloader) { # prefix, timestamp, entity, index if (preg_match('/^([^,]+),(\d+),([-a-z]+|db[0-9]+),(\d+)$/', $downloader, $matches)) { $findex = (empty($matches[4])) ? '0' : $matches[4]; $updraftplus->nonce = dechex($matches[2]).$findex.substr(md5($matches[3]), 0, 3); $updraftplus->jobdata_reset(); $status = $this->download_status($matches[2], $matches[3], $matches[4]); if (is_array($status)) { $status['base'] = $matches[1]; $status['timestamp'] = $matches[2]; $status['what'] = $matches[3]; $status['findex'] = $findex; $download_status[] = $status; } } } return $download_status; } public function get_activejobs_list($request) { global $updraftplus; $download_status = empty($request['downloaders']) ? array(): $this->get_download_statuses(explode(':', $request['downloaders'])); if (!empty($request['oneshot'])) { $job_id = get_site_option('updraft_oneshotnonce', false); // print_active_job() for one-shot jobs that aren't in cron $active_jobs = (false === $job_id) ? '' : $this->print_active_job($job_id, true); } elseif (!empty($request['thisjobonly'])) { // print_active_jobs() is for resumable jobs where we want the cron info to be included in the output $active_jobs = $this->print_active_jobs($request['thisjobonly']); } else { $active_jobs = $this->print_active_jobs(); } $logupdate_array = array(); if (!empty($request['log_fetch'])) { if (isset($request['log_nonce'])) { $log_nonce = $request['log_nonce']; $log_pointer = isset($request['log_pointer']) ? absint($request['log_pointer']) : 0; $logupdate_array = $this->fetch_log($log_nonce, $log_pointer); } } return array( // We allow the front-end to decide what to do if there's nothing logged - we used to (up to 1.11.29) send a pre-defined message 'l' => htmlspecialchars(UpdraftPlus_Options::get_updraft_option('updraft_lastmessage', '')), 'j' => $active_jobs, 'ds' => $download_status, 'u' => $logupdate_array ); } public function request_backupnow($request, $close_connection_callable = false) { global $updraftplus; $backupnow_nocloud = (empty($request['backupnow_nocloud'])) ? false : true; $event = (!empty($request['backupnow_nofiles'])) ? 'updraft_backupnow_backup_database' : ((!empty($request['backupnow_nodb'])) ? 'updraft_backupnow_backup' : 'updraft_backupnow_backup_all'); // The call to backup_time_nonce() allows us to know the nonce in advance, and return it $nonce = $updraftplus->backup_time_nonce(); $msg = array( 'nonce' => $nonce, 'm' => '<strong>'.__('Start backup', 'updraftplus').':</strong> '.htmlspecialchars(__('OK. You should soon see activity in the "Last log message" field below.','updraftplus')) ); if ($close_connection_callable && is_callable($close_connection_callable)) { call_user_func($close_connection_callable, $msg); } else { $updraftplus->close_browser_connection(json_encode($msg)); } $options = array('nocloud' => $backupnow_nocloud, 'use_nonce' => $nonce); if (!empty($request['onlythisfileentity']) && is_string($request['onlythisfileentity'])) { // Something to see in the 'last log' field when it first appears, before the backup actually starts $updraftplus->log(__('Start backup','updraftplus')); $options['restrict_files_to_override'] = explode(',', $request['onlythisfileentity']); } if (!empty($request['extradata'])) { $options['extradata'] = $request['extradata']; } do_action($event, apply_filters('updraft_backupnow_options', $options, $request)); } public function fetch_log($backup_nonce, $log_pointer=0) { global $updraftplus; if (empty($backup_nonce)) { list($mod_time, $log_file, $nonce) = $updraftplus->last_modified_log(); } else { $nonce = $backup_nonce; } if (!preg_match('/^[0-9a-f]+$/', $nonce)) die('Security check'); $log_content = ''; $new_pointer = $log_pointer; if (!empty($nonce)) { $updraft_dir = $updraftplus->backups_dir_location(); $potential_log_file = $updraft_dir."/log.".$nonce.".txt"; if (is_readable($potential_log_file)){ $templog_array = array(); $log_file = fopen($potential_log_file, "r"); if ($log_pointer > 0) fseek($log_file, $log_pointer); while (($buffer = fgets($log_file, 4096)) !== false) { $templog_array[] = $buffer; } if (!feof($log_file)) { $templog_array[] = __('Error: unexpected file read fail', 'updraftplus'); } $new_pointer = ftell($log_file); $log_content = implode("", $templog_array); } else { $log_content .= __('The log file could not be read.','updraftplus'); } } else { $log_content .= __('The log file could not be read.','updraftplus'); } $ret_array = array( 'html' => $log_content, 'nonce' => $nonce, 'pointer' => $new_pointer ); return $ret_array; } public function howmany_overdue_crons() { $how_many_overdue = 0; if (function_exists('_get_cron_array') || (is_file(ABSPATH.WPINC.'/cron.php') && include_once(ABSPATH.WPINC.'/cron.php') && function_exists('_get_cron_array'))) { $crons = _get_cron_array(); if (is_array($crons)) { $timenow = time(); foreach ($crons as $jt => $job) { if ($jt < $timenow) { $how_many_overdue++; } } } } return $how_many_overdue; } public function get_php_errors($errno, $errstr, $errfile, $errline) { global $updraftplus; if (0 == error_reporting()) return true; $logline = $updraftplus->php_error_to_logline($errno, $errstr, $errfile, $errline); if (false !== $logline) $this->logged[] = $logline; # Don't pass it up the chain (since it's going to be output to the user always) return true; } private function download_status($timestamp, $type, $findex) { global $updraftplus; $response = array( 'm' => $updraftplus->jobdata_get('dlmessage_'.$timestamp.'_'.$type.'_'.$findex).'<br>' ); if ($file = $updraftplus->jobdata_get('dlfile_'.$timestamp.'_'.$type.'_'.$findex)) { if ('failed' == $file) { $response['e'] = __('Download failed', 'updraftplus').'<br>'; $response['failed'] = true; $errs = $updraftplus->jobdata_get('dlerrors_'.$timestamp.'_'.$type.'_'.$findex); if (is_array($errs) && !empty($errs)) { $response['e'] .= '<ul class="disc">'; foreach ($errs as $err) { if (is_array($err)) { $response['e'] .= '<li>'.htmlspecialchars($err['message']).'</li>'; } else { $response['e'] .= '<li>'.htmlspecialchars($err).'</li>'; } } $response['e'] .= '</ul>'; } } elseif (preg_match('/^downloaded:(\d+):(.*)$/', $file, $matches) && file_exists($matches[2])) { $response['p'] = 100; $response['f'] = $matches[2]; $response['s'] = (int)$matches[1]; $response['t'] = (int)$matches[1]; $response['m'] = __('File ready.', 'updraftplus'); } elseif (preg_match('/^downloading:(\d+):(.*)$/', $file, $matches) && file_exists($matches[2])) { // Convert to bytes $response['f'] = $matches[2]; $total_size = (int)max($matches[1], 1); $cur_size = filesize($matches[2]); $response['s'] = $cur_size; $file_age = time() - filemtime($matches[2]); if ($file_age > 20) $response['a'] = time() - filemtime($matches[2]); $response['t'] = $total_size; $response['m'] .= __("Download in progress", 'updraftplus').' ('.round($cur_size/1024).' / '.round(($total_size/1024)).' KB)'; $response['p'] = round(100*$cur_size/$total_size); } else { $response['m'] .= __('No local copy present.', 'updraftplus'); $response['p'] = 0; $response['s'] = 0; $response['t'] = 1; } } return $response; } public function upload_dir($uploads) { global $updraftplus; $updraft_dir = $updraftplus->backups_dir_location(); if (is_writable($updraft_dir)) $uploads['path'] = $updraft_dir; return $uploads; } // We do actually want to over-write public function unique_filename_callback($dir, $name, $ext) { return $name.$ext; } public function sanitize_file_name($filename) { // WordPress 3.4.2 on multisite (at least) adds in an unwanted underscore return preg_replace('/-db(.*)\.gz_\.crypt$/', '-db$1.gz.crypt', $filename); } public function plupload_action() { // check ajax nonce global $updraftplus; @set_time_limit(UPDRAFTPLUS_SET_TIME_LIMIT); if (!UpdraftPlus_Options::user_can_manage()) exit; check_ajax_referer('updraft-uploader'); $updraft_dir = $updraftplus->backups_dir_location(); if (!@$updraftplus->really_is_writable($updraft_dir)) { echo json_encode(array('e' => sprintf(__("Backup directory (%s) is not writable, or does not exist.", 'updraftplus'), $updraft_dir).' '.__('You will find more information about this in the Settings section.', 'updraftplus'))); exit; } add_filter('upload_dir', array($this, 'upload_dir')); add_filter('sanitize_file_name', array($this, 'sanitize_file_name')); // handle file upload $farray = array('test_form' => true, 'action' => 'plupload_action'); $farray['test_type'] = false; $farray['ext'] = 'x-gzip'; $farray['type'] = 'application/octet-stream'; if (!isset($_POST['chunks'])) { $farray['unique_filename_callback'] = array($this, 'unique_filename_callback'); } $status = wp_handle_upload( $_FILES['async-upload'], $farray ); remove_filter('upload_dir', array($this, 'upload_dir')); remove_filter('sanitize_file_name', array($this, 'sanitize_file_name')); if (isset($status['error'])) { echo json_encode(array('e' => $status['error'])); exit; } // If this was the chunk, then we should instead be concatenating onto the final file if (isset($_POST['chunks']) && isset($_POST['chunk']) && preg_match('/^[0-9]+$/',$_POST['chunk'])) { $final_file = basename($_POST['name']); if (!rename($status['file'], $updraft_dir.'/'.$final_file.'.'.$_POST['chunk'].'.zip.tmp')) { @unlink($status['file']); echo json_encode(array('e' => sprintf(__('Error: %s', 'updraftplus'), __('This file could not be uploaded', 'updraftplus')))); exit; } $status['file'] = $updraft_dir.'/'.$final_file.'.'.$_POST['chunk'].'.zip.tmp'; // Final chunk? If so, then stich it all back together if ($_POST['chunk'] == $_POST['chunks']-1) { if ($wh = fopen($updraft_dir.'/'.$final_file, 'wb')) { for ($i=0 ; $i<$_POST['chunks']; $i++) { $rf = $updraft_dir.'/'.$final_file.'.'.$i.'.zip.tmp'; if ($rh = fopen($rf, 'rb')) { while ($line = fread($rh, 32768)) fwrite($wh, $line); fclose($rh); @unlink($rf); } } fclose($wh); $status['file'] = $updraft_dir.'/'.$final_file; if ('.tar' == substr($final_file, -4, 4)) { if (file_exists($status['file'].'.gz')) unlink($status['file'].'.gz'); if (file_exists($status['file'].'.bz2')) unlink($status['file'].'.bz2'); } elseif ('.tar.gz' == substr($final_file, -7, 7)) { if (file_exists(substr($status['file'], 0, strlen($status['file'])-3))) unlink(substr($status['file'], 0, strlen($status['file'])-3)); if (file_exists(substr($status['file'], 0, strlen($status['file'])-3).'.bz2')) unlink(substr($status['file'], 0, strlen($status['file'])-3).'.bz2'); } elseif ('.tar.bz2' == substr($final_file, -8, 8)) { if (file_exists(substr($status['file'], 0, strlen($status['file'])-4))) unlink(substr($status['file'], 0, strlen($status['file'])-4)); if (file_exists(substr($status['file'], 0, strlen($status['file'])-4).'.gz')) unlink(substr($status['file'], 0, strlen($status['file'])-3).'.gz'); } } } } $response = array(); if (!isset($_POST['chunks']) || (isset($_POST['chunk']) && $_POST['chunk'] == $_POST['chunks']-1)) { $file = basename($status['file']); if (!preg_match('/^log\.[a-f0-9]{12}\.txt/i', $file) && !preg_match('/^backup_([\-0-9]{15})_.*_([0-9a-f]{12})-([\-a-z]+)([0-9]+)?(\.(zip|gz|gz\.crypt))?$/i', $file, $matches)) { $accept = apply_filters('updraftplus_accept_archivename', array()); if (is_array($accept)) { foreach ($accept as $acc) { if (preg_match('/'.$acc['pattern'].'/i', $file)) $accepted = $acc['desc']; } } if (!empty($accepted)) { $response['dm'] = sprintf(__('This backup was created by %s, and can be imported.', 'updraftplus'), $accepted); } else { @unlink($status['file']); echo json_encode(array('e' => sprintf(__('Error: %s', 'updraftplus'),__('Bad filename format - this does not look like a file created by UpdraftPlus','updraftplus')))); exit; } } else { $backupable_entities = $updraftplus->get_backupable_file_entities(true); $type = isset($matches[3]) ? $matches[3] : ''; if (!preg_match('/^log\.[a-f0-9]{12}\.txt/', $file) && 'db' != $type && !isset($backupable_entities[$type])) { @unlink($status['file']); echo json_encode(array('e' => sprintf(__('Error: %s', 'updraftplus'),sprintf(__('This looks like a file created by UpdraftPlus, but this install does not know about this type of object: %s. Perhaps you need to install an add-on?','updraftplus'), htmlspecialchars($type))))); exit; } } } // send the uploaded file url in response $response['m'] = $status['url']; echo json_encode($response); exit; } # Database decrypter public function plupload_action2() { @set_time_limit(UPDRAFTPLUS_SET_TIME_LIMIT); global $updraftplus; if (!UpdraftPlus_Options::user_can_manage()) exit; check_ajax_referer('updraft-uploader'); $updraft_dir = $updraftplus->backups_dir_location(); if (!is_writable($updraft_dir)) exit; add_filter('upload_dir', array($this, 'upload_dir')); add_filter('sanitize_file_name', array($this, 'sanitize_file_name')); // handle file upload $farray = array( 'test_form' => true, 'action' => 'plupload_action2' ); $farray['test_type'] = false; $farray['ext'] = 'crypt'; $farray['type'] = 'application/octet-stream'; if (isset($_POST['chunks'])) { // $farray['ext'] = 'zip'; // $farray['type'] = 'application/zip'; } else { $farray['unique_filename_callback'] = array($this, 'unique_filename_callback'); } $status = wp_handle_upload( $_FILES['async-upload'], $farray ); remove_filter('upload_dir', array($this, 'upload_dir')); remove_filter('sanitize_file_name', array($this, 'sanitize_file_name')); if (isset($status['error'])) { echo 'ERROR:'.$status['error']; exit; } // If this was the chunk, then we should instead be concatenating onto the final file if (isset($_POST['chunks']) && isset($_POST['chunk']) && preg_match('/^[0-9]+$/',$_POST['chunk'])) { $final_file = basename($_POST['name']); rename($status['file'], $updraft_dir.'/'.$final_file.'.'.$_POST['chunk'].'.zip.tmp'); $status['file'] = $updraft_dir.'/'.$final_file.'.'.$_POST['chunk'].'.zip.tmp'; // Final chunk? If so, then stich it all back together if ($_POST['chunk'] == $_POST['chunks']-1) { if ($wh = fopen($updraft_dir.'/'.$final_file, 'wb')) { for ($i=0 ; $i<$_POST['chunks']; $i++) { $rf = $updraft_dir.'/'.$final_file.'.'.$i.'.zip.tmp'; if ($rh = fopen($rf, 'rb')) { while ($line = fread($rh, 32768)) fwrite($wh, $line); fclose($rh); @unlink($rf); } } fclose($wh); $status['file'] = $updraft_dir.'/'.$final_file; } } } if (!isset($_POST['chunks']) || (isset($_POST['chunk']) && $_POST['chunk'] == $_POST['chunks']-1)) { $file = basename($status['file']); if (!preg_match('/^backup_([\-0-9]{15})_.*_([0-9a-f]{12})-db([0-9]+)?\.(gz\.crypt)$/i', $file)) { @unlink($status['file']); echo 'ERROR:'.__('Bad filename format - this does not look like an encrypted database file created by UpdraftPlus','updraftplus'); exit; } } // send the uploaded file url in response // echo 'OK:'.$status['url']; echo 'OK:'.$file; exit; } public function settings_header() { global $updraftplus; ?> <div class="wrap" id="updraft-wrap"> <h1><?php echo $updraftplus->plugin_title; ?></h1> <a href="https://updraftplus.com">UpdraftPlus.Com</a> | <?php if (!defined('UPDRAFTPLUS_NOADS_B')) { ?><a href="https://updraftplus.com/shop/updraftplus-premium/"><?php _e("Premium",'updraftplus');?></a> | <?php } ?> <a href="https://updraftplus.com/news/"><?php _e('News','updraftplus');?></a> | <a href="https://twitter.com/updraftplus"><?php _e('Twitter', 'updraftplus');?></a> | <a href="https://updraftplus.com/support/"><?php _e("Support",'updraftplus');?></a> | <?php if (!is_file(UPDRAFTPLUS_DIR.'/udaddons/updraftplus-addons.php')) { ?><a href="https://updraftplus.com/newsletter-signup"><?php _e("Newsletter sign-up", 'updraftplus');?></a> | <?php } ?> <a href="http://david.dw-perspective.org.uk"><?php _e("Lead developer's homepage",'updraftplus');?></a> | <a href="https://updraftplus.com/support/frequently-asked-questions/"><?php _e('FAQs', 'updraftplus'); ?></a> | <a href="https://www.simbahosting.co.uk/s3/shop/"><?php _e('More plugins', 'updraftplus');?></a> - <?php _e('Version','updraftplus');?>: <?php echo $updraftplus->version; ?> <br> <?php } public function settings_output() { if (false == ($render = apply_filters('updraftplus_settings_page_render', true))) { do_action('updraftplus_settings_page_render_abort', $render); return; } do_action('updraftplus_settings_page_init'); global $updraftplus; /* we use request here because the initial restore is triggered by a POSTed form. we then may need to obtain credentials for the WP_Filesystem. to do this WP outputs a form, but we don't pass our parameters via that. So the values are passed back in as GET parameters. */ if (isset($_REQUEST['action']) && (($_REQUEST['action'] == 'updraft_restore' && isset($_REQUEST['backup_timestamp'])) || ('updraft_restore_continue' == $_REQUEST['action'] && !empty($_REQUEST['restoreid'])))) { $is_continuation = ('updraft_restore_continue' == $_REQUEST['action']) ? true : false; if ($is_continuation) { $restore_in_progress = get_site_option('updraft_restore_in_progress'); if ($restore_in_progress != $_REQUEST['restoreid']) { $abort_restore_already = true; $updraftplus->log(__('Sufficient information about the in-progress restoration operation could not be found.', 'updraftplus').' (restoreid_mismatch)', 'error', 'restoreid_mismatch'); } else { $restore_jobdata = $updraftplus->jobdata_getarray($restore_in_progress); if (is_array($restore_jobdata) && isset($restore_jobdata['job_type']) && 'restore' == $restore_jobdata['job_type'] && isset($restore_jobdata['second_loop_entities']) && !empty($restore_jobdata['second_loop_entities']) && isset($restore_jobdata['job_time_ms']) && isset($restore_jobdata['backup_timestamp'])) { $backup_timestamp = $restore_jobdata['backup_timestamp']; $continuation_data = $restore_jobdata; } else { $abort_restore_already = true; $updraftplus->log(__('Sufficient information about the in-progress restoration operation could not be found.', 'updraftplus').' (restoreid_nojobdata)', 'error', 'restoreid_nojobdata'); } } } else { $backup_timestamp = $_REQUEST['backup_timestamp']; $continuation_data = null; } if (empty($abort_restore_already)) { $backup_success = $this->restore_backup($backup_timestamp, $continuation_data); } else { $backup_success = false; } if (empty($updraftplus->errors) && $backup_success === true) { // TODO: Deal with the case of some of the work having been deferred // If we restored the database, then that will have out-of-date information which may confuse the user - so automatically re-scan for them. $updraftplus->rebuild_backup_history(); echo '<p><strong>'; $updraftplus->log_e('Restore successful!'); echo '</strong></p>'; $updraftplus->log("Restore successful"); $s_val = 1; if (!empty($this->entities_to_restore) && is_array($this->entities_to_restore)) { foreach ($this->entities_to_restore as $k => $v) { if ('db' != $v) $s_val = 2; } } $pval = ($updraftplus->have_addons) ? 1 : 0; echo '<strong>'.__('Actions','updraftplus').':</strong> <a href="'.UpdraftPlus_Options::admin_page_url().'?page=updraftplus&updraft_restore_success='.$s_val.'&pval='.$pval.'">'.__('Return to UpdraftPlus Configuration','updraftplus').'</a>'; return; } elseif (is_wp_error($backup_success)) { echo '<p>'; $updraftplus->log_e('Restore failed...'); echo '</p>'; $updraftplus->log_wp_error($backup_success); $updraftplus->log("Restore failed"); $updraftplus->list_errors(); echo '<strong>'.__('Actions','updraftplus').':</strong> <a href="'.UpdraftPlus_Options::admin_page_url().'?page=updraftplus">'.__('Return to UpdraftPlus Configuration','updraftplus').'</a>'; return; } elseif (false === $backup_success) { # This means, "not yet - but stay on the page because we may be able to do it later, e.g. if the user types in the requested information" echo '<p>'; $updraftplus->log_e('Restore failed...'); echo '</p>'; $updraftplus->log("Restore failed"); $updraftplus->list_errors(); echo '<strong>'.__('Actions','updraftplus').':</strong> <a href="'.UpdraftPlus_Options::admin_page_url().'?page=updraftplus">'.__('Return to UpdraftPlus Configuration','updraftplus').'</a>'; return; } } if (isset($_REQUEST['action']) && 'updraft_delete_old_dirs' == $_REQUEST['action']) { $nonce = (empty($_REQUEST['_wpnonce'])) ? "" : $_REQUEST['_wpnonce']; if (!wp_verify_nonce($nonce, 'updraftplus-credentialtest-nonce')) die('Security check'); $this->delete_old_dirs_go(); return; } if (!empty($_REQUEST['action']) && 'updraftplus_broadcastaction' == $_REQUEST['action'] && !empty($_REQUEST['subaction'])) { $nonce = (empty($_REQUEST['nonce'])) ? "" : $_REQUEST['nonce']; if (!wp_verify_nonce($nonce, 'updraftplus-credentialtest-nonce')) die('Security check'); do_action($_REQUEST['subaction']); return; } if (isset($_GET['error'])) { // This is used by Microsoft OneDrive authorisation failures (May 15). I am not sure what may have been using the 'error' GET parameter otherwise - but it is harmless. if (!empty($_GET['error_description'])) { $this->show_admin_warning(htmlspecialchars($_GET['error_description']).' ('.htmlspecialchars($_GET['error']).')', 'error'); } else { $this->show_admin_warning(htmlspecialchars($_GET['error']), 'error'); } } if (isset($_GET['message'])) $this->show_admin_warning(htmlspecialchars($_GET['message'])); if (isset($_GET['action']) && $_GET['action'] == 'updraft_create_backup_dir' && isset($_GET['nonce']) && wp_verify_nonce($_GET['nonce'], 'create_backup_dir')) { $created = $this->create_backup_dir(); if (is_wp_error($created)) { echo '<p>'.__('Backup directory could not be created', 'updraftplus').'...<br/>'; echo '<ul class="disc">'; foreach ($created->get_error_messages() as $key => $msg) { echo '<li>'.htmlspecialchars($msg).'</li>'; } echo '</ul></p>'; } elseif ($created !== false) { echo '<p>'.__('Backup directory successfully created.', 'updraftplus').'</p><br/>'; } echo '<b>'.__('Actions','updraftplus').':</b> <a href="'.UpdraftPlus_Options::admin_page_url().'?page=updraftplus">'.__('Return to UpdraftPlus Configuration', 'updraftplus').'</a>'; return; } echo '<div id="updraft_backup_started" class="updated updraft-hidden" style="display:none;"></div>'; if (isset($_POST['action']) && 'updraft_backup_debug_all' == $_POST['action']) { $updraftplus->boot_backup(true,true); } elseif (isset($_POST['action']) && 'updraft_backup_debug_db' == $_POST['action']) { $updraftplus->boot_backup(false, true, false, true); } elseif (isset($_POST['action']) && 'updraft_wipesettings' == $_POST['action']) { $settings = $updraftplus->get_settings_keys(); foreach ($settings as $s) UpdraftPlus_Options::delete_updraft_option($s); // These aren't in get_settings_keys() because they are always in the options table, regardless of context global $wpdb; $wpdb->query("DELETE FROM $wpdb->options WHERE ( option_name LIKE 'updraftplus_unlocked_%' OR option_name LIKE 'updraftplus_locked_%' OR option_name LIKE 'updraftplus_last_lock_time_%' OR option_name LIKE 'updraftplus_semaphore_%' OR option_name LIKE 'updraft_jobdata_%' OR option_name LIKE 'updraft_last_scheduled_%' )"); $site_options = array('updraft_oneshotnonce'); foreach ($site_options as $s) delete_site_option($s); $this->show_admin_warning(__("Your settings have been wiped.", 'updraftplus')); } // This opens a div $this->settings_header(); ?> <div id="updraft-hidethis"> <p> <strong><?php _e('Warning:', 'updraftplus'); ?> <?php _e("If you can still read these words after the page finishes loading, then there is a JavaScript or jQuery problem in the site.", 'updraftplus'); ?></strong> <?php if (false !== strpos(basename(UPDRAFTPLUS_URL), ' ')) { ?> <strong><?php _e('The UpdraftPlus directory in wp-content/plugins has white-space in it; WordPress does not like this. You should rename the directory to wp-content/plugins/updraftplus to fix this problem.', 'updraftplus');?></strong> <?php } else { ?> <a href="https://updraftplus.com/do-you-have-a-javascript-or-jquery-error/"><?php _e('Go here for more information.', 'updraftplus'); ?></a> <?php } ?> </p> </div> <?php $include_deleteform_div = true; // Opens a div, which needs closing later if (isset($_GET['updraft_restore_success'])) { $success_advert = (isset($_GET['pval']) && 0 == $_GET['pval'] && !$updraftplus->have_addons) ? '<p>'.__('For even more features and personal support, check out ','updraftplus').'<strong><a href="https://updraftplus.com/shop/updraftplus-premium/" target="_blank">UpdraftPlus Premium</a>.</strong></p>' : ""; echo "<div class=\"updated backup-restored\"><span><strong>".__('Your backup has been restored.','updraftplus').'</strong></span><br>'; // Unnecessary - will be advised of this below // if (2 == $_GET['updraft_restore_success']) echo ' '.__('Your old (themes, uploads, plugins, whatever) directories have been retained with "-old" appended to their name. Remove them when you are satisfied that the backup worked properly.'); echo $success_advert; $include_deleteform_div = false; } // $this->print_restore_in_progress_box_if_needed(); if ($this->scan_old_dirs(true)) $this->print_delete_old_dirs_form(true, $include_deleteform_div); // Close the div opened by the earlier section if (isset($_GET['updraft_restore_success'])) echo '</div>'; $ws_advert = $updraftplus->wordshell_random_advert(1); if ($ws_advert && empty($success_advert) && empty($this->no_settings_warning)) { echo '<div class="updated ws_advert" style="clear:left;">'.$ws_advert.'</div>'; } if (!$updraftplus->memory_check(64)) {?> <div class="updated memory-limit"><?php _e("Your PHP memory limit (set by your web hosting company) is very low. UpdraftPlus attempted to raise it but was unsuccessful. This plugin may struggle with a memory limit of less than 64 Mb - especially if you have very large files uploaded (though on the other hand, many sites will be successful with a 32Mb limit - your experience may vary).",'updraftplus');?> <?php _e('Current limit is:','updraftplus');?> <?php echo $updraftplus->memory_check_current(); ?> MB</div> <?php } if (!empty($updraftplus->errors)) { echo '<div class="error updraft_list_errors">'; $updraftplus->list_errors(); echo '</div>'; } $backup_history = UpdraftPlus_Options::get_updraft_option('updraft_backup_history'); if (empty($backup_history)) { $updraftplus->rebuild_backup_history(); $backup_history = UpdraftPlus_Options::get_updraft_option('updraft_backup_history'); } $backup_history = is_array($backup_history) ? $backup_history : array(); ?> <h2 class="nav-tab-wrapper"> <?php $tabflag = 1; if (isset($_REQUEST['tab'])){ switch($_REQUEST['tab']) { case 'status': $tabflag = 1; break; case 'backups': $tabflag = 2; break; case 'settings': $tabflag = 3; break; case 'expert': $tabflag = 4; break; case 'addons': $tabflag = 5; break; default : $tabflag = 1; } } ?> <a class="nav-tab <?php if (1 == $tabflag) echo 'nav-tab-active'; ?>" id="updraft-navtab-status" href="#updraft-navtab-status-content" ><?php _e('Current Status', 'updraftplus');?> </span></a> <a class="nav-tab <?php if (2 == $tabflag) echo 'nav-tab-active'; ?>" id="updraft-navtab-backups" href="#updraft-navtab-backups-contents" ><?php echo __('Existing Backups', 'updraftplus').' ('.count($backup_history).')';?> </span></a> <a class="nav-tab <?php if (3 == $tabflag) echo 'nav-tab-active'; ?>" id="updraft-navtab-settings" href="#updraft-navtab-settings-content"><?php _e('Settings', 'updraftplus');?> </span></a> <a class="nav-tab<?php if (4 == $tabflag) echo ' nav-tab-active'; ?>" id="updraft-navtab-expert" href="#updraft-navtab-expert-content"><?php _e('Advanced Tools', 'updraftplus');?> </span></a> <a class="nav-tab<?php if (5 == $tabflag) echo ' nav-tab-active'; ?>" id="updraft-navtab-addons" href="#updraft-navtab-addons-content"><?php _e('Premium / Extensions', 'updraftplus');?> </span></a> <?php //do_action('updraftplus_settings_afternavtabs'); ?> </h2> <?php $updraft_dir = $updraftplus->backups_dir_location(); $backup_disabled = ($updraftplus->really_is_writable($updraft_dir)) ? '' : 'disabled="disabled"'; ?> <div id="updraft-poplog" > <pre id="updraft-poplog-content"></pre> </div> <div id="updraft-navtab-status-content" class="<?php if (1 != $tabflag) echo 'updraft-hidden'; ?>" style="<?php if (1 != $tabflag) echo 'display:none;'; ?>"> <div id="updraft-insert-admin-warning"></div> <table class="form-table" style="float:left; clear:both;"> <noscript> <tr> <th><?php _e('JavaScript warning','updraftplus');?>:</th> <td style="color:red"><?php _e('This admin interface uses JavaScript heavily. You either need to activate it within your browser, or to use a JavaScript-capable browser.','updraftplus');?></td> </tr> </noscript> <tr> <th></th> <td> <?php if ($backup_disabled) { $unwritable_mess = htmlspecialchars(__("The 'Backup Now' button is disabled as your backup directory is not writable (go to the 'Settings' tab and find the relevant option).", 'updraftplus')); $this->show_admin_warning($unwritable_mess, "error"); } ?> <button id="updraft-backupnow-button" type="button" <?php echo $backup_disabled ?> class="updraft-bigbutton button-primary" <?php if ($backup_disabled) echo 'title="'.esc_attr(__('This button is disabled because your backup directory is not writable (see the settings).', 'updraftplus')).'" ';?> onclick="updraft_backup_dialog_open();"><?php _e('Backup Now', 'updraftplus');?></button> <button type="button" class="updraft-bigbutton button-primary" onclick="updraft_openrestorepanel();"> <?php _e('Restore','updraftplus');?> </button> <button type="button" class="updraft-bigbutton button-primary" onclick="updraft_migrate_dialog_open();"><?php _e('Clone/Migrate','updraftplus');?></button> </td> </tr> <?php $last_backup_html = $this->last_backup_html(); $current_time = get_date_from_gmt(gmdate('Y-m-d H:i:s'), 'D, F j, Y H:i'); // $current_time = date_i18n('D, F j, Y H:i'); ?> <script>var lastbackup_laststatus = '<?php echo esc_js($last_backup_html);?>';</script> <tr> <th><span title="<?php esc_attr_e("All the times shown in this section are using WordPress's configured time zone, which you can set in Settings -> General", 'updraftplus'); ?>"><?php _e('Next scheduled backups', 'updraftplus');?>:<br> <span style="font-weight:normal;"><em><?php _e('Now', 'updraftplus');?>: <?php echo $current_time; ?></span></span></em></th> <td> <table id="next-backup-table-inner" class="next-backup"> <?php $this->next_scheduled_backups_output(); ?> </table> </td> </tr> <tr> <th><?php _e('Last backup job run:','updraftplus');?></th> <td id="updraft_last_backup"><?php echo $last_backup_html ?></td> </tr> </table> <br style="clear:both;" /> <?php $this->render_active_jobs_and_log_table(); ?> <div id="updraft-migrate-modal" title="<?php _e('Migrate Site', 'updraftplus'); ?>" style="display:none;"> <?php if (class_exists('UpdraftPlus_Addons_Migrator')) { do_action('updraftplus_migrate_modal_output'); } else { echo '<p id="updraft_migrate_modal_main">'.__('Do you want to migrate or clone/duplicate a site?', 'updraftplus').'</p><p>'.__('Then, try out our "Migrator" add-on. After using it once, you\'ll have saved the purchase price compared to the time needed to copy a site by hand.', 'updraftplus').'</p><p><a href="https://updraftplus.com/landing/migrator">'.__('Get it here.', 'updraftplus').'</a></p>'; } ?> </div> <div id="updraft-iframe-modal"> <div id="updraft-iframe-modal-innards"> </div> </div> <div id="updraft-backupnow-modal" title="UpdraftPlus - <?php _e('Perform a one-time backup', 'updraftplus'); ?>"> <!-- <p> <?php _e("To proceed, press 'Backup Now'. Then, watch the 'Last Log Message' field for activity.", 'updraftplus');?> </p>--> <?php echo $this->backupnow_modal_contents(); ?> </div> <?php if (is_multisite() && !file_exists(UPDRAFTPLUS_DIR.'/addons/multisite.php')) { ?> <h2>UpdraftPlus <?php _e('Multisite','updraftplus');?></h2> <table> <tr> <td> <p class="multisite-advert-width"><?php echo __('Do you need WordPress Multisite support?','updraftplus').' <a href="https://updraftplus.com/shop/updraftplus-premium/">'. __('Please check out UpdraftPlus Premium, or the stand-alone Multisite add-on.','updraftplus');?></a>.</p> </td> </tr> </table> <?php } ?> </div> <div id="updraft-navtab-backups-content" <?php if (2 != $tabflag) echo 'class="updraft-hidden"'; ?> style="<?php if (2 != $tabflag) echo 'display:none;'; ?>"> <?php $is_opera = (false !== strpos($_SERVER['HTTP_USER_AGENT'], 'Opera') || false !== strpos($_SERVER['HTTP_USER_AGENT'], 'OPR/')); $tmp_opts = array('include_opera_warning' => $is_opera); $this->settings_downloading_and_restoring($backup_history, false, $tmp_opts); $this->settings_delete_and_restore_modals(); ?> </div> <div id="updraft-navtab-settings-content" <?php if (3 != $tabflag) echo 'class="updraft-hidden"'; ?> style="<?php if (3 != $tabflag) echo 'display:none;'; ?>"> <h2 class="updraft_settings_sectionheading"><?php _e('Backup Contents And Schedule','updraftplus');?></h2> <?php UpdraftPlus_Options::options_form_begin(); ?> <?php $this->settings_formcontents(); ?> </form> </div> <div id="updraft-navtab-expert-content"<?php if (4 != $tabflag) echo ' class="updraft-hidden"'; ?> style="<?php if (4 != $tabflag) echo 'display:none;'; ?>"> <?php $this->settings_expertsettings($backup_disabled); ?> </div> <div id="updraft-navtab-addons-content"<?php if (5 != $tabflag) echo ' class="updraft-hidden"'; ?> style="<?php if (5 != $tabflag) echo 'display:none;'; ?>"> <?php $tick = UPDRAFTPLUS_URL.'/images/updraft_tick.png'; $cross = UPDRAFTPLUS_URL.'/images/updraft_cross.png'; $freev = UPDRAFTPLUS_URL.'/images/updraft_freev.png'; $premv = UPDRAFTPLUS_URL.'/images/updraft_premv.png'; ob_start(); ?> <div> <h2>UpdraftPlus Premium</h2> <p> <span class="premium-upgrade-prompt"><?php _e('You are currently using the free version of UpdraftPlus from wordpress.org.', 'updraftplus');?> <a href="https://updraftplus.com/support/installing-updraftplus-premium-your-add-on/"><br><?php echo __('If you have made a purchase from UpdraftPlus.Com, then follow this link to the instructions to install your purchase.', 'updraftplus').' '.__('The first step is to de-install the free version.', 'updraftplus')?></a></span> <ul class="updraft_premium_description_list"> <li><a href="https://updraftplus.com/shop/updraftplus-premium/"><strong><?php _e('Get UpdraftPlus Premium', 'updraftplus');?></strong></a></li> <li><a href="https://updraftplus.com/updraftplus-full-feature-list/"><?php _e('Full feature list', 'updraftplus');?></a></li> <li><a href="https://updraftplus.com/faq-category/general-and-pre-sales-questions/"><?php _e('Pre-sales FAQs', 'updraftplus');?></a></li> <li class="last"><a href="https://updraftplus.com/ask-a-pre-sales-question/"><?php _e('Ask a pre-sales question', 'updraftplus');?></a> - <a href="https://updraftplus.com/support/"><?php _e('Support', 'updraftplus');?></a></li> </ul> </p> </div> <div> <table class="updraft_feat_table"> <tr> <th class="updraft_feat_th" style="text-align:left;"></th> <th class="updraft_feat_th"><img src="<?php echo $freev;?>" height="120"></th> <th class="updraft_feat_th" style='background-color:#DF6926;'><a href="https://updraftplus.com/shop/updraftplus-premium/"><img src="<?php echo $premv;?>" height="120"></a></th> </tr> <tr> <td class="updraft_feature_cell"><?php _e('Get it from', 'updraftplus');?></td> <td class="updraft_tick_cell" style="vertical-align:top; line-height: 120%; margin-top:6px; padding-top:6px;">WordPress.Org</td> <td class="updraft_tick_cell" style="padding: 6px; line-height: 120%;"> UpdraftPlus.Com<br> <a href="https://updraftplus.com/shop/updraftplus-premium/"><strong><?php _e('Buy It Now!', 'updraftplus');?></strong></a><br> </td> </tr> <tr> <td class="updraft_feature_cell"><?php _e('Backup WordPress files and database', 'updraftplus');?></td> <td class="updraft_tick_cell"><img src="<?php echo $tick;?>"></td> <td class="updraft_tick_cell"><img src="<?php echo $tick;?>"></td> </tr> <tr> <td class="updraft_feature_cell"><?php echo sprintf(__('Translated into over %s languages', 'updraftplus'), 16);?></td> <td class="updraft_tick_cell"><img src="<?php echo $tick;?>"></td> <td class="updraft_tick_cell"><img src="<?php echo $tick;?>"></td> </tr> <tr> <td class="updraft_feature_cell"><?php _e('Restore from backup', 'updraftplus');?></td> <td class="updraft_tick_cell"><img src="<?php echo $tick;?>"></td> <td class="updraft_tick_cell"><img src="<?php echo $tick;?>"></td> </tr> <tr> <td class="updraft_feature_cell"><?php _e('Backup to remote storage', 'updraftplus');?></td> <td class="updraft_tick_cell"><img src="<?php echo $tick;?>"></td> <td class="updraft_tick_cell"><img src="<?php echo $tick;?>"></td> </tr> <tr> <td class="updraft_feature_cell"><?php _e('Dropbox, Google Drive, FTP, S3, Rackspace, Email', 'updraftplus');?></td> <td class="updraft_tick_cell"><img src="<?php echo $tick;?>"></td> <td class="updraft_tick_cell"><img src="<?php echo $tick;?>"></td> </tr> <tr> <td class="updraft_feature_cell"><?php _e('WebDAV, Copy.Com, SFTP/SCP, encrypted FTP', 'updraftplus');?></td> <td class="updraft_tick_cell"><img src="<?php echo $cross;?>"></td> <td class="updraft_tick_cell"><img src="<?php echo $tick;?>"></td> </tr> <tr> <td class="updraft_feature_cell"><?php _e('Microsoft OneDrive, Microsoft Azure, Google Cloud Storage', 'updraftplus');?></td> <td class="updraft_tick_cell"><img src="<?php echo $cross;?>"></td> <td class="updraft_tick_cell"><img src="<?php echo $tick;?>"></td> </tr> <tr> <td class="updraft_feature_cell"><?php _e('Free 1GB for UpdraftPlus Vault', 'updraftplus');?></td> <td class="updraft_tick_cell"><img src="<?php echo $cross;?>"></td> <td class="updraft_tick_cell"><img src="<?php echo $tick;?>"></td> </tr> <tr> <td class="updraft_feature_cell"><?php _e('Backup extra files and databases', 'updraftplus');?></td> <td class="updraft_tick_cell"><img src="<?php echo $cross;?>"></td> <td class="updraft_tick_cell"><img src="<?php echo $tick;?>"></td> </tr> <tr> <td class="updraft_feature_cell"><?php _e('Migrate / clone (i.e. copy) websites', 'updraftplus');?></td> <td class="updraft_tick_cell"><img src="<?php echo $cross;?>"></td> <td class="updraft_tick_cell"><img src="<?php echo $tick;?>"></td> </tr> <tr> <td class="updraft_feature_cell"><?php _e('Basic email reporting', 'updraftplus');?></td> <td class="updraft_tick_cell"><img src="<?php echo $tick;?>"></td> <td class="updraft_tick_cell"><img src="<?php echo $tick;?>"></td> </tr> <tr> <td class="updraft_feature_cell"><?php _e('Advanced reporting features', 'updraftplus');?></td> <td class="updraft_tick_cell"><img src="<?php echo $cross;?>"></td> <td class="updraft_tick_cell"><img src="<?php echo $tick;?>"></td> </tr> <tr> <td class="updraft_feature_cell"><?php _e('Automatic backup when updating WP/plugins/themes', 'updraftplus');?></td> <td class="updraft_tick_cell"><img src="<?php echo $cross;?>"></td> <td class="updraft_tick_cell"><img src="<?php echo $tick;?>"></td> </tr> <tr> <td class="updraft_feature_cell"><?php _e('Send backups to multiple remote destinations', 'updraftplus');?></td> <td class="updraft_tick_cell"><img src="<?php echo $cross;?>"></td> <td class="updraft_tick_cell"><img src="<?php echo $tick;?>"></td> </tr> <tr> <td class="updraft_feature_cell"><?php _e('Database encryption', 'updraftplus');?></td> <td class="updraft_tick_cell"><img src="<?php echo $cross;?>"></td> <td class="updraft_tick_cell"><img src="<?php echo $tick;?>"></td> </tr> <tr> <td class="updraft_feature_cell"><?php _e('Restore backups from other plugins', 'updraftplus');?></td> <td class="updraft_tick_cell"><img src="<?php echo $cross;?>"></td> <td class="updraft_tick_cell"><img src="<?php echo $tick;?>"></td> </tr> <tr> <td class="updraft_feature_cell"><?php _e('No advertising links on UpdraftPlus settings page', 'updraftplus');?></td> <td class="updraft_tick_cell"><img src="<?php echo $cross;?>"></td> <td class="updraft_tick_cell"><img src="<?php echo $tick;?>"></td> </tr> <tr> <td class="updraft_feature_cell"><?php _e('Scheduled backups', 'updraftplus');?></td> <td class="updraft_tick_cell"><img src="<?php echo $tick;?>"></td> <td class="updraft_tick_cell"><img src="<?php echo $tick;?>"></td> </tr> <tr> <td class="updraft_feature_cell"><?php _e('Fix backup time', 'updraftplus');?></td> <td class="updraft_tick_cell"><img src="<?php echo $cross;?>"></td> <td class="updraft_tick_cell"><img src="<?php echo $tick;?>"></td> </tr> <tr> <td class="updraft_feature_cell"><?php _e('Network/Multisite support', 'updraftplus');?></td> <td class="updraft_tick_cell"><img src="<?php echo $cross;?>"></td> <td class="updraft_tick_cell"><img src="<?php echo $tick;?>"></td> </tr> <tr> <td class="updraft_feature_cell"><?php _e('Lock settings access', 'updraftplus');?></td> <td class="updraft_tick_cell"><img src="<?php echo $cross;?>"></td> <td class="updraft_tick_cell"><img src="<?php echo $tick;?>"></td> </tr> <tr> <td class="updraft_feature_cell"><?php _e('Personal support', 'updraftplus');?></td> <td class="updraft_tick_cell"><img src="<?php echo $cross;?>"></td> <td class="updraft_tick_cell"><img src="<?php echo $tick;?>"></td> </tr> </table> </div> <?php echo apply_filters('updraftplus_addonstab_content', ob_get_clean()); // Close addons tab echo '</div>'; // settings_header() opens a div echo '</div>'; } private function print_restore_in_progress_box_if_needed() { $restore_in_progress = get_site_option('updraft_restore_in_progress'); if (!empty($restore_in_progress)) { global $updraftplus; $restore_jobdata = $updraftplus->jobdata_getarray($restore_in_progress); if (is_array($restore_jobdata) && !empty($restore_jobdata)) { // Only print if within the last 24 hours; and only after 2 minutes if (isset($restore_jobdata['job_type']) && 'restore' == $restore_jobdata['job_type'] && isset($restore_jobdata['second_loop_entities']) && !empty($restore_jobdata['second_loop_entities']) && isset($restore_jobdata['job_time_ms']) && (time() - $restore_jobdata['job_time_ms'] > 120 || (defined('UPDRAFTPLUS_RESTORE_PROGRESS_ALWAYS_SHOW') && UPDRAFTPLUS_RESTORE_PROGRESS_ALWAYS_SHOW)) && time() - $restore_jobdata['job_time_ms'] < 86400 && (empty($_REQUEST['action']) || ('updraft_restore' != $_REQUEST['action'] && 'updraft_restore_continue' != $_REQUEST['action']))) { $restore_jobdata['jobid'] = $restore_in_progress; $this->restore_in_progress_jobdata = $restore_jobdata; add_action('all_admin_notices', array($this, 'show_admin_restore_in_progress_notice') ); } } } } public function show_admin_restore_in_progress_notice() { if (isset($_REQUEST['action']) && 'updraft_restore_abort' == $_REQUEST['action'] && !empty($_REQUEST['restoreid'])) { delete_site_option('updraft_restore_in_progress'); return; } $restore_jobdata = $this->restore_in_progress_jobdata; $seconds_ago = time() - (int)$restore_jobdata['job_time_ms']; $minutes_ago = floor($seconds_ago/60); $seconds_ago = $seconds_ago - $minutes_ago*60; $time_ago = sprintf(__("%s minutes, %s seconds", 'updraftplus'), $minutes_ago, $seconds_ago); ?><div class="updated show_admin_restore_in_progress_notice"> <span class="unfinished-restoration"><strong><?php echo 'UpdraftPlus: '.__('Unfinished restoration', 'updraftplus'); ?> </strong></span><br> <p><?php printf(__('You have an unfinished restoration operation, begun %s ago.', 'updraftplus'), $time_ago);?></p> <form method="post" action="<?php echo UpdraftPlus_Options::admin_page_url().'?page=updraftplus'; ?>"> <?php wp_nonce_field('updraftplus-credentialtest-nonce'); ?> <input id="updraft_restore_continue_action" type="hidden" name="action" value="updraft_restore_continue"> <input type="hidden" name="restoreid" value="<?php echo $restore_jobdata['jobid'];?>" value="<?php echo esc_attr($restore_jobdata['jobid']);?>"> <button onclick="jQuery('#updraft_restore_continue_action').val('updraft_restore_continue'); jQuery(this).parent('form').submit();" type="submit" class="button-primary"><?php _e('Continue restoration', 'updraftplus'); ?></button> <button onclick="jQuery('#updraft_restore_continue_action').val('updraft_restore_abort'); jQuery(this).parent('form').submit();" class="button-secondary"><?php _e('Dismiss', 'updraftplus');?></button> </form><?php echo "</div>"; } public function backupnow_modal_contents() { $ret = $this->backup_now_widgetry(); // $ret .= '<p>'.__('Does nothing happen when you attempt backups?','updraftplus').' <a href="https://updraftplus.com/faqs/my-scheduled-backups-and-pressing-backup-now-does-nothing-however-pressing-debug-backup-does-produce-a-backup/">'.__('Go here for help.', 'updraftplus').'</a></p>'; return $ret; } private function backup_now_widgetry() { $ret = ''; $ret .= '<p> <input type="checkbox" id="backupnow_includedb" checked="checked"> <label for="backupnow_includedb">'.__("Include the database in the backup", 'updraftplus').'</label><br>'; $ret .= '<input type="checkbox" id="backupnow_includefiles" checked="checked"> <label for="backupnow_includefiles">'.__("Include any files in the backup", 'updraftplus').'</label> (<a href="#" id="backupnow_includefiles_showmoreoptions">...</a>)<br>'; $ret .= '<div id="backupnow_includefiles_moreoptions" class="updraft-hidden" style="display:none;"><em>'.__('Your saved settings also affect what is backed up - e.g. files excluded.', 'updraftplus').'</em><br>'.$this->files_selector_widgetry('backupnow_files_', false, 'sometimes').'</div>'; $ret .= '<span id="backupnow_remote_container">'.$this->backup_now_remote_message().'</span>'; $ret .= '</p>'; $ret .= apply_filters('updraft_backupnow_modal_afteroptions', '', ''); return $ret; } // Also used by the auto-backups add-on public function render_active_jobs_and_log_table($wide_format = false, $print_active_jobs = true) { ?> <table class="form-table" id="updraft_activejobs_table"> <?php $active_jobs = ($print_active_jobs) ? $this->print_active_jobs() : '';?> <tr id="updraft_activejobsrow" class="<?php if (!$active_jobs && !$wide_format) { echo 'hidden'; } if ($wide_format) { echo ".minimum-height"; } ?>"> <?php if ($wide_format) { ?> <td id="updraft_activejobs" colspan="2"> <?php echo $active_jobs;?> </td> <?php } else { ?> <th><?php _e('Backups in progress:', 'updraftplus');?></th> <td id="updraft_activejobs"><?php echo $active_jobs;?></td> <?php } ?> </tr> <tr id="updraft_lastlogmessagerow"> <?php if ($wide_format) { // Hide for now - too ugly ?> <td colspan="2" class="last-message"><strong><?php _e('Last log message','updraftplus');?>:</strong><br> <span id="updraft_lastlogcontainer"><?php echo htmlspecialchars(UpdraftPlus_Options::get_updraft_option('updraft_lastmessage', __('(Nothing yet logged)','updraftplus'))); ?></span><br> <?php $this->most_recently_modified_log_link(); ?> </td> <?php } else { ?> <th><?php _e('Last log message','updraftplus');?>:</th> <td> <span id="updraft_lastlogcontainer"><?php echo htmlspecialchars(UpdraftPlus_Options::get_updraft_option('updraft_lastmessage', __('(Nothing yet logged)','updraftplus'))); ?></span><br> <?php $this->most_recently_modified_log_link(); ?> </td> <?php } ?> </tr> <?php # Currently disabled - not sure who we want to show this to if (1==0 && !defined('UPDRAFTPLUS_NOADS_B')) { $feed = $updraftplus->get_updraftplus_rssfeed(); if (is_a($feed, 'SimplePie')) { echo '<tr><th style="vertical-align:top;">'.__('Latest UpdraftPlus.com news:', 'updraftplus').'</th><td class="updraft_simplepie">'; echo '<ul class="disc;">'; foreach ($feed->get_items(0, 5) as $item) { echo '<li>'; echo '<a href="'.esc_attr($item->get_permalink()).'">'; echo htmlspecialchars($item->get_title()); # D, F j, Y H:i echo "</a> (".htmlspecialchars($item->get_date('j F Y')).")"; echo '</li>'; } echo '</ul></td></tr>'; } } ?> </table> <?php } private function most_recently_modified_log_link() { global $updraftplus; list($mod_time, $log_file, $nonce) = $updraftplus->last_modified_log(); ?> <a href="?page=updraftplus&amp;action=downloadlatestmodlog&amp;wpnonce=<?php echo wp_create_nonce('updraftplus_download') ?>" <?php if (!$mod_time) echo 'style="display:none;"'; ?> class="updraft-log-link" onclick="event.preventDefault(); updraft_popuplog('');"><?php _e('Download most recently modified log file', 'updraftplus');?></a> <?php } public function settings_downloading_and_restoring($backup_history = array(), $return_result = false, $options = array()) { global $updraftplus; if ($return_result) ob_start(); $default_options = array( 'include_uploader' => true, 'include_opera_warning' => false, 'will_immediately_calculate_disk_space' => true, 'include_whitespace_warning' => true, 'include_header' => false, ); foreach ($default_options as $k => $v) { if (!isset($options[$k])) $options[$k] = $v; } if (false === $backup_history) $backup_history = UpdraftPlus_Options::get_updraft_option('updraft_backup_history'); if (!is_array($backup_history)) $backup_history=array(); if (!empty($options['include_header'])) echo '<h2>'.__('Existing Backups', 'updraftplus').' ('.count($backup_history).')</h2>'; ?> <div class="download-backups form-table"> <?php /* echo '<h2>'.__('Existing Backups: Downloading And Restoring', 'updraftplus').'</h2>'; */ ?> <?php if (!empty($options['include_whitespace_warning'])) { ?> <p class="ud-whitespace-warning updraft-hidden" style="display:none;"> <?php echo '<strong>'.__('Warning','updraftplus').':</strong> '.__('Your WordPress installation has a problem with outputting extra whitespace. This can corrupt backups that you download from here.','updraftplus').' <a href="https://updraftplus.com/problems-with-extra-white-space/">'.__('Please consult this FAQ for help on what to do about it.', 'updraftplus').'</a>';?> </p> <?php } ?> <ul> <li title="<?php esc_attr_e('This is a count of the contents of your Updraft directory', 'updraftplus');?>"><strong><?php _e('Web-server disk space in use by UpdraftPlus', 'updraftplus');?>:</strong> <span class="updraft_diskspaceused"><em><?php echo empty($options['will_immediately_calculate_disk_space']) ? '' : __('calculating...', 'updraftplus'); ?></em></span> <a class="updraft_diskspaceused_update" href="#"><?php echo empty($options['will_immediately_calculate_disk_space']) ? __('calculate', 'updraftplus') : __('refresh','updraftplus');?></a></li> <li> <strong><?php _e('More tasks:', 'updraftplus');?></strong> <?php if (!empty($options['include_uploader'])) { ?><a class="updraft_uploader_toggle" href="#"><?php _e('Upload backup files', 'updraftplus');?></a> | <?php } ?> <a href="#" class="updraft_rescan_local" title="<?php echo __('Press here to look inside your UpdraftPlus directory (in your web hosting space) for any new backup sets that you have uploaded.', 'updraftplus').' '.__('The location of this directory is set in the expert settings, in the Settings tab.', 'updraftplus'); ?>"><?php _e('Rescan local folder for new backup sets', 'updraftplus');?></a> | <a href="#" class="updraft_rescan_remote" title="<?php _e('Press here to look inside your remote storage methods for any existing backup sets (from any site, if they are stored in the same folder).', 'updraftplus'); ?>"><?php _e('Rescan remote storage','updraftplus');?></a> </li> <?php if (!empty($options['include_opera_warning'])) { ?> <li><strong><?php _e('Opera web browser', 'updraftplus');?>:</strong> <?php _e('If you are using this, then turn Turbo/Road mode off.', 'updraftplus');?></li> <?php } ?> </ul> <?php if (!empty($options['include_uploader'])) { ?> <div id="updraft-plupload-modal" style="display:none;" title="<?php _e('UpdraftPlus - Upload backup files','updraftplus'); ?>"> <p class="upload"><em><?php _e("Upload files into UpdraftPlus." ,'updraftplus');?> <?php echo htmlspecialchars(__('Or, you can place them manually into your UpdraftPlus directory (usually wp-content/updraft), e.g. via FTP, and then use the "rescan" link above.', 'updraftplus'));?></em></p> <?php global $wp_version; if (version_compare($wp_version, '3.3', '<')) { echo '<em>'.sprintf(__('This feature requires %s version %s or later', 'updraftplus'), 'WordPress', '3.3').'</em>'; } else { ?> <div id="plupload-upload-ui"> <div id="drag-drop-area"> <div class="drag-drop-inside"> <p class="drag-drop-info"><?php _e('Drop backup files here', 'updraftplus'); ?></p> <p><?php _ex('or', 'Uploader: Drop backup files here - or - Select Files'); ?></p> <p class="drag-drop-buttons"><input id="plupload-browse-button" type="button" value="<?php esc_attr_e('Select Files'); ?>" class="button" /></p> </div> </div> <div id="filelist"> </div> </div> <?php } ?> </div> <?php } ?> <div class="ud_downloadstatus"></div> <div class="updraft_existing_backups"> <?php echo $this->existing_backup_table($backup_history); ?> </div> </div> <?php if ($return_result) return ob_get_clean(); } public function settings_delete_and_restore_modals($return_result = false) { global $updraftplus; if ($return_result) ob_start(); ?> <div id="ud_massactions" class="updraft-hidden" style="display:none;"> <strong><?php _e('Actions upon selected backups', 'updraftplus');?></strong> <br> <div class="updraftplus-remove" style="float: left;"><a href="#" onclick="updraft_deleteallselected(); return false;"><?php _e('Delete', 'updraftplus');?></a></div> <div class="updraft-viewlogdiv"><a href="#" onclick="jQuery('#updraft-navtab-backups-content .updraft_existing_backups .updraft_existing_backups_row').addClass('backuprowselected'); return false;"><?php _e('Select all', 'updraftplus');?></a></div> <div class="updraft-viewlogdiv"><a href="#" onclick="jQuery('#updraft-navtab-backups-content .updraft_existing_backups .updraft_existing_backups_row').removeClass('backuprowselected'); jQuery('#ud_massactions').hide(); return false;"><?php _e('Deselect', 'updraftplus');?></a></div> </div> <div id="updraft-message-modal" title="UpdraftPlus"> <div id="updraft-message-modal-innards"> </div> </div> <div id="updraft-delete-modal" title="<?php _e('Delete backup set', 'updraftplus');?>"> <form id="updraft_delete_form" method="post"> <p id="updraft_delete_question_singular"> <?php echo sprintf(__('Are you sure that you wish to remove %s from UpdraftPlus?', 'updraftplus'), __('this backup set', 'updraftplus')); ?> </p> <p id="updraft_delete_question_plural" class="updraft-hidden" style="display:none;"> <?php echo sprintf(__('Are you sure that you wish to remove %s from UpdraftPlus?', 'updraftplus'), __('these backup sets', 'updraftplus')); ?> </p> <fieldset> <input type="hidden" name="nonce" value="<?php echo wp_create_nonce('updraftplus-credentialtest-nonce');?>"> <input type="hidden" name="action" value="updraft_ajax"> <input type="hidden" name="subaction" value="deleteset"> <input type="hidden" name="backup_timestamp" value="0" id="updraft_delete_timestamp"> <input type="hidden" name="backup_nonce" value="0" id="updraft_delete_nonce"> <div id="updraft-delete-remote-section"><input checked="checked" type="checkbox" name="delete_remote" id="updraft_delete_remote" value="1"> <label for="updraft_delete_remote"><?php _e('Also delete from remote storage', 'updraftplus');?></label><br> <p id="updraft-delete-waitwarning" class="updraft-hidden" style="display:none;"><em><?php _e('Deleting... please allow time for the communications with the remote storage to complete.', 'updraftplus');?></em></p> </div> </fieldset> </form> </div> <div id="updraft-restore-modal" title="UpdraftPlus - <?php _e('Restore backup','updraftplus');?>"> <p><strong><?php _e('Restore backup from','updraftplus');?>:</strong> <span class="updraft_restore_date"></span></p> <div id="updraft-restore-modal-stage2"> <p><strong><?php _e('Retrieving (if necessary) and preparing backup files...', 'updraftplus');?></strong></p> <div id="ud_downloadstatus2"></div> <div id="updraft-restore-modal-stage2a"></div> </div> <div id="updraft-restore-modal-stage1"> <p><?php _e("Restoring will replace this site's themes, plugins, uploads, database and/or other content directories (according to what is contained in the backup set, and your selection).",'updraftplus');?> <?php _e('Choose the components to restore','updraftplus');?>:</p> <form id="updraft_restore_form" method="post"> <fieldset> <input type="hidden" name="action" value="updraft_restore"> <input type="hidden" name="backup_timestamp" value="0" id="updraft_restore_timestamp"> <input type="hidden" name="meta_foreign" value="0" id="updraft_restore_meta_foreign"> <input type="hidden" name="updraft_restorer_backup_info" value="" id="updraft_restorer_backup_info"> <input type="hidden" name="updraft_restorer_restore_options" value="" id="updraft_restorer_restore_options"> <?php # The 'off' check is for badly configured setups - http://wordpress.org/support/topic/plugin-wp-super-cache-warning-php-safe-mode-enabled-but-safe-mode-is-off if ($updraftplus->detect_safe_mode()) { echo "<p><em>".__("Your web server has PHP's so-called safe_mode active.", 'updraftplus').' '.__('This makes time-outs much more likely. You are recommended to turn safe_mode off, or to restore only one entity at a time, <a href="https://updraftplus.com/faqs/i-want-to-restore-but-have-either-cannot-or-have-failed-to-do-so-from-the-wp-admin-console/">or to restore manually</a>.', 'updraftplus')."</em></p><br/>"; } $backupable_entities = $updraftplus->get_backupable_file_entities(true, true); foreach ($backupable_entities as $type => $info) { if (!isset($info['restorable']) || $info['restorable'] == true) { echo '<div><input id="updraft_restore_'.$type.'" type="checkbox" name="updraft_restore[]" value="'.$type.'"> <label id="updraft_restore_label_'.$type.'" for="updraft_restore_'.$type.'">'.$info['description'].'</label><br>'; do_action("updraftplus_restore_form_$type"); echo '</div>'; } else { $sdescrip = isset($info['shortdescription']) ? $info['shortdescription'] : $info['description']; echo "<div class=\"cannot-restore\"><em>".htmlspecialchars(sprintf(__('The following entity cannot be restored automatically: "%s".', 'updraftplus'), $sdescrip))." ".__('You will need to restore it manually.', 'updraftplus')."</em><br>".'<input id="updraft_restore_'.$type.'" type="hidden" name="updraft_restore[]" value="'.$type.'">'; echo '</div>'; } } ?> <div><input id="updraft_restore_db" type="checkbox" name="updraft_restore[]" value="db"> <label for="updraft_restore_db"><?php _e('Database','updraftplus'); ?></label><br> <div id="updraft_restorer_dboptions" class="updraft-hidden" style="display:none;"><h4><?php echo sprintf(__('%s restoration options:','updraftplus'),__('Database','updraftplus')); ?></h4> <?php do_action("updraftplus_restore_form_db"); if (!class_exists('UpdraftPlus_Addons_Migrator')) { echo '<a href="https://updraftplus.com/faqs/tell-me-more-about-the-search-and-replace-site-location-in-the-database-option/">'.__('You can search and replace your database (for migrating a website to a new location/URL) with the Migrator add-on - follow this link for more information','updraftplus').'</a>'; } ?> </div> </div> </fieldset> </form> <p><em><a href="https://updraftplus.com/faqs/what-should-i-understand-before-undertaking-a-restoration/" target="_blank"><?php _e('Do read this helpful article of useful things to know before restoring.','updraftplus');?></a></em></p> </div> </div> <?php if ($return_result) return ob_get_clean(); } public function settings_debugrow($head, $content) { echo "<tr class=\"updraft_debugrow\"><th>$head</th><td>$content</td></tr>"; } private function settings_expertsettings($backup_disabled) { global $updraftplus, $wpdb; $backupable_entities = $updraftplus->get_backupable_file_entities(true, true); ?> <div class="expertmode"> <p><em><?php _e('Unless you have a problem, you can completely ignore everything here.', 'updraftplus');?></em></p> <table> <?php // It appears (Mar 2015) that some mod_security distributions block the output of the string el6.x86_64 in PHP output, on the silly assumption that only hackers are interested in knowing what environment PHP is running on. // $uname_info = @php_uname(); $uname_info = @php_uname('s').' '.@php_uname('n').' '; $release_name = @php_uname('r'); if (preg_match('/^(.*)\.(x86_64|[3456]86)$/', $release_name, $matches)) { $release_name = $matches[1].' '; } else { $release_name = ''; } // In case someone does something similar with just the processor type string $mtype = @php_uname('m'); if ('x86_64' == $mtype) { $mtype = '64-bit'; } elseif (preg_match('/^i([3456]86)$/', $mtype, $matches)) { $mtype = $matches[1]; } $uname_info .= $release_name.$mtype.' '.@php_uname('v'); $this->settings_debugrow(__('Web server:','updraftplus'), htmlspecialchars($_SERVER["SERVER_SOFTWARE"]).' ('.htmlspecialchars($uname_info).')'); $this->settings_debugrow('ABSPATH:', htmlspecialchars(ABSPATH)); $this->settings_debugrow('WP_CONTENT_DIR:', htmlspecialchars(WP_CONTENT_DIR)); $this->settings_debugrow('WP_PLUGIN_DIR:', htmlspecialchars(WP_PLUGIN_DIR)); $this->settings_debugrow('Table prefix:', htmlspecialchars($updraftplus->get_table_prefix())); $peak_memory_usage = memory_get_peak_usage(true)/1024/1024; $memory_usage = memory_get_usage(true)/1024/1024; $this->settings_debugrow(__('Peak memory usage','updraftplus').':', $peak_memory_usage.' MB'); $this->settings_debugrow(__('Current memory usage','updraftplus').':', $memory_usage.' MB'); $this->settings_debugrow(__('Memory limit', 'updraftplus').':', htmlspecialchars(ini_get('memory_limit'))); $this->settings_debugrow(sprintf(__('%s version:','updraftplus'), 'PHP'), htmlspecialchars(phpversion()).' - <a href="admin-ajax.php?page=updraftplus&action=updraft_ajax&subaction=phpinfo&nonce='.wp_create_nonce('updraftplus-credentialtest-nonce').'" id="updraftplus-phpinfo">'.__('show PHP information (phpinfo)', 'updraftplus').'</a>'); $this->settings_debugrow(sprintf(__('%s version:','updraftplus'), 'MySQL'), htmlspecialchars($wpdb->db_version())); if (function_exists('curl_version') && function_exists('curl_exec')) { $cv = curl_version(); $cvs = $cv['version'].' / SSL: '.$cv['ssl_version'].' / libz: '.$cv['libz_version']; } else { $cvs = __('Not installed', 'updraftplus').' ('.__('required for some remote storage providers', 'updraftplus').')'; } $this->settings_debugrow(sprintf(__('%s version:', 'updraftplus'), 'Curl'), htmlspecialchars($cvs)); $this->settings_debugrow(sprintf(__('%s version:', 'updraftplus'), 'OpenSSL'), defined('OPENSSL_VERSION_TEXT') ? OPENSSL_VERSION_TEXT : '-'); $this->settings_debugrow('MCrypt:', function_exists('mcrypt_encrypt') ? __('Yes') : __('No')); if (version_compare(phpversion(), '5.2.0', '>=') && extension_loaded('zip')) { $ziparchive_exists = __('Yes', 'updraftplus'); } else { # First do class_exists, because method_exists still sometimes segfaults due to a rare PHP bug $ziparchive_exists = (class_exists('ZipArchive') && method_exists('ZipArchive', 'addFile')) ? __('Yes', 'updraftplus') : __('No', 'updraftplus'); } $this->settings_debugrow('ZipArchive::addFile:', $ziparchive_exists); $binzip = $updraftplus->find_working_bin_zip(false, false); $this->settings_debugrow(__('zip executable found:', 'updraftplus'), ((is_string($binzip)) ? __('Yes').': '.$binzip : __('No'))); $hosting_bytes_free = $updraftplus->get_hosting_disk_quota_free(); if (is_array($hosting_bytes_free)) { $perc = round(100*$hosting_bytes_free[1]/(max($hosting_bytes_free[2], 1)), 1); $this->settings_debugrow(__('Free disk space in account:', 'updraftplus'), sprintf(__('%s (%s used)', 'updraftplus'), round($hosting_bytes_free[3]/1048576, 1)." MB", "$perc %")); } $this->settings_debugrow(__('Plugins for debugging:', 'updraftplus'),'<a href="'.wp_nonce_url(self_admin_url('update.php?action=install-plugin&updraftplus_noautobackup=1&plugin=wp-crontrol'), 'install-plugin_wp-crontrol').'">WP Crontrol</a> | <a href="'.wp_nonce_url(self_admin_url('update.php?action=install-plugin&updraftplus_noautobackup=1&plugin=sql-executioner'), 'install-plugin_sql-executioner').'">SQL Executioner</a> | <a href="'.wp_nonce_url(self_admin_url('update.php?action=install-plugin&updraftplus_noautobackup=1&plugin=advanced-code-editor'), 'install-plugin_advanced-code-editor').'">Advanced Code Editor</a> '.(current_user_can('edit_plugins') ? '<a href="'.self_admin_url('plugin-editor.php?file=updraftplus/updraftplus.php').'">(edit UpdraftPlus)</a>' : '').' | <a href="'.wp_nonce_url(self_admin_url('update.php?action=install-plugin&updraftplus_noautobackup=1&plugin=wp-filemanager'), 'install-plugin_wp-filemanager').'">WP Filemanager</a>'); $this->settings_debugrow("HTTP Get: ", '<input id="updraftplus_httpget_uri" type="text" class="call-action"> <a href="#" id="updraftplus_httpget_go">'.__('Fetch', 'updraftplus').'</a> <a href="#" id="updraftplus_httpget_gocurl">'.__('Fetch', 'updraftplus').' (Curl)</a><p id="updraftplus_httpget_results"></p>'); $this->settings_debugrow(__("Call WordPress action:", 'updraftplus'), '<input id="updraftplus_callwpaction" type="text" class="call-action"> <a href="#" id="updraftplus_callwpaction_go">'.__('Call', 'updraftplus').'</a><div id="updraftplus_callwpaction_results"></div>'); $this->settings_debugrow('Site ID:', '(used to identify any Vault connections) <span id="updraft_show_sid">'.htmlspecialchars($updraftplus->siteid()).'</span> - <a href="#" id="updraft_reset_sid">'.__('reset', 'updraftplus')."</a>"); $this->settings_debugrow('', '<a href="admin-ajax.php?page=updraftplus&action=updraft_ajax&subaction=backuphistoryraw&nonce='.wp_create_nonce('updraftplus-credentialtest-nonce').'" id="updraftplus-rawbackuphistory">'.__('Show raw backup and file list', 'updraftplus').'</a>'); echo '</table>'; do_action('updraftplus_debugtools_dashboard'); if (!class_exists('UpdraftPlus_Addon_LockAdmin')) { echo '<p class="updraftplus-lock-advert"><a href="https://updraftplus.com/shop/updraftplus-premium/"><em>'.__('For the ability to lock access to UpdraftPlus settings with a password, upgrade to UpdraftPlus Premium.', 'updraftplus').'</em></a></p>'; } echo '<h3>'.__('Total (uncompressed) on-disk data:','updraftplus').'</h3>'; echo '<p class="uncompressed-data"><em>'.__('N.B. This count is based upon what was, or was not, excluded the last time you saved the options.', 'updraftplus').'</em></p><table>'; foreach ($backupable_entities as $key => $info) { $sdescrip = preg_replace('/ \(.*\)$/', '', $info['description']); if (strlen($sdescrip) > 20 && isset($info['shortdescription'])) $sdescrip = $info['shortdescription']; // echo '<div style="clear: left;float:left; width:150px;">'.ucfirst($sdescrip).':</strong></div><div style="float:left;"><span id="updraft_diskspaceused_'.$key.'"><em></em></span> <a href="#" onclick="updraftplus_diskspace_entity(\''.$key.'\'); return false;">'.__('count','updraftplus').'</a></div>'; $this->settings_debugrow(ucfirst($sdescrip).':', '<span id="updraft_diskspaceused_'.$key.'"><em></em></span> <a href="#" onclick="updraftplus_diskspace_entity(\''.$key.'\'); return false;">'.__('count','updraftplus').'</a>'); } ?> </table> <p class="immediate-run"><?php _e('The buttons below will immediately execute a backup run, independently of WordPress\'s scheduler. If these work whilst your scheduled backups do absolutely nothing (i.e. not even produce a log file), then it means that your scheduler is broken.','updraftplus');?> <a href="https://updraftplus.com/faqs/my-scheduled-backups-and-pressing-backup-now-does-nothing-however-pressing-debug-backup-does-produce-a-backup/"><?php _e('Go here for more information.', 'updraftplus'); ?></a></p> <table border="0" class="debug-table"> <tbody> <tr> <td> <form method="post" action="<?php echo esc_url(add_query_arg(array('error' => false, 'updraft_restore_success' => false, 'action' => false, 'page' => 'updraftplus'))); ?>"> <input type="hidden" name="action" value="updraft_backup_debug_all" /> <p><input type="submit" class="button-primary" <?php echo $backup_disabled ?> value="<?php _e('Debug Full Backup','updraftplus');?>" onclick="return(confirm('<?php echo htmlspecialchars(__('This will cause an immediate backup. The page will stall loading until it finishes (ie, unscheduled).','updraftplus'));?>'))" /></p> </form> </td><td> <form method="post" action="<?php echo esc_url(add_query_arg(array('error' => false, 'updraft_restore_success' => false, 'action' => false, 'page' => 'updraftplus'))); ?>"> <input type="hidden" name="action" value="updraft_backup_debug_db" /> <p><input type="submit" class="button-primary" <?php echo $backup_disabled ?> value="<?php _e('Debug Database Backup','updraftplus');?>" onclick="return(confirm('<?php echo htmlspecialchars(__('This will cause an immediate DB backup. The page will stall loading until it finishes (ie, unscheduled). The backup may well run out of time; really this button is only helpful for checking that the backup is able to get through the initial stages, or for small WordPress sites..','updraftplus'));?>'))" /></p> </form> </td> </tr> </tbody> </table> <h3><?php _e('Wipe settings', 'updraftplus');?></h3> <p class="max-width-600"><?php echo __('This button will delete all UpdraftPlus settings and progress information for in-progress backups (but not any of your existing backups from your cloud storage).', 'updraftplus').' '.__('You will then need to enter all your settings again. You can also do this before deactivating/deinstalling UpdraftPlus if you wish.','updraftplus');?></p> <form method="post" action="<?php echo esc_url(add_query_arg(array('error' => false, 'updraft_restore_success' => false, 'action' => false, 'page' => 'updraftplus'))); ?>"> <input type="hidden" name="action" value="updraft_wipesettings" /> <p><input type="submit" class="button-primary" value="<?php _e('Wipe settings','updraftplus'); ?>" onclick="return(confirm('<?php echo esc_js(__('This will delete all your UpdraftPlus settings - are you sure you want to do this?', 'updraftplus'));?>'))" /></p> </form> </div> <?php } private function print_delete_old_dirs_form($include_blurb = true, $include_div = true) { if ($include_blurb) { if ($include_div) { echo '<div id="updraft_delete_old_dirs_pagediv" class="updated delete-old-directories">'; } echo '<p>'.__('Your WordPress install has old directories from its state before you restored/migrated (technical information: these are suffixed with -old). You should press this button to delete them as soon as you have verified that the restoration worked.','updraftplus').'</p>'; } ?> <form method="post" onsubmit="return updraft_delete_old_dirs();" action="<?php echo esc_url(add_query_arg(array('error' => false, 'updraft_restore_success' => false, 'action' => false, 'page' => 'updraftplus'))); ?>"> <?php wp_nonce_field('updraftplus-credentialtest-nonce'); ?> <input type="hidden" name="action" value="updraft_delete_old_dirs"> <input type="submit" class="button-primary" value="<?php echo esc_attr(__('Delete Old Directories', 'updraftplus'));?>" /> </form> <?php if ($include_blurb && $include_div) echo '</div>'; } private function get_cron($job_id = false) { $cron = get_option('cron'); if (!is_array($cron)) $cron = array(); if (false === $job_id) return $cron; foreach ($cron as $time => $job) { if (isset($job['updraft_backup_resume'])) { foreach ($job['updraft_backup_resume'] as $hook => $info) { if (isset($info['args'][1]) && $job_id == $info['args'][1]) { global $updraftplus; $jobdata = $updraftplus->jobdata_getarray($job_id); return (!is_array($jobdata)) ? false : array($time, $jobdata); } } } } } // A value for $this_job_only also causes something to always be returned (to allow detection of the job having started on the front-end) private function print_active_jobs($this_job_only = false) { $cron = $this->get_cron(); // $found_jobs = 0; $ret = ''; foreach ($cron as $time => $job) { if (isset($job['updraft_backup_resume'])) { foreach ($job['updraft_backup_resume'] as $hook => $info) { if (isset($info['args'][1])) { // $found_jobs++; $job_id = $info['args'][1]; if (false === $this_job_only || $job_id == $this_job_only) { $ret .= $this->print_active_job($job_id, false, $time, $info['args'][0]); } } } } } // A value for $this_job_only implies that output is required if (false !== $this_job_only && !$ret) { $ret = $this->print_active_job($this_job_only); if ('' == $ret) { // The presence of the exact ID matters to the front-end - indicates that the backup job has at least begun $ret = '<div class="active-jobs updraft_finished" id="updraft-jobid-'.$this_job_only.'"><em>'.__('The backup has finished running', 'updraftplus').'</em> - <a class="updraft-log-link" data-jobid="'.$this_job_only.'">'.__('View Log', 'updraftplus').'</a></div>'; } } // if (0 == $found_jobs) $ret .= '<p><em>'.__('(None)', 'updraftplus').'</em></p>'; return $ret; } private function print_active_job($job_id, $is_oneshot = false, $time = false, $next_resumption = false) { $ret = ''; global $updraftplus; $jobdata = $updraftplus->jobdata_getarray($job_id); if (false == apply_filters('updraftplus_print_active_job_continue', true, $is_oneshot, $next_resumption, $jobdata)) return ''; #if (!is_array($jobdata)) $jobdata = array(); if (!isset($jobdata['backup_time'])) return ''; $backupable_entities = $updraftplus->get_backupable_file_entities(true, true); $began_at = (isset($jobdata['backup_time'])) ? get_date_from_gmt(gmdate('Y-m-d H:i:s', (int)$jobdata['backup_time']), 'D, F j, Y H:i') : '?'; $jobstatus = empty($jobdata['jobstatus']) ? 'unknown' : $jobdata['jobstatus']; $stage = 0; switch ($jobstatus) { # Stage 0 case 'begun': $curstage = __('Backup begun', 'updraftplus'); break; # Stage 1 case 'filescreating': $stage = 1; $curstage = __('Creating file backup zips', 'updraftplus'); if (!empty($jobdata['filecreating_substatus']) && isset($backupable_entities[$jobdata['filecreating_substatus']['e']]['description'])) { $sdescrip = preg_replace('/ \(.*\)$/', '', $backupable_entities[$jobdata['filecreating_substatus']['e']]['description']); if (strlen($sdescrip) > 20 && isset($jobdata['filecreating_substatus']['e']) && is_array($jobdata['filecreating_substatus']['e']) && isset($backupable_entities[$jobdata['filecreating_substatus']['e']]['shortdescription'])) $sdescrip = $backupable_entities[$jobdata['filecreating_substatus']['e']]['shortdescription']; $curstage .= ' ('.$sdescrip.')'; if (isset($jobdata['filecreating_substatus']['i']) && isset($jobdata['filecreating_substatus']['t'])) { $stage = min(2, 1 + ($jobdata['filecreating_substatus']['i']/max($jobdata['filecreating_substatus']['t'],1))); } } break; case 'filescreated': $stage = 2; $curstage = __('Created file backup zips', 'updraftplus'); break; # Stage 4 case 'clouduploading': $stage = 4; $curstage = __('Uploading files to remote storage', 'updraftplus'); if (isset($jobdata['uploading_substatus']['t']) && isset($jobdata['uploading_substatus']['i'])) { $t = max((int)$jobdata['uploading_substatus']['t'], 1); $i = min($jobdata['uploading_substatus']['i']/$t, 1); $p = min($jobdata['uploading_substatus']['p'], 1); $pd = $i + $p/$t; $stage = 4 + $pd; $curstage .= ' '.sprintf(__('(%s%%, file %s of %s)', 'updraftplus'), floor(100*$pd), $jobdata['uploading_substatus']['i']+1, $t); } break; case 'pruning': $stage = 5; $curstage = __('Pruning old backup sets', 'updraftplus'); break; case 'resumingforerrors': $stage = -1; $curstage = __('Waiting until scheduled time to retry because of errors', 'updraftplus'); break; # Stage 6 case 'finished': $stage = 6; $curstage = __('Backup finished', 'updraftplus'); break; default: # Database creation and encryption occupies the space from 2 to 4. Databases are created then encrypted, then the next databae is created/encrypted, etc. if ('dbcreated' == substr($jobstatus, 0, 9)) { $jobstatus = 'dbcreated'; $whichdb = substr($jobstatus, 9); if (!is_numeric($whichdb)) $whichdb = 0; $howmanydbs = max((empty($jobdata['backup_database']) || !is_array($jobdata['backup_database'])) ? 1 : count($jobdata['backup_database']), 1); $perdbspace = 2/$howmanydbs; $stage = min(4, 2 + ($whichdb+2)*$perdbspace); $curstage = __('Created database backup', 'updraftplus'); } elseif ('dbcreating' == substr($jobstatus, 0, 10)) { $whichdb = substr($jobstatus, 10); if (!is_numeric($whichdb)) $whichdb = 0; $howmanydbs = (empty($jobdata['backup_database']) || !is_array($jobdata['backup_database'])) ? 1 : count($jobdata['backup_database']); $perdbspace = 2/$howmanydbs; $jobstatus = 'dbcreating'; $stage = min(4, 2 + $whichdb*$perdbspace); $curstage = __('Creating database backup', 'updraftplus'); if (!empty($jobdata['dbcreating_substatus']['t'])) { $curstage .= ' ('.sprintf(__('table: %s', 'updraftplus'), $jobdata['dbcreating_substatus']['t']).')'; if (!empty($jobdata['dbcreating_substatus']['i']) && !empty($jobdata['dbcreating_substatus']['a'])) { $substage = max(0.001, ($jobdata['dbcreating_substatus']['i'] / max($jobdata['dbcreating_substatus']['a'],1))); $stage += $substage * $perdbspace * 0.5; } } } elseif ('dbencrypting' == substr($jobstatus, 0, 12)) { $whichdb = substr($jobstatus, 12); if (!is_numeric($whichdb)) $whichdb = 0; $howmanydbs = (empty($jobdata['backup_database']) || !is_array($jobdata['backup_database'])) ? 1 : count($jobdata['backup_database']); $perdbspace = 2/$howmanydbs; $stage = min(4, 2 + $whichdb*$perdbspace + $perdbspace*0.5); $jobstatus = 'dbencrypting'; $curstage = __('Encrypting database', 'updraftplus'); } elseif ('dbencrypted' == substr($jobstatus, 0, 11)) { $whichdb = substr($jobstatus, 11); if (!is_numeric($whichdb)) $whichdb = 0; $howmanydbs = (empty($jobdata['backup_database']) || !is_array($jobdata['backup_database'])) ? 1 : count($jobdata['backup_database']); $jobstatus = 'dbencrypted'; $perdbspace = 2/$howmanydbs; $stage = min(4, 2 + $whichdb*$perdbspace + $perdbspace); $curstage = __('Encrypted database', 'updraftplus'); } else { $curstage = __('Unknown', 'updraftplus'); } } $runs_started = (empty($jobdata['runs_started'])) ? array() : $jobdata['runs_started']; $time_passed = (empty($jobdata['run_times'])) ? array() : $jobdata['run_times']; $last_checkin_ago = -1; if (is_array($time_passed)) { foreach ($time_passed as $run => $passed) { if (isset($runs_started[$run])) { $time_ago = microtime(true) - ($runs_started[$run] + $time_passed[$run]); if ($time_ago < $last_checkin_ago || $last_checkin_ago == -1) $last_checkin_ago = $time_ago; } } } $next_res_after = (int)$time-time(); $next_res_txt = ($is_oneshot) ? '' : ' - '.sprintf(__("next resumption: %d (after %ss)", 'updraftplus'), $next_resumption, $next_res_after). ' '; $last_activity_txt = ($last_checkin_ago >= 0) ? ' - '.sprintf(__('last activity: %ss ago', 'updraftplus'), floor($last_checkin_ago)).' ' : ''; if (($last_checkin_ago < 50 && $next_res_after>30) || $is_oneshot) { $show_inline_info = $last_activity_txt; $title_info = $next_res_txt; } else { $show_inline_info = $next_res_txt; $title_info = $last_activity_txt; } // Existence of the 'updraft-jobid-(id)' id is checked for in other places, so do not modify this $ret .= '<div class="job-id" id="updraft-jobid-'.$job_id.'"><span class="updraft_jobtimings next-resumption'; if (!empty($jobdata['is_autobackup'])) $ret .= ' isautobackup'; $ret .= '" data-jobid="'.$job_id.'" data-lastactivity="'.(int)$last_checkin_ago.'" data-nextresumption="'.$next_resumption.'" data-nextresumptionafter="'.$next_res_after.'" title="'.esc_attr(sprintf(__('Job ID: %s', 'updraftplus'), $job_id)).$title_info.'">'.$began_at.'</span> '; $ret .= $show_inline_info; $ret .= '- <a data-jobid="'.$job_id.'" href="'.UpdraftPlus_Options::admin_page_url().'?page=updraftplus&action=downloadlog&updraftplus_backup_nonce='.$job_id.'" class="updraft-log-link">'.__('show log', 'updraftplus').'</a>'; if (!$is_oneshot) $ret .=' - <a href="#" data-jobid="'.$job_id.'" title="'.esc_attr(__('Note: the progress bar below is based on stages, NOT time. Do not stop the backup simply because it seems to have remained in the same place for a while - that is normal.', 'updraftplus')).'" class="updraft_jobinfo_delete">'.__('stop', 'updraftplus').'</a>'; $ret .= apply_filters('updraft_printjob_beforewarnings', '', $jobdata, $job_id); if (!empty($jobdata['warnings']) && is_array($jobdata['warnings'])) { $ret .= '<ul class="disc">'; foreach ($jobdata['warnings'] as $warning) { $ret .= '<li>'.sprintf(__('Warning: %s', 'updraftplus'), make_clickable(htmlspecialchars($warning))).'</li>'; } $ret .= '</ul>'; } $ret .= '<div class="curstage">'; $ret .= htmlspecialchars($curstage); $ret .= '<div class="updraft_percentage" style="height: 100%; width:'.(($stage>0) ? (ceil((100/6)*$stage)) : '0').'%"></div>'; $ret .= '</div></div>'; $ret .= '</div>'; return $ret; } private function delete_old_dirs_go($show_return = true) { echo ($show_return) ? '<h1>UpdraftPlus - '.__('Remove old directories', 'updraftplus').'</h1>' : '<h2>'.__('Remove old directories', 'updraftplus').'</h2>'; if ($this->delete_old_dirs()) { echo '<p>'.__('Old directories successfully removed.','updraftplus').'</p><br/>'; } else { echo '<p>',__('Old directory removal failed for some reason. You may want to do this manually.','updraftplus').'</p><br/>'; } if ($show_return) echo '<b>'.__('Actions','updraftplus').':</b> <a href="'.UpdraftPlus_Options::admin_page_url().'?page=updraftplus">'.__('Return to UpdraftPlus Configuration','updraftplus').'</a>'; } //deletes the -old directories that are created when a backup is restored. private function delete_old_dirs() { global $wp_filesystem, $updraftplus; $credentials = request_filesystem_credentials(wp_nonce_url(UpdraftPlus_Options::admin_page_url()."?page=updraftplus&action=updraft_delete_old_dirs", 'updraftplus-credentialtest-nonce')); WP_Filesystem($credentials); if ($wp_filesystem->errors->get_error_code()) { foreach ($wp_filesystem->errors->get_error_messages() as $message) show_message($message); exit; } // From WP_CONTENT_DIR - which contains 'themes' $ret = $this->delete_old_dirs_dir($wp_filesystem->wp_content_dir()); $updraft_dir = $updraftplus->backups_dir_location(); if ($updraft_dir) { $ret4 = ($updraft_dir) ? $this->delete_old_dirs_dir($updraft_dir, false) : true; } else { $ret4 = true; } // $ret2 = $this->delete_old_dirs_dir($wp_filesystem->abspath()); $plugs = untrailingslashit($wp_filesystem->wp_plugins_dir()); if ($wp_filesystem->is_dir($plugs.'-old')) { print "<strong>".__('Delete','updraftplus').": </strong>plugins-old: "; if (!$wp_filesystem->delete($plugs.'-old', true)) { $ret3 = false; print "<strong>".__('Failed', 'updraftplus')."</strong><br>"; } else { $ret3 = true; print "<strong>".__('OK', 'updraftplus')."</strong><br>"; } } else { $ret3 = true; } return $ret && $ret3 && $ret4; } private function delete_old_dirs_dir($dir, $wpfs = true) { $dir = trailingslashit($dir); global $wp_filesystem, $updraftplus; if ($wpfs) { $list = $wp_filesystem->dirlist($dir); } else { $list = scandir($dir); } if (!is_array($list)) return false; $ret = true; foreach ($list as $item) { $name = (is_array($item)) ? $item['name'] : $item; if ("-old" == substr($name, -4, 4)) { //recursively delete print "<strong>".__('Delete','updraftplus').": </strong>".htmlspecialchars($name).": "; if ($wpfs) { if (!$wp_filesystem->delete($dir.$name, true)) { $ret = false; echo "<strong>".__('Failed', 'updraftplus')."</strong><br>"; } else { echo "<strong>".__('OK', 'updraftplus')."</strong><br>"; } } else { if ($updraftplus->remove_local_directory($dir.$name)) { echo "<strong>".__('OK', 'updraftplus')."</strong><br>"; } else { $ret = false; echo "<strong>".__('Failed', 'updraftplus')."</strong><br>"; } } } } return $ret; } // The aim is to get a directory that is writable by the webserver, because that's the only way we can create zip files private function create_backup_dir() { global $wp_filesystem, $updraftplus; if (false === ($credentials = request_filesystem_credentials(UpdraftPlus_Options::admin_page().'?page=updraftplus&action=updraft_create_backup_dir&nonce='.wp_create_nonce('create_backup_dir')))) { return false; } if ( ! WP_Filesystem($credentials) ) { // our credentials were no good, ask the user for them again request_filesystem_credentials(UpdraftPlus_Options::admin_page().'?page=updraftplus&action=updraft_create_backup_dir&nonce='.wp_create_nonce('create_backup_dir'), '', true); return false; } $updraft_dir = $updraftplus->backups_dir_location(); $default_backup_dir = $wp_filesystem->find_folder(dirname($updraft_dir)).basename($updraft_dir); $updraft_dir = ($updraft_dir) ? $wp_filesystem->find_folder(dirname($updraft_dir)).basename($updraft_dir) : $default_backup_dir; if (!$wp_filesystem->is_dir($default_backup_dir) && !$wp_filesystem->mkdir($default_backup_dir, 0775)) { $wperr = new WP_Error; if ( $wp_filesystem->errors->get_error_code() ) { foreach ( $wp_filesystem->errors->get_error_messages() as $message ) { $wperr->add('mkdir_error', $message); } return $wperr; } else { return new WP_Error('mkdir_error', __('The request to the filesystem to create the directory failed.', 'updraftplus')); } } if ($wp_filesystem->is_dir($default_backup_dir)) { if ($updraftplus->really_is_writable($updraft_dir)) return true; @$wp_filesystem->chmod($default_backup_dir, 0775); if ($updraftplus->really_is_writable($updraft_dir)) return true; @$wp_filesystem->chmod($default_backup_dir, 0777); if ($updraftplus->really_is_writable($updraft_dir)) { echo '<p>'.__('The folder was created, but we had to change its file permissions to 777 (world-writable) to be able to write to it. You should check with your hosting provider that this will not cause any problems', 'updraftplus').'</p>'; return true; } else { @$wp_filesystem->chmod($default_backup_dir, 0775); $show_dir = (0 === strpos($default_backup_dir, ABSPATH)) ? substr($default_backup_dir, strlen(ABSPATH)) : $default_backup_dir; return new WP_Error('writable_error', __('The folder exists, but your webserver does not have permission to write to it.', 'updraftplus').' '.__('You will need to consult with your web hosting provider to find out how to set permissions for a WordPress plugin to write to the directory.', 'updraftplus').' ('.$show_dir.')'); } } return true; } //scans the content dir to see if any -old dirs are present private function scan_old_dirs($print_as_comment = false) { global $updraftplus; $dirs = scandir(untrailingslashit(WP_CONTENT_DIR)); if (!is_array($dirs)) $dirs = array(); $dirs_u = @scandir($updraftplus->backups_dir_location()); if (!is_array($dirs_u)) $dirs_u = array(); foreach (array_merge($dirs, $dirs_u) as $dir) { if (preg_match('/-old$/', $dir)) { if ($print_as_comment) echo '<!--'.htmlspecialchars($dir).'-->'; return true; } } # No need to scan ABSPATH - we don't backup there if (is_dir(untrailingslashit(WP_PLUGIN_DIR).'-old')) { if ($print_as_comment) echo '<!--'.htmlspecialchars(untrailingslashit(WP_PLUGIN_DIR).'-old').'-->'; return true; } return false; } public function storagemethod_row($method, $header, $contents) { ?> <tr class="updraftplusmethod <?php echo $method;?>"> <th><?php echo $header;?></th> <td><?php echo $contents;?></td> </tr> <?php } private function last_backup_html() { global $updraftplus; $updraft_last_backup = UpdraftPlus_Options::get_updraft_option('updraft_last_backup'); if ($updraft_last_backup) { // Convert to GMT, then to blog time $backup_time = (int)$updraft_last_backup['backup_time']; $print_time = get_date_from_gmt(gmdate('Y-m-d H:i:s', $backup_time), 'D, F j, Y H:i'); // $print_time = date_i18n('D, F j, Y H:i', $backup_time); if (empty($updraft_last_backup['backup_time_incremental'])) { $last_backup_text = "<span style=\"color:".(($updraft_last_backup['success']) ? 'green' : 'black').";\">".$print_time.'</span>'; } else { $inc_time = get_date_from_gmt(gmdate('Y-m-d H:i:s', $updraft_last_backup['backup_time_incremental']), 'D, F j, Y H:i'); // $inc_time = date_i18n('D, F j, Y H:i', $updraft_last_backup['backup_time_incremental']); $last_backup_text = "<span style=\"color:".(($updraft_last_backup['success']) ? 'green' : 'black').";\">$inc_time</span> (".sprintf(__('incremental backup; base backup: %s', 'updraftplus'), $print_time).')'; } $last_backup_text .= '<br>'; // Show errors + warnings if (is_array($updraft_last_backup['errors'])) { foreach ($updraft_last_backup['errors'] as $err) { $level = (is_array($err)) ? $err['level'] : 'error'; $message = (is_array($err)) ? $err['message'] : $err; $last_backup_text .= ('warning' == $level) ? "<span style=\"color:orange;\">" : "<span style=\"color:red;\">"; if ('warning' == $level) { $message = sprintf(__("Warning: %s", 'updraftplus'), make_clickable(htmlspecialchars($message))); } else { $message = htmlspecialchars($message); } $last_backup_text .= $message; $last_backup_text .= '</span><br>'; } } // Link log if (!empty($updraft_last_backup['backup_nonce'])) { $updraft_dir = $updraftplus->backups_dir_location(); $potential_log_file = $updraft_dir."/log.".$updraft_last_backup['backup_nonce'].".txt"; if (is_readable($potential_log_file)) $last_backup_text .= "<a href=\"?page=updraftplus&action=downloadlog&updraftplus_backup_nonce=".$updraft_last_backup['backup_nonce']."\" class=\"updraft-log-link\" onclick=\"event.preventDefault(); updraft_popuplog('".$updraft_last_backup['backup_nonce']."');\">".__('Download log file','updraftplus')."</a>"; } } else { $last_backup_text = "<span style=\"color:blue;\">".__('No backup has been completed','updraftplus')."</span>"; } return $last_backup_text; } public function get_intervals() { return apply_filters('updraftplus_backup_intervals', array( 'manual' => _x("Manual", 'i.e. Non-automatic', 'updraftplus'), 'every4hours' => sprintf(__("Every %s hours", 'updraftplus'), '4'), 'every8hours' => sprintf(__("Every %s hours", 'updraftplus'), '8'), 'twicedaily' => sprintf(__("Every %s hours", 'updraftplus'), '12'), 'daily' => __("Daily", 'updraftplus'), 'weekly' => __("Weekly", 'updraftplus'), 'fortnightly' => __("Fortnightly", 'updraftplus'), 'monthly' => __("Monthly", 'updraftplus') )); } private function really_writable_message($really_is_writable, $updraft_dir){ if ($really_is_writable) { $dir_info = '<span style="color:green;">'.__('Backup directory specified is writable, which is good.','updraftplus').'</span>'; } else { $dir_info = '<span style="color:red;">'; if (!is_dir($updraft_dir)) { $dir_info .= __('Backup directory specified does <b>not</b> exist.','updraftplus'); } else { $dir_info .= __('Backup directory specified exists, but is <b>not</b> writable.','updraftplus'); } $dir_info .= '<span class="updraft-directory-not-writable-blurb"><span class="directory-permissions"><a class="updraft_create_backup_dir" href="'.UpdraftPlus_Options::admin_page_url().'?page=updraftplus&action=updraft_create_backup_dir&nonce='.wp_create_nonce('create_backup_dir').'">'.__('Click here to attempt to create the directory and set the permissions','updraftplus').'</a></span>, '.__('or, to reset this option','updraftplus').' <a href="#" class="updraft_backup_dir_reset">'.__('click here','updraftplus').'</a>. '.__('If that is unsuccessful check the permissions on your server or change it to another directory that is writable by your web server process.','updraftplus').'</span>'; } return $dir_info; } public function settings_formcontents($options = array()) { global $updraftplus; $updraft_dir = $updraftplus->backups_dir_location(); $really_is_writable = $updraftplus->really_is_writable($updraft_dir); $default_options = array( 'include_database_decrypter' => true, 'include_adverts' => true, 'include_save_button' => true ); foreach ($default_options as $k => $v) { if (!isset($options[$k])) $options[$k] = $v; } ?> <table class="form-table"> <tr> <th><?php _e('Files backup schedule','updraftplus'); ?>:</th> <td> <div style="float:left; clear:both;"> <select class="updraft_interval" name="updraft_interval"> <?php $intervals = $this->get_intervals(); $selected_interval = UpdraftPlus_Options::get_updraft_option('updraft_interval', 'manual'); foreach ($intervals as $cronsched => $descrip) { echo "<option value=\"$cronsched\" "; if ($cronsched == $selected_interval) echo 'selected="selected"'; echo ">".htmlspecialchars($descrip)."</option>\n"; } ?> </select> <span class="updraft_files_timings"><?php echo apply_filters('updraftplus_schedule_showfileopts', '<input type="hidden" name="updraftplus_starttime_files" value="">', $selected_interval); ?></span> <?php $updraft_retain = max((int)UpdraftPlus_Options::get_updraft_option('updraft_retain', 2), 1); $retain_files_config = __('and retain this many scheduled backups', 'updraftplus').': <input type="number" min="1" step="1" name="updraft_retain" value="'.$updraft_retain.'" class="retain-files" />'; // echo apply_filters('updraftplus_retain_files_intervalline', $retain_files_config, $updraft_retain); echo $retain_files_config; ?> </div> <?php do_action('updraftplus_after_filesconfig'); ?> </td> </tr> <?php if (defined('UPDRAFTPLUS_EXPERIMENTAL') && UPDRAFTPLUS_EXPERIMENTAL) { ?> <tr class="updraft_incremental_row"> <th><?php _e('Incremental file backup schedule', 'updraftplus'); ?>:</th> <td> <?php do_action('updraftplus_incremental_cell', $selected_interval); ?> <a href="https://updraftplus.com/support/tell-me-more-about-incremental-backups/"><em><?php _e('Tell me more about incremental backups', 'updraftplus'); ?><em></a> </td> </tr> <?php } ?> <?php apply_filters('updraftplus_after_file_intervals', false, $selected_interval); ?> <tr> <th><?php _e('Database backup schedule','updraftplus'); ?>:</th> <td> <div style="float:left; clear:both;"> <select class="updraft_interval_database" name="updraft_interval_database"> <?php $selected_interval_db = UpdraftPlus_Options::get_updraft_option('updraft_interval_database', UpdraftPlus_Options::get_updraft_option('updraft_interval')); foreach ($intervals as $cronsched => $descrip) { echo "<option value=\"$cronsched\" "; if ($cronsched == $selected_interval_db) echo 'selected="selected"'; echo ">$descrip</option>\n"; } ?> </select> <span class="updraft_same_schedules_message"><?php echo apply_filters('updraftplus_schedule_sametimemsg', '');?></span><span class="updraft_db_timings"><?php echo apply_filters('updraftplus_schedule_showdbopts', '<input type="hidden" name="updraftplus_starttime_db" value="">', $selected_interval_db); ?></span> <?php $updraft_retain_db = max((int)UpdraftPlus_Options::get_updraft_option('updraft_retain_db', $updraft_retain), 1); $retain_dbs_config = __('and retain this many scheduled backups', 'updraftplus').': <input type="number" min="1" step="1" name="updraft_retain_db" value="'.$updraft_retain_db.'" class="retain-files" />'; // echo apply_filters('updraftplus_retain_db_intervalline', $retain_dbs_config, $updraft_retain_db); echo $retain_dbs_config; ?> </div> <?php do_action('updraftplus_after_dbconfig'); ?> </td> </tr> <tr class="backup-interval-description"> <th></th> <td><div> <?php echo apply_filters('updraftplus_fixtime_ftinfo', '<p>'.__('To fix the time at which a backup should take place,','updraftplus').' ('.__('e.g. if your server is busy at day and you want to run overnight','updraftplus').'), '.__('or to configure more complex schedules', 'updraftplus').', <a href="https://updraftplus.com/shop/updraftplus-premium/">'.htmlspecialchars(__('use UpdraftPlus Premium', 'updraftplus')).'</a></p>'); ?> </div></td> </tr> </table> <h2 class="updraft_settings_sectionheading"><?php _e('Sending Your Backup To Remote Storage','updraftplus');?></h2> <?php $debug_mode = UpdraftPlus_Options::get_updraft_option('updraft_debug_mode') ? 'checked="checked"' : ""; $active_service = UpdraftPlus_Options::get_updraft_option('updraft_service'); ?> <table class="form-table width-900"> <tr> <th><?php echo __('Choose your remote storage','updraftplus').'<br>'.apply_filters('updraftplus_after_remote_storage_heading_message', '<em>'.__('(tap on an icon to select or unselect)', 'updraftplus').'</em>'); ?>:</th> <td> <div id="remote-storage-container"> <?php if (is_array($active_service)) $active_service = $updraftplus->just_one($active_service); //Change this to give a class that we can exclude $multi = apply_filters('updraftplus_storage_printoptions_multi', ''); foreach($updraftplus->backup_methods as $method => $description) { $backup_using = esc_attr(sprintf(__("Backup using %s?", 'updraftplus'), $description)); echo "<input aria-label=\"$backup_using\" name=\"updraft_service[]\" class=\"updraft_servicecheckbox $method $multi\" id=\"updraft_servicecheckbox_$method\" type=\"checkbox\" value=\"$method\""; if ($active_service === $method || (is_array($active_service) && in_array($method, $active_service))) echo ' checked="checked"'; echo " data-labelauty=\"".esc_attr($description)."\">"; } ?> <?php if (false === apply_filters('updraftplus_storage_printoptions', false, $active_service)) { echo '</div>'; echo '<p><a href="https://updraftplus.com/shop/morestorage/">'.htmlspecialchars(__('You can send a backup to more than one destination with an add-on.','updraftplus')).'</a></p>'; echo '</td></tr>'; } ?> <tr class="updraftplusmethod none ud_nostorage" style="display:none;"> <td></td> <td><em><?php echo htmlspecialchars(__('If you choose no remote storage, then the backups remain on the web-server. This is not recommended (unless you plan to manually copy them to your computer), as losing the web-server would mean losing both your website and the backups in one event.', 'updraftplus'));?></em></td> </tr> <?php $method_objects = array(); foreach ($updraftplus->backup_methods as $method => $description) { do_action('updraftplus_config_print_before_storage', $method); require_once(UPDRAFTPLUS_DIR.'/methods/'.$method.'.php'); $call_method = 'UpdraftPlus_BackupModule_'.$method; $method_objects[$method] = new $call_method; $method_objects[$method]->config_print(); do_action('updraftplus_config_print_after_storage', $method); } ?> </table> <hr style="width:900px; float:left;"> <h2 class="updraft_settings_sectionheading"><?php _e('File Options', 'updraftplus');?></h2> <table class="form-table" > <tr> <th><?php _e('Include in files backup', 'updraftplus');?>:</th> <td> <?php echo $this->files_selector_widgetry(); ?> <p><?php echo apply_filters('updraftplus_admin_directories_description', __('The above directories are everything, except for WordPress core itself which you can download afresh from WordPress.org.', 'updraftplus').' <a href="https://updraftplus.com/shop/">'.htmlspecialchars(__('See also the "More Files" add-on from our shop.', 'updraftplus')).'</a>'); ?></p> </td> </tr> </table> <h2 class="updraft_settings_sectionheading"><?php _e('Database Options','updraftplus');?></h2> <table class="form-table width-900"> <tr> <th><?php _e('Database encryption phrase', 'updraftplus');?>:</th> <td> <?php echo apply_filters('updraft_database_encryption_config', '<a href="https://updraftplus.com/shop/updraftplus-premium/">'.__("Don't want to be spied on? UpdraftPlus Premium can encrypt your database backup.", 'updraftplus').'</a> '.__('It can also backup external databases.', 'updraftplus')); ?> </td> </tr> <?php if (!empty($options['include_database_decrypter'])) { ?> <tr class="backup-crypt-description"> <td></td> <td> <a href="#" class="updraft_show_decryption_widget"><?php _e('You can manually decrypt an encrypted database here.','updraftplus');?></a> <div id="updraft-manualdecrypt-modal" class="updraft-hidden" style="display:none;"> <p><h3><?php _e("Manually decrypt a database backup file" ,'updraftplus');?></h3></p> <?php global $wp_version; if (version_compare($wp_version, '3.3', '<')) { echo '<em>'.sprintf(__('This feature requires %s version %s or later', 'updraftplus'), 'WordPress', '3.3').'</em>'; } else { ?> <div id="plupload-upload-ui2"> <div id="drag-drop-area2"> <div class="drag-drop-inside"> <p class="drag-drop-info"><?php _e('Drop encrypted database files (db.gz.crypt files) here to upload them for decryption', 'updraftplus'); ?></p> <p><?php _ex('or', 'Uploader: Drop db.gz.crypt files here to upload them for decryption - or - Select Files', 'updraftplus'); ?></p> <p class="drag-drop-buttons"><input id="plupload-browse-button2" type="button" value="<?php esc_attr_e('Select Files', 'updraftplus'); ?>" class="button" /></p> <p style="margin-top: 18px;"><?php _e('First, enter the decryption key','updraftplus')?>: <input id="updraftplus_db_decrypt" type="text" size="12"></input></p> </div> </div> <div id="filelist2"> </div> </div> <?php } ?> </div> </td> </tr> <?php } ?> <?php #'<a href="https://updraftplus.com/shop/updraftplus-premium/">'.__("This feature is part of UpdraftPlus Premium.", 'updraftplus').'</a>' $moredbs_config = apply_filters('updraft_database_moredbs_config', false); if (!empty($moredbs_config)) { ?> <tr> <th><?php _e('Back up more databases', 'updraftplus');?>:</th> <td><?php echo $moredbs_config; ?> </td> </tr> <?php } ?> </table> <h2 class="updraft_settings_sectionheading"><?php _e('Reporting','updraftplus');?></h2> <table class="form-table" style="width:900px;"> <?php $report_rows = apply_filters('updraftplus_report_form', false); if (is_string($report_rows)) { echo $report_rows; } else { ?> <tr> <th><?php _e('Email', 'updraftplus'); ?>:</th> <td> <?php $updraft_email = UpdraftPlus_Options::get_updraft_option('updraft_email'); ?> <input type="checkbox" id="updraft_email" name="updraft_email" value="<?php esc_attr_e(get_bloginfo('admin_email')); ?>"<?php if (!empty($updraft_email)) echo ' checked="checked"';?> > <br><label for="updraft_email"><?php echo __("Check this box to have a basic report sent to", 'updraftplus').' <a href="'.admin_url('options-general.php').'">'.__("your site's admin address", 'updraftplus').'</a> ('.htmlspecialchars(get_bloginfo('admin_email')).")."; ?></label> <?php if (!class_exists('UpdraftPlus_Addon_Reporting')) echo '<a href="https://updraftplus.com/shop/reporting/">'.__('For more reporting features, use the Reporting add-on.', 'updraftplus').'</a>'; ?> </td> </tr> <?php } ?> </table> <script type="text/javascript"> /* <![CDATA[ */ <?php echo $this->get_settings_js($method_objects, $really_is_writable, $updraft_dir); ?> /* ]]> */ </script> <table class="form-table width-900"> <tr> <td colspan="2"><h2 class="updraft_settings_sectionheading"><?php _e('Advanced / Debugging Settings','updraftplus'); ?></h2></td> </tr> <tr> <th><?php _e('Expert settings','updraftplus');?>:</th> <td><a class="enableexpertmode" href="#enableexpertmode"><?php _e('Show expert settings','updraftplus');?></a> - <?php _e("click this to show some further options; don't bother with this unless you have a problem or are curious.",'updraftplus');?> <?php do_action('updraftplus_expertsettingsdescription'); ?></td> </tr> <?php $delete_local = UpdraftPlus_Options::get_updraft_option('updraft_delete_local', 1); $split_every_mb = UpdraftPlus_Options::get_updraft_option('updraft_split_every', 400); if (!is_numeric($split_every_mb)) $split_every_mb = 400; if ($split_every_mb < UPDRAFTPLUS_SPLIT_MIN) $split_every_mb = UPDRAFTPLUS_SPLIT_MIN; ?> <tr class="expertmode updraft-hidden" style="display:none;"> <th><?php _e('Debug mode','updraftplus');?>:</th> <td><input type="checkbox" id="updraft_debug_mode" name="updraft_debug_mode" value="1" <?php echo $debug_mode; ?> /> <br><label for="updraft_debug_mode"><?php _e('Check this to receive more information and emails on the backup process - useful if something is going wrong.','updraftplus');?> <?php _e('This will also cause debugging output from all plugins to be shown upon this screen - please do not be surprised to see these.', 'updraftplus');?></label></td> </tr> <tr class="expertmode updraft-hidden" style="display:none;"> <th><?php _e('Split archives every:','updraftplus');?></th> <td><input type="text" name="updraft_split_every" class="updraft_split_every" value="<?php echo $split_every_mb ?>" size="5" /> MB<br><?php echo sprintf(__('UpdraftPlus will split up backup archives when they exceed this file size. The default value is %s megabytes. Be careful to leave some margin if your web-server has a hard size limit (e.g. the 2 GB / 2048 MB limit on some 32-bit servers/file systems).','updraftplus'), 400); ?></td> </tr> <tr class="deletelocal expertmode updraft-hidden" style="display:none;"> <th><?php _e('Delete local backup','updraftplus');?>:</th> <td><input type="checkbox" id="updraft_delete_local" name="updraft_delete_local" value="1" <?php if ($delete_local) echo 'checked="checked"'; ?>> <br><label for="updraft_delete_local"><?php _e('Check this to delete any superfluous backup files from your server after the backup run finishes (i.e. if you uncheck, then any files despatched remotely will also remain locally, and any files being kept locally will not be subject to the retention limits).','updraftplus');?></label></td> </tr> <tr class="expertmode backupdirrow updraft-hidden" style="display:none;"> <th><?php _e('Backup directory','updraftplus');?>:</th> <td><input type="text" name="updraft_dir" id="updraft_dir" style="width:525px" value="<?php echo htmlspecialchars($this->prune_updraft_dir_prefix($updraft_dir)); ?>" /></td> </tr> <tr class="expertmode backupdirrow updraft-hidden" style="display:none;"> <td></td> <td> <span id="updraft_writable_mess"> <?php $dir_info = $this->really_writable_message($really_is_writable, $updraft_dir); echo $dir_info; ?> </span> <?php echo __("This is where UpdraftPlus will write the zip files it creates initially. This directory must be writable by your web server. It is relative to your content directory (which by default is called wp-content).", 'updraftplus').' '.__("<b>Do not</b> place it inside your uploads or plugins directory, as that will cause recursion (backups of backups of backups of...).", 'updraftplus'); ?> </td> </tr> <tr class="expertmode updraft-hidden" style="display:none;"> <th><?php _e("Use the server's SSL certificates", 'updraftplus');?>:</th> <td><input data-updraft_settings_test="useservercerts" type="checkbox" id="updraft_ssl_useservercerts" name="updraft_ssl_useservercerts" value="1" <?php if (UpdraftPlus_Options::get_updraft_option('updraft_ssl_useservercerts')) echo 'checked="checked"'; ?>> <br><label for="updraft_ssl_useservercerts"><?php _e('By default UpdraftPlus uses its own store of SSL certificates to verify the identity of remote sites (i.e. to make sure it is talking to the real Dropbox, Amazon S3, etc., and not an attacker). We keep these up to date. However, if you get an SSL error, then choosing this option (which causes UpdraftPlus to use your web server\'s collection instead) may help.','updraftplus');?></label></td> </tr> <tr class="expertmode updraft-hidden" style="display:none;"> <th><?php _e('Do not verify SSL certificates','updraftplus');?>:</th> <td><input data-updraft_settings_test="disableverify" type="checkbox" id="updraft_ssl_disableverify" name="updraft_ssl_disableverify" value="1" <?php if (UpdraftPlus_Options::get_updraft_option('updraft_ssl_disableverify')) echo 'checked="checked"'; ?>> <br><label for="updraft_ssl_disableverify"><?php _e('Choosing this option lowers your security by stopping UpdraftPlus from verifying the identity of encrypted sites that it connects to (e.g. Dropbox, Google Drive). It means that UpdraftPlus will be using SSL only for encryption of traffic, and not for authentication.','updraftplus');?> <?php _e('Note that not all cloud backup methods are necessarily using SSL authentication.', 'updraftplus');?></label></td> </tr> <tr class="expertmode updraft-hidden" style="display:none;"> <th><?php _e('Disable SSL entirely where possible', 'updraftplus');?>:</th> <td><input data-updraft_settings_test="nossl" type="checkbox" id="updraft_ssl_nossl" name="updraft_ssl_nossl" value="1" <?php if (UpdraftPlus_Options::get_updraft_option('updraft_ssl_nossl')) echo 'checked="checked"'; ?>> <br><label for="updraft_ssl_nossl"><?php _e('Choosing this option lowers your security by stopping UpdraftPlus from using SSL for authentication and encrypted transport at all, where possible. Note that some cloud storage providers do not allow this (e.g. Dropbox), so with those providers this setting will have no effect.','updraftplus');?> <a href="https://updraftplus.com/faqs/i-get-ssl-certificate-errors-when-backing-up-andor-restoring/"><?php _e('See this FAQ also.', 'updraftplus');?></a></label></td> </tr> <?php do_action('updraftplus_configprint_expertoptions'); ?> <tr> <td></td> <td> <?php $ws_ad = empty($options['include_adverts']) ? false : $updraftplus->wordshell_random_advert(1); if ($ws_ad) { ?> <p class="wordshell-advert"> <?php echo $ws_ad; ?> </p> <?php } ?> </td> </tr> <?php if (!empty($options['include_save_button'])) { ?> <tr> <td></td> <td> <input type="hidden" name="action" value="update" /> <input type="submit" class="button-primary" id="updraftplus-settings-save" value="<?php _e('Save Changes','updraftplus');?>" /> </td> </tr> <?php } ?> </table> <?php } private function get_settings_js($method_objects, $really_is_writable, $updraft_dir) { global $updraftplus; ob_start(); ?> jQuery(document).ready(function() { <?php if (!$really_is_writable) echo "jQuery('.backupdirrow').show();\n"; ?> <?php if (!empty($active_service)) { if (is_array($active_service)) { foreach ($active_service as $serv) { echo "jQuery('.${serv}').show();\n"; } } else { echo "jQuery('.${active_service}').show();\n"; } } else { echo "jQuery('.none').show();\n"; } foreach ($updraftplus->backup_methods as $method => $description) { // already done: require_once(UPDRAFTPLUS_DIR.'/methods/'.$method.'.php'); $call_method = "UpdraftPlus_BackupModule_$method"; if (method_exists($call_method, 'config_print_javascript_onready')) { $method_objects[$method]->config_print_javascript_onready(); } } ?> }); <?php $ret = ob_get_contents(); ob_end_clean(); return $ret; } // $include_more can be (bool) or (string)"sometimes" public function files_selector_widgetry($prefix = '', $show_exclusion_options = true, $include_more = true) { $ret = ''; global $updraftplus; $backupable_entities = $updraftplus->get_backupable_file_entities(true, true); # The true (default value if non-existent) here has the effect of forcing a default of on. $include_more_paths = UpdraftPlus_Options::get_updraft_option('updraft_include_more_path'); foreach ($backupable_entities as $key => $info) { $included = (UpdraftPlus_Options::get_updraft_option("updraft_include_$key", apply_filters("updraftplus_defaultoption_include_".$key, true))) ? 'checked="checked"' : ""; if ('others' == $key || 'uploads' == $key) { $data_toggle_exclude_field = $show_exclusion_options ? 'data-toggle_exclude_field="'.$key.'"' : ''; $ret .= '<input class="updraft_include_entity" id="'.$prefix.'updraft_include_'.$key.'" '.$data_toggle_exclude_field.' type="checkbox" name="updraft_include_'.$key.'" value="1" '.$included.'> <label '.(('others' == $key) ? 'title="'.sprintf(__('Your wp-content directory server path: %s', 'updraftplus'), WP_CONTENT_DIR).'" ' : '').' for="'.$prefix.'updraft_include_'.$key.'">'.(('others' == $key) ? __('Any other directories found inside wp-content', 'updraftplus') : htmlspecialchars($info['description'])).'</label><br>'; if ($show_exclusion_options) { $include_exclude = UpdraftPlus_Options::get_updraft_option('updraft_include_'.$key.'_exclude', ('others' == $key) ? UPDRAFT_DEFAULT_OTHERS_EXCLUDE : UPDRAFT_DEFAULT_UPLOADS_EXCLUDE); $display = ($included) ? '' : 'class="updraft-hidden" style="display:none;"'; $ret .= "<div id=\"".$prefix."updraft_include_".$key."_exclude\" $display>"; $ret .= '<label for="'.$prefix.'updraft_include_'.$key.'_exclude">'.__('Exclude these:', 'updraftplus').'</label>'; $ret .= '<input title="'.__('If entering multiple files/directories, then separate them with commas. For entities at the top level, you can use a * at the start or end of the entry as a wildcard.', 'updraftplus').'" type="text" id="'.$prefix.'updraft_include_'.$key.'_exclude" name="updraft_include_'.$key.'_exclude" size="54" value="'.htmlspecialchars($include_exclude).'" />'; $ret .= '<br></div>'; } } else { if ($key != 'more' || true === $include_more || ('sometimes' === $include_more && !empty($include_more_paths))) { $data_toggle_exclude_field = $show_exclusion_options ? 'data-toggle_exclude_field="'.$key.'"' : ''; $ret .= "<input class=\"updraft_include_entity\" $data_toggle_exclude_field id=\"".$prefix."updraft_include_$key\" type=\"checkbox\" name=\"updraft_include_$key\" value=\"1\" $included /><label for=\"".$prefix."updraft_include_$key\"".((isset($info['htmltitle'])) ? ' title="'.htmlspecialchars($info['htmltitle']).'"' : '')."> ".htmlspecialchars($info['description']); $ret .= "</label><br>"; $ret .= apply_filters("updraftplus_config_option_include_$key", '', $prefix); } } } return $ret; } public function show_double_warning($text, $extraclass = '', $echo = true) { $ret = "<div class=\"error updraftplusmethod $extraclass\"><p>$text</p></div>"; $ret .= "<p class=\"double-warning\">$text</p>"; if ($echo) echo $ret; return $ret; } public function optionfilter_split_every($value) { $value = absint($value); if ($value < UPDRAFTPLUS_SPLIT_MIN) $value = UPDRAFTPLUS_SPLIT_MIN; return $value; } public function curl_check($service, $has_fallback = false, $extraclass = '', $echo = true) { $ret = ''; // Check requirements if (!function_exists("curl_init") || !function_exists('curl_exec')) { $ret .= $this->show_double_warning('<strong>'.__('Warning','updraftplus').':</strong> '.sprintf(__("Your web server's PHP installation does not included a <strong>required</strong> (for %s) module (%s). Please contact your web hosting provider's support and ask for them to enable it.", 'updraftplus'), $service, 'Curl').' ', $extraclass, false); } else { $curl_version = curl_version(); $curl_ssl_supported= ($curl_version['features'] & CURL_VERSION_SSL); if (!$curl_ssl_supported) { if ($has_fallback) { $ret .= '<p><strong>'.__('Warning','updraftplus').':</strong> '.sprintf(__("Your web server's PHP/Curl installation does not support https access. Communications with %s will be unencrypted. ask your web host to install Curl/SSL in order to gain the ability for encryption (via an add-on).",'updraftplus'),$service).'</p>'; } else { $ret .= $this->show_double_warning('<p><strong>'.__('Warning','updraftplus').':</strong> '.sprintf(__("Your web server's PHP/Curl installation does not support https access. We cannot access %s without this support. Please contact your web hosting provider's support. %s <strong>requires</strong> Curl+https. Please do not file any support requests; there is no alternative.",'updraftplus'),$service).'</p>', $extraclass, false); } } else { $ret .= '<p><em>'.sprintf(__("Good news: Your site's communications with %s can be encrypted. If you see any errors to do with encryption, then look in the 'Expert Settings' for more help.", 'updraftplus'),$service).'</em></p>'; } } if ($echo) { echo $ret; } else { return $ret; } } # If $basedirs is passed as an array, then $directorieses must be too private function recursive_directory_size($directorieses, $exclude = array(), $basedirs = '', $format='text') { $size = 0; if (is_string($directorieses)) { $basedirs = $directorieses; $directorieses = array($directorieses); } if (is_string($basedirs)) $basedirs = array($basedirs); foreach ($directorieses as $ind => $directories) { if (!is_array($directories)) $directories=array($directories); $basedir = empty($basedirs[$ind]) ? $basedirs[0] : $basedirs[$ind]; foreach ($directories as $dir) { if (is_file($dir)) { $size += @filesize($dir); } else { $suffix = ('' != $basedir) ? ((0 === strpos($dir, $basedir.'/')) ? substr($dir, 1+strlen($basedir)) : '') : ''; $size += $this->recursive_directory_size_raw($basedir, $exclude, $suffix); } } } if ('numeric' == $format) return $size; global $updraftplus; return $updraftplus->convert_numeric_size_to_text($size); } private function recursive_directory_size_raw($prefix_directory, &$exclude = array(), $suffix_directory = '') { $directory = $prefix_directory.('' == $suffix_directory ? '' : '/'.$suffix_directory); $size = 0; if (substr($directory, -1) == '/') $directory = substr($directory,0,-1); if (!file_exists($directory) || !is_dir($directory) || !is_readable($directory)) return -1; if (file_exists($directory.'/.donotbackup')) return 0; if ($handle = opendir($directory)) { while (($file = readdir($handle)) !== false) { if ($file != '.' && $file != '..') { $spath = ('' == $suffix_directory) ? $file : $suffix_directory.'/'.$file; if (false !== ($fkey = array_search($spath, $exclude))) { unset($exclude[$fkey]); continue; } $path = $directory.'/'.$file; if (is_file($path)) { $size += filesize($path); } elseif (is_dir($path)) { $handlesize = $this->recursive_directory_size_raw($prefix_directory, $exclude, $suffix_directory.('' == $suffix_directory ? '' : '/').$file); if ($handlesize >= 0) { $size += $handlesize; }# else { return -1; } } } } closedir($handle); } return $size; } private function raw_backup_info($backup_history, $key, $nonce) { global $updraftplus; $backup = $backup_history[$key]; $pretty_date = get_date_from_gmt(gmdate('Y-m-d H:i:s', (int)$key), 'M d, Y G:i'); $rawbackup = "<h2 title=\"$key\">$pretty_date</h2>"; if (!empty($backup['label'])) $rawbackup .= '<span class="raw-backup-info">'.$backup['label'].'</span>'; $rawbackup .= '<hr><p>'; $backupable_entities = $updraftplus->get_backupable_file_entities(true, true); if (!empty($nonce)) { $jd = $updraftplus->jobdata_getarray($nonce); } else { $jd = array(); } foreach ($backupable_entities as $type => $info) { if (!isset($backup[$type])) continue; $rawbackup .= $updraftplus->printfile($info['description'], $backup, $type, array('sha1'), $jd, true); // $rawbackup .= '<h3>'.$info['description'].'</h3>'; // $files = is_string($backup[$type]) ? array($backup[$type]) : $backup[$type]; // foreach ($files as $index => $file) { // $rawbackup .= $file.'<br>'; // } } $total_size = 0; foreach ($backup as $ekey => $files) { if ('db' == strtolower(substr($ekey, 0, 2)) && '-size' != substr($ekey, -5, 5)) { $rawbackup .= $updraftplus->printfile(__('Database', 'updraftplus'), $backup, $ekey, array('sha1'), $jd, true); } if (!isset($backupable_entities[$ekey]) && ('db' != substr($ekey, 0, 2) || '-size' == substr($ekey, -5, 5))) continue; if (is_string($files)) $files = array($files); foreach ($files as $findex => $file) { $size_key = (0 == $findex) ? $ekey.'-size' : $ekey.$findex.'-size'; $total_size = (false === $total_size || !isset($backup[$size_key]) || !is_numeric($backup[$size_key])) ? false : $total_size + $backup[$size_key]; } } $services = empty($backup['service']) ? array('none') : $backup['service']; if (!is_array($services)) $services = array('none'); $rawbackup .= '<strong>'.__('Uploaded to:', 'updraftplus').'</strong> '; $show_services = ''; foreach ($services as $serv) { if ('none' == $serv || '' == $serv) { $add_none = true; } elseif (isset($updraftplus->backup_methods[$serv])) { $show_services .= ($show_services) ? ', '.$updraftplus->backup_methods[$serv] : $updraftplus->backup_methods[$serv]; } else { $show_services .= ($show_services) ? ', '.$serv : $serv; } } if ('' == $show_services && $add_none) $show_services .= __('None', 'updraftplus'); $rawbackup .= $show_services; if ($total_size !== false) { $rawbackup .= '</p><strong>'.__('Total backup size:', 'updraftplus').'</strong> '.$updraftplus->convert_numeric_size_to_text($total_size).'<p>'; } $rawbackup .= '</p><hr><p><pre>'.print_r($backup, true).'</p></pre>'; if (!empty($jd) && is_array($jd)) { $rawbackup .= '<p><pre>'.print_r($jd, true).'</pre></p>'; } return esc_attr($rawbackup); } private function existing_backup_table($backup_history = false) { global $updraftplus; if (false === $backup_history) $backup_history = UpdraftPlus_Options::get_updraft_option('updraft_backup_history'); if (!is_array($backup_history)) $backup_history=array(); if (empty($backup_history)) return "<p><em>".__('You have not yet made any backups.', 'updraftplus')."</em></p>"; $updraft_dir = $updraftplus->backups_dir_location(); $backupable_entities = $updraftplus->get_backupable_file_entities(true, true); $accept = apply_filters('updraftplus_accept_archivename', array()); if (!is_array($accept)) $accept = array(); $ret = '<table class="existing-backups-table">'; //".__('Actions', 'updraftplus')." $ret .= "<thead> <tr style=\"margin-bottom: 4px;\"> <th class=\"backup-date\">".__('Backup date', 'updraftplus')."</th> <th class=\"backup-data\">".__('Backup data (click to download)', 'updraftplus')."</th> <th class=\"updraft_backup_actions\">".__('Actions', 'updraftplus')."</th> </tr> <tr style=\"height:2px; padding:1px; margin:0px;\"> <td colspan=\"4\" style=\"margin:0; padding:0\"><div style=\"height: 2px; background-color:#888888;\">&nbsp;</div></td> </tr> </thead> <tbody>"; // $ret .= "<thead> // </thead> // <tbody>"; krsort($backup_history); foreach ($backup_history as $key => $backup) { $remote_sent = (!empty($backup['service']) && ((is_array($backup['service']) && in_array('remotesend', $backup['service'])) || 'remotesend' === $backup['service'])) ? true : false; # https://core.trac.wordpress.org/ticket/25331 explains why the following line is wrong # $pretty_date = date_i18n('Y-m-d G:i',$key); // Convert to blog time zone // $pretty_date = get_date_from_gmt(gmdate('Y-m-d H:i:s', (int)$key), 'Y-m-d G:i'); $pretty_date = get_date_from_gmt(gmdate('Y-m-d H:i:s', (int)$key), 'M d, Y G:i'); $esc_pretty_date = esc_attr($pretty_date); $entities = ''; $non = $backup['nonce']; $rawbackup = $this->raw_backup_info($backup_history, $key, $non); $jobdata = $updraftplus->jobdata_getarray($non); $delete_button = $this->delete_button($key, $non, $backup); $date_label = $this->date_label($pretty_date, $key, $backup, $jobdata, $non); $log_button = $this->log_button($backup); // Remote backups with no log result in useless empty rows // However, not showing anything messes up the "Existing Backups (14)" display, until we tweak that code to count differently // if ($remote_sent && !$log_button) continue; $ret .= <<<ENDHERE <tr class="updraft_existing_backups_row updraft_existing_backups_row_$key" data-key="$key" data-nonce="$non"> <td class="updraft_existingbackup_date " data-rawbackup="$rawbackup"> $date_label </td> ENDHERE; $ret .= "<td>"; if ($remote_sent) { $ret .= __('Backup sent to remote site - not available for download.', 'updraftplus'); if (!empty($backup['remotesend_url'])) $ret .= '<br>'.__('Site', 'updraftplus').': '.htmlspecialchars($backup['remotesend_url']); } else { if (empty($backup['meta_foreign']) || !empty($accept[$backup['meta_foreign']]['separatedb'])) { if (isset($backup['db'])) { $entities .= '/db=0/'; // Set a flag according to whether or not $backup['db'] ends in .crypt, then pick this up in the display of the decrypt field. $db = is_array($backup['db']) ? $backup['db'][0] : $backup['db']; if ($updraftplus->is_db_encrypted($db)) $entities .= '/dbcrypted=1/'; $ret .= $this->download_db_button('db', $key, $esc_pretty_date, $backup, $accept); } else { // $ret .= sprintf(_x('(No %s)','Message shown when no such object is available','updraftplus'), __('database', 'updraftplus')); } # External databases foreach ($backup as $bkey => $binfo) { if ('db' == $bkey || 'db' != substr($bkey, 0, 2) || '-size' == substr($bkey, -5, 5)) continue; $ret .= $this->download_db_button($bkey, $key, $esc_pretty_date, $backup); } } else { # Foreign without separate db $entities = '/db=0/meta_foreign=1/'; } if (!empty($backup['meta_foreign']) && !empty($accept[$backup['meta_foreign']]) && !empty($accept[$backup['meta_foreign']]['separatedb'])) { $entities .= '/meta_foreign=2/'; } $download_buttons = $this->download_buttons($backup, $key, $accept, $entities, $esc_pretty_date); $ret .= $download_buttons; // $ret .="</td>"; // No logs expected for foreign backups if (empty($backup['meta_foreign'])) { // $ret .= '<td>'.$this->log_button($backup)."</td>"; } } $ret .= "</td>"; $ret .= '<td class="before-restore-button">'; $ret .= $this->restore_button($backup, $key, $pretty_date, $entities); $ret .= $delete_button; if (empty($backup['meta_foreign'])) $ret .= $log_button; $ret .= '</td>'; $ret .= '</tr>'; $ret .= "<tr style=\"height:2px; padding:1px; margin:0px;\"><td colspan=\"4\" style=\"margin:0; padding:0\"><div style=\"height: 2px; background-color:#aaaaaa;\">&nbsp;</div></td></tr>"; } $ret .= '</tbody></table>'; return $ret; } private function download_db_button($bkey, $key, $esc_pretty_date, $backup, $accept = array()) { if (!empty($backup['meta_foreign']) && isset($accept[$backup['meta_foreign']])) { $desc_source = $accept[$backup['meta_foreign']]['desc']; } else { $desc_source = __('unknown source', 'updraftplus'); } $ret = ''; if ('db' == $bkey) { $dbt = empty($backup['meta_foreign']) ? esc_attr(__('Database','updraftplus')) : esc_attr(sprintf(__('Database (created by %s)', 'updraftplus'), $desc_source)); } else { $dbt = __('External database','updraftplus').' ('.substr($bkey, 2).')'; } $ret .= $this->download_button($bkey, $key, 0, null, '', $dbt, $esc_pretty_date, '0'); return $ret; } // Go through each of the file entities private function download_buttons($backup, $key, $accept, &$entities, $esc_pretty_date) { global $updraftplus; $ret = ''; $backupable_entities = $updraftplus->get_backupable_file_entities(true, true); // $colspan = 1; // if (!empty($backup['meta_foreign'])) { // $colspan = 2; // if (empty($accept[$backup['meta_foreign']]['separatedb'])) $colspan++; // } // $ret .= (1 == $colspan) ? '<td>' : '<td colspan="'.$colspan.'">'; $first_entity = true; foreach ($backupable_entities as $type => $info) { if (!empty($backup['meta_foreign']) && 'wpcore' != $type) continue; // $colspan = 1; // if (!empty($backup['meta_foreign'])) { // $colspan = (1+count($backupable_entities)); // if (empty($accept[$backup['meta_foreign']]['separatedb'])) $colspan++; // } // $ret .= (1 == $colspan) ? '<td>' : '<td colspan="'.$colspan.'">'; $ide = ''; if ('wpcore' == $type) $wpcore_restore_descrip = $info['description']; if (empty($backup['meta_foreign'])) { $sdescrip = preg_replace('/ \(.*\)$/', '', $info['description']); if (strlen($sdescrip) > 20 && isset($info['shortdescription'])) $sdescrip = $info['shortdescription']; } else { $info['description'] = 'WordPress'; if (isset($accept[$backup['meta_foreign']])) { $desc_source = $accept[$backup['meta_foreign']]['desc']; $ide .= sprintf(__('Backup created by: %s.', 'updraftplus'), $accept[$backup['meta_foreign']]['desc']).' '; } else { $desc_source = __('unknown source', 'updraftplus'); $ide .= __('Backup created by unknown source (%s) - cannot be restored.', 'updraftplus').' '; } $sdescrip = (empty($accept[$backup['meta_foreign']]['separatedb'])) ? sprintf(__('Files and database WordPress backup (created by %s)', 'updraftplus'), $desc_source) : sprintf(__('Files backup (created by %s)', 'updraftplus'), $desc_source); if ('wpcore' == $type) $wpcore_restore_descrip = $sdescrip; } if (isset($backup[$type])) { if (!is_array($backup[$type])) $backup[$type]=array($backup[$type]); $howmanyinset = count($backup[$type]); $expected_index = 0; $index_missing = false; $set_contents = ''; $entities .= "/$type="; $whatfiles = $backup[$type]; ksort($whatfiles); foreach ($whatfiles as $findex => $bfile) { $set_contents .= ($set_contents == '') ? $findex : ",$findex"; if ($findex != $expected_index) $index_missing = true; $expected_index++; } $entities .= $set_contents.'/'; if (!empty($backup['meta_foreign'])) { $entities .= '/plugins=0//themes=0//uploads=0//others=0/'; } $printing_first = true; foreach ($whatfiles as $findex => $bfile) { $pdescrip = ($findex > 0) ? $sdescrip.' ('.($findex+1).')' : $sdescrip; if ($printing_first) { $ide .= __('Press here to download', 'updraftplus').' '.strtolower($info['description']); } else { $ret .= '<div class="updraft-hidden" style="display:none;">'; } if (count($backup[$type]) >0) { if ($printing_first) $ide .= ' '.sprintf(__('(%d archive(s) in set).', 'updraftplus'), $howmanyinset); } if ($index_missing) { if ($printing_first) $ide .= ' '.__('You appear to be missing one or more archives from this multi-archive set.', 'updraftplus'); } if (!$first_entity) { // $ret .= ', '; } else { $first_entity = false; } $ret .= $this->download_button($type, $key, $findex, $info, $ide, $pdescrip, $esc_pretty_date, $set_contents); if (!$printing_first) { $ret .= '</div>'; } else { $printing_first = false; } } } else { // $ret .= sprintf(_x('(No %s)','Message shown when no such object is available','updraftplus'), preg_replace('/\s\(.{12,}\)/', '', strtolower($sdescrip))); } // $ret .= '</td>'; } // $ret .= '</td>'; return $ret; } public function date_label($pretty_date, $key, $backup, $jobdata, $nonce, $simple_format = false) { // $ret = apply_filters('updraftplus_showbackup_date', '<strong>'.$pretty_date.'</strong>', $backup, $jobdata, (int)$key); $ret = apply_filters('updraftplus_showbackup_date', $pretty_date, $backup, $jobdata, (int)$key, $simple_format); if (is_array($jobdata) && !empty($jobdata['resume_interval']) && (empty($jobdata['jobstatus']) || 'finished' != $jobdata['jobstatus'])) { if ($simple_format) { $ret .= ' '.__('(Not finished)', 'updraftplus'); } else { $ret .= apply_filters('updraftplus_msg_unfinishedbackup', "<br><span title=\"".esc_attr(__('If you are seeing more backups than you expect, then it is probably because the deletion of old backup sets does not happen until a fresh backup completes.', 'updraftplus'))."\">".__('(Not finished)', 'updraftplus').'</span>', $jobdata, $nonce); } } return $ret; } private function download_button($type, $backup_timestamp, $findex, $info, $title, $pdescrip, $esc_pretty_date, $set_contents) { $ret = ''; $wp_nonce = wp_create_nonce('updraftplus_download'); // updraft_downloader(base, backup_timestamp, what, whicharea, set_contents, prettydate, async) $ret .= '<button data-wp_nonce="'.esc_attr($wp_nonce).'" data-backup_timestamp="'.esc_attr($backup_timestamp).'" data-what="'.esc_attr($type).'" data-set_contents="'.esc_attr($set_contents).'" data-prettydate="'.esc_attr($esc_pretty_date).'" type="button" class="updraft_download_button '."uddownloadform_${type}_${backup_timestamp}_${findex}".'" title="'.$title.'">'.$pdescrip.'</button>'; // onclick="'."return updraft_downloader('uddlstatus_', '$backup_timestamp', '$type', '.ud_downloadstatus', '$set_contents', '$esc_pretty_date', true)".'" return $ret; } private function restore_button($backup, $key, $pretty_date, $entities = '') { $ret = '<div class="restore-button">'; if ($entities) { $show_data = $pretty_date; if (isset($backup['native']) && false == $backup['native']) { $show_data .= ' '.__('(backup set imported from remote location)', 'updraftplus'); } $ret .= '<button data-showdata="'.esc_attr($show_data).'" data-backup_timestamp="'.$key.'" data-entities="'.esc_attr($entities).'" title="'.__('After pressing this button, you will be given the option to choose which components you wish to restore','updraftplus').'" type="button" style="float:left; clear:none;" class="button-primary choose-components-button">'.__('Restore', 'updraftplus').'</button>'; } $ret .= "</div>\n"; return $ret; } private function delete_button($key, $nonce, $backup) { $sval = ((isset($backup['service']) && $backup['service'] != 'email' && $backup['service'] != 'none')) ? '1' : '0'; return '<div class="updraftplus-remove" style="float: left; clear: none;" data-hasremote="'.$sval.'"> <a data-hasremote="'.$sval.'" data-nonce="'.$nonce.'" data-key="'.$key.'" class="no-decoration updraft-delete-link" href="#" title="'.esc_attr(__('Delete this backup set', 'updraftplus')).'">'.__('Delete', 'updraftplus').'</a> </div>'; } private function log_button($backup) { global $updraftplus; $updraft_dir = $updraftplus->backups_dir_location(); $ret = ''; if (isset($backup['nonce']) && preg_match("/^[0-9a-f]{12}$/",$backup['nonce']) && is_readable($updraft_dir.'/log.'.$backup['nonce'].'.txt')) { $nval = $backup['nonce']; // $lt = esc_attr(__('View Log','updraftplus')); $lt = __('View Log', 'updraftplus'); $url = esc_attr(UpdraftPlus_Options::admin_page()."?page=updraftplus&action=downloadlog&amp;updraftplus_backup_nonce=$nval"); $ret .= <<<ENDHERE <div style="clear:none;" class="updraft-viewlogdiv"> <a class="no-decoration updraft-log-link" href="$url" data-jobid="$nval"> $lt </a> <!-- <form action="$url" method="get"> <input type="hidden" name="action" value="downloadlog" /> <input type="hidden" name="page" value="updraftplus" /> <input type="hidden" name="updraftplus_backup_nonce" value="$nval" /> <input type="submit" value="$lt" class="updraft-log-link" onclick="event.preventDefault(); updraft_popuplog('$nval');" /> </form> --> </div> ENDHERE; return $ret; } else { // return str_replace(' ', '&nbsp;', '('.__('No backup log)', 'updraftplus').')'); } } // Return values: false = 'not yet' (not necessarily terminal); WP_Error = terminal failure; true = success private function restore_backup($timestamp, $continuation_data = null) { @set_time_limit(UPDRAFTPLUS_SET_TIME_LIMIT); global $wp_filesystem, $updraftplus; $backup_history = UpdraftPlus_Options::get_updraft_option('updraft_backup_history'); if (!isset($backup_history[$timestamp]) || !is_array($backup_history[$timestamp])) { echo '<p>'.__('This backup does not exist in the backup history - restoration aborted. Timestamp:','updraftplus')." $timestamp</p><br/>"; return new WP_Error('does_not_exist', __('Backup does not exist in the backup history', 'updraftplus')); } // request_filesystem_credentials passes on fields just via hidden name/value pairs. // Build array of parameters to be passed via this $extra_fields = array(); if (isset($_POST['updraft_restore']) && is_array($_POST['updraft_restore'])) { foreach ($_POST['updraft_restore'] as $entity) { $_POST['updraft_restore_'.$entity] = 1; $extra_fields[] = 'updraft_restore_'.$entity; } } if (is_array($continuation_data)) { foreach ($continuation_data['second_loop_entities'] as $type => $files) { $_POST['updraft_restore_'.$type] = 1; if (!in_array('updraft_restore_'.$type, $extra_fields)) $extra_fields[] = 'updraft_restore_'.$type; } if (!empty($continuation_data['restore_options'])) $restore_options = $continuation_data['restore_options']; } // Now make sure that updraft_restorer_ option fields get passed along to request_filesystem_credentials foreach ($_POST as $key => $value) { if (0 === strpos($key, 'updraft_restorer_')) $extra_fields[] = $key; } $credentials = request_filesystem_credentials(UpdraftPlus_Options::admin_page()."?page=updraftplus&action=updraft_restore&backup_timestamp=$timestamp", '', false, false, $extra_fields); WP_Filesystem($credentials); if ( $wp_filesystem->errors->get_error_code() ) { echo '<p><em><a href="https://updraftplus.com/faqs/asked-ftp-details-upon-restorationmigration-updates/">'.__('Why am I seeing this?', 'updraftplus').'</a></em></p>'; foreach ( $wp_filesystem->errors->get_error_messages() as $message ) show_message($message); exit; } // If we make it this far then WP_Filesystem has been instantiated and is functional # Set up logging $updraftplus->backup_time_nonce(); $updraftplus->jobdata_set('job_type', 'restore'); $updraftplus->jobdata_set('job_time_ms', $updraftplus->job_time_ms); $updraftplus->logfile_open($updraftplus->nonce); # Provide download link for the log file # TODO: Automatic purging of old log files # TODO: Provide option to auto-email the log file echo '<h1>'.__('UpdraftPlus Restoration: Progress', 'updraftplus').'</h1><div id="updraft-restore-progress">'; $this->show_admin_warning('<a target="_blank" href="?action=downloadlog&page=updraftplus&updraftplus_backup_nonce='.htmlspecialchars($updraftplus->nonce).'">'.__('Follow this link to download the log file for this restoration (needed for any support requests).', 'updraftplus').'</a>'); $updraft_dir = trailingslashit($updraftplus->backups_dir_location()); $foreign_known = apply_filters('updraftplus_accept_archivename', array()); $service = (isset($backup_history[$timestamp]['service'])) ? $backup_history[$timestamp]['service'] : false; if (!is_array($service)) $service = array($service); // Now, need to turn any updraft_restore_<entity> fields (that came from a potential WP_Filesystem form) back into parts of the _POST array (which we want to use) if (empty($_POST['updraft_restore']) || (!is_array($_POST['updraft_restore']))) $_POST['updraft_restore'] = array(); $backup_set = $backup_history[$timestamp]; $entities_to_restore = array(); foreach ($_POST['updraft_restore'] as $entity) { if (empty($backup_set['meta_foreign'])) { $entities_to_restore[$entity] = $entity; } else { if ('db' == $entity && !empty($foreign_known[$backup_set['meta_foreign']]) && !empty($foreign_known[$backup_set['meta_foreign']]['separatedb'])) { $entities_to_restore[$entity] = 'db'; } else { $entities_to_restore[$entity] = 'wpcore'; } } } foreach ($_POST as $key => $value) { if (0 === strpos($key, 'updraft_restore_')) { $nkey = substr($key, 16); if (!isset($entities_to_restore[$nkey])) { $_POST['updraft_restore'][] = $nkey; if (empty($backup_set['meta_foreign'])) { $entities_to_restore[$nkey] = $nkey; } else { if ('db' == $entity && !empty($foreign_known[$backup_set['meta_foreign']]['separatedb'])) { $entities_to_restore[$nkey] = 'db'; } else { $entities_to_restore[$nkey] = 'wpcore'; } } } } } if (0 == count($_POST['updraft_restore'])) { echo '<p>'.__('ABORT: Could not find the information on which entities to restore.', 'updraftplus').'</p>'; echo '<p>'.__('If making a request for support, please include this information:','updraftplus').' '.count($_POST).' : '.htmlspecialchars(serialize($_POST)).'</p>'; return new WP_Error('missing_info', 'Backup information not found'); } $this->entities_to_restore = $entities_to_restore; set_error_handler(array($updraftplus, 'php_error'), E_ALL & ~E_STRICT); /* $_POST['updraft_restore'] is typically something like: array( 0=>'db', 1=>'plugins', 2=>'themes'), etc. i.e. array ( 'db', 'plugins', themes') */ if (empty($restore_options)) { // Gather the restore optons into one place - code after here should read the options, and not the HTTP layer $restore_options = array(); if (!empty($_POST['updraft_restorer_restore_options'])) { parse_str(stripslashes($_POST['updraft_restorer_restore_options']), $restore_options); } $restore_options['updraft_restorer_replacesiteurl'] = empty($_POST['updraft_restorer_replacesiteurl']) ? false : true; $restore_options['updraft_encryptionphrase'] = empty($_POST['updraft_encryptionphrase']) ? '' : (string)stripslashes($_POST['updraft_encryptionphrase']); $restore_options['updraft_restorer_wpcore_includewpconfig'] = empty($_POST['updraft_restorer_wpcore_includewpconfig']) ? false : true; $updraftplus->jobdata_set('restore_options', $restore_options); } // Restore in the most helpful order uksort($backup_set, array($this, 'sort_restoration_entities')); // Now log $copy_restore_options = $restore_options; if (!empty($copy_restore_options['updraft_encryptionphrase'])) $copy_restore_options['updraft_encryptionphrase'] = '***'; $updraftplus->log("Restore job started. Entities to restore: ".implode(', ', array_flip($entities_to_restore)).'. Restore options: '.json_encode($copy_restore_options)); $backup_set['timestamp'] = $timestamp; $backupable_entities = $updraftplus->get_backupable_file_entities(true, true); // Allow add-ons to adjust the restore directory (but only in the case of restore - otherwise, they could just use the filter built into UpdraftPlus::get_backupable_file_entities) $backupable_entities = apply_filters('updraft_backupable_file_entities_on_restore', $backupable_entities, $restore_options, $backup_set); // We use a single object for each entity, because we want to store information about the backup set require_once(UPDRAFTPLUS_DIR.'/restorer.php'); global $updraftplus_restorer; $updraftplus_restorer = new Updraft_Restorer(new Updraft_Restorer_Skin, $backup_set, false, $restore_options); $second_loop = array(); echo "<h2>".__('Final checks', 'updraftplus').'</h2>'; if (empty($backup_set['meta_foreign'])) { $entities_to_download = $entities_to_restore; } else { if (!empty($foreign_known[$backup_set['meta_foreign']]['separatedb'])) { $entities_to_download = array(); if (in_array('db', $entities_to_restore)) { $entities_to_download['db'] = 1; } if (count($entities_to_restore) > 1 || !in_array('db', $entities_to_restore)) { $entities_to_download['wpcore'] = 1; } } else { $entities_to_download = array('wpcore' => 1); } } // First loop: make sure that files are present + readable; and populate array for second loop foreach ($backup_set as $type => $files) { // All restorable entities must be given explicitly, as we can store other arbitrary data in the history array if (!isset($backupable_entities[$type]) && 'db' != $type) continue; if (isset($backupable_entities[$type]['restorable']) && $backupable_entities[$type]['restorable'] == false) continue; if (!isset($entities_to_download[$type])) continue; if ('wpcore' == $type && is_multisite() && 0 === $updraftplus_restorer->ud_backup_is_multisite) { echo "<p>$type: <strong>"; echo __('Skipping restoration of WordPress core when importing a single site into a multisite installation. If you had anything necessary in your WordPress directory then you will need to re-add it manually from the zip file.', 'updraftplus'); #TODO #$updraftplus->log_e('Skipping restoration of WordPress core when importing a single site into a multisite installation. If you had anything necessary in your WordPress directory then you will need to re-add it manually from the zip file.'); echo "</strong></p>"; continue; } if (is_string($files)) $files=array($files); foreach ($files as $ind => $file) { $fullpath = $updraft_dir.$file; echo sprintf(__("Looking for %s archive: file name: %s", 'updraftplus'), $type, htmlspecialchars($file))."<br>"; if (is_array($continuation_data) && isset($continuation_data['second_loop_entities'][$type]) && !in_array($file, $continuation_data['second_loop_entities'][$type])) { echo __('Skipping: this archive was already restored.', 'updraftplus')."<br>"; // Set the marker so that the existing directory isn't moved out of the way $updraftplus_restorer->been_restored[$type] = true; continue; } add_action('http_request_args', array($updraftplus, 'modify_http_options')); foreach ($service as $serv) { if (!is_readable($fullpath)) { $sd = (empty($updraftplus->backup_methods[$serv])) ? $serv : $updraftplus->backup_methods[$serv]; echo __("File is not locally present - needs retrieving from remote storage",'updraftplus')." ($sd)"; $this->download_file($file, $serv); echo ": "; if (!is_readable($fullpath)) { echo __("Error", 'updraftplus'); } else { echo __("OK", 'updraftplus'); } echo '<br>'; } } remove_action('http_request_args', array($updraftplus, 'modify_http_options')); $index = ($ind == 0) ? '' : $ind; // If a file size is stored in the backup data, then verify correctness of the local file if (isset($backup_history[$timestamp][$type.$index.'-size'])) { $fs = $backup_history[$timestamp][$type.$index.'-size']; echo __("Archive is expected to be size:",'updraftplus')." ".round($fs/1024, 1)." KB: "; $as = @filesize($fullpath); if ($as == $fs) { echo __('OK','updraftplus').'<br>'; } else { echo "<strong>".__('Error:','updraftplus')."</strong> ".__('file is size:', 'updraftplus')." ".round($as/1024)." ($fs, $as)<br>"; } } else { echo __("The backup records do not contain information about the proper size of this file.",'updraftplus')."<br>"; } if (!is_readable($fullpath)) { echo __('Could not find one of the files for restoration', 'updraftplus')." ($file)<br>"; $updraftplus->log("$file: ".__('Could not find one of the files for restoration', 'updraftplus'), 'error'); echo '</div>'; restore_error_handler(); return false; } } if (empty($updraftplus_restorer->ud_foreign)) { $types = array($type); } else { if ('db' != $type || empty($foreign_known[$updraftplus_restorer->ud_foreign]['separatedb'])) { $types = array('wpcore'); } else { $types = array('db'); } } foreach ($types as $check_type) { $info = (isset($backupable_entities[$check_type])) ? $backupable_entities[$check_type] : array(); $val = $updraftplus_restorer->pre_restore_backup($files, $check_type, $info, $continuation_data); if (is_wp_error($val)) { $updraftplus->log_wp_error($val); foreach ($val->get_error_messages() as $msg) { echo '<strong>'.__('Error:', 'updraftplus').'</strong> '.htmlspecialchars($msg).'<br>'; } foreach ($val->get_error_codes() as $code) { if ('already_exists' == $code) $this->print_delete_old_dirs_form(false); } echo '</div>'; //close the updraft_restore_progress div even if we error restore_error_handler(); return $val; } elseif (false === $val) { echo '</div>'; //close the updraft_restore_progress div even if we error restore_error_handler(); return false; } } foreach ($entities_to_restore as $entity => $via) { if ($via == $type) { if ('wpcore' == $via && 'db' == $entity && count($files) > 1) { $second_loop[$entity] = apply_filters('updraftplus_select_wpcore_file_with_db', $files, $updraftplus_restorer->ud_foreign); } else { $second_loop[$entity] = $files; } } } } $updraftplus_restorer->delete = (UpdraftPlus_Options::get_updraft_option('updraft_delete_local')) ? true : false; if ('none' === $service || 'email' === $service || empty($service) || (is_array($service) && 1 == count($service) && (in_array('none', $service) || in_array('', $service) || in_array('email', $service))) || !empty($updraftplus_restorer->ud_foreign)) { if ($updraftplus_restorer->delete) $updraftplus->log_e('Will not delete any archives after unpacking them, because there was no cloud storage for this backup'); $updraftplus_restorer->delete = false; } if (!empty($updraftplus_restorer->ud_foreign)) $updraftplus->log("Foreign backup; created by: ".$updraftplus_restorer->ud_foreign); // Second loop: now actually do the restoration uksort($second_loop, array($this, 'sort_restoration_entities')); // If continuing, then prune those already done if (is_array($continuation_data)) { foreach ($second_loop as $type => $files) { if (isset($continuation_data['second_loop_entities'][$type])) $second_loop[$type] = $continuation_data['second_loop_entities'][$type]; } } $updraftplus->jobdata_set('second_loop_entities', $second_loop); $updraftplus->jobdata_set('backup_timestamp', $timestamp); // use a site option, as otherwise on multisite when all the array of options is updated via UpdraftPlus_Options::update_site_option(), it will over-write any restored UD options from the backup update_site_option('updraft_restore_in_progress', $updraftplus->nonce); foreach ($second_loop as $type => $files) { # Types: uploads, themes, plugins, others, db $info = (isset($backupable_entities[$type])) ? $backupable_entities[$type] : array(); echo ('db' == $type) ? "<h2>".__('Database','updraftplus')."</h2>" : "<h2>".$info['description']."</h2>"; $updraftplus->log("Entity: ".$type); if (is_string($files)) $files = array($files); foreach ($files as $fkey => $file) { $last_one = (1 == count($second_loop) && 1 == count($files)); $val = $updraftplus_restorer->restore_backup($file, $type, $info, $last_one); if (is_wp_error($val)) { $codes = $val->get_error_codes(); if (is_array($codes) && in_array('not_found', $codes) && !empty($updraftplus_restorer->ud_foreign) && apply_filters('updraftplus_foreign_allow_missing_entity', false, $type, $updraftplus_restorer->ud_foreign)) { $updraftplus->log("Entity to move not found in this zip - but this is possible with this foreign backup type"); } else { $updraftplus->log_e($val); foreach ($val->get_error_messages() as $msg) { echo '<strong>'.__('Error message', 'updraftplus').':</strong> '.htmlspecialchars($msg).'<br>'; } $codes = $val->get_error_codes(); if (is_array($codes)) { foreach ($codes as $code) { $data = $val->get_error_data($code); if (!empty($data)) { $pdata = (is_string($data)) ? $data : serialize($data); echo '<strong>'.__('Error data:', 'updraftplus').'</strong> '.htmlspecialchars($pdata).'<br>'; if (false !== strpos($pdata, 'PCLZIP_ERR_BAD_FORMAT (-10)')) { echo '<a href="https://updraftplus.com/faqs/error-message-pclzip_err_bad_format-10-invalid-archive-structure-mean/"><strong>'.__('Please consult this FAQ for help on what to do about it.', 'updraftplus').'</strong></a><br>'; } } } } echo '</div>'; //close the updraft_restore_progress div even if we error restore_error_handler(); return $val; } } elseif (false === $val) { echo '</div>'; //close the updraft_restore_progress div even if we error restore_error_handler(); return false; } unset($files[$fkey]); $second_loop[$type] = $files; $updraftplus->jobdata_set('second_loop_entities', $second_loop); $updraftplus->jobdata_set('backup_timestamp', $timestamp); do_action('updraft_restored_archive', $file, $type, $val, $fkey, $timestamp); } unset($second_loop[$type]); update_site_option('updraft_restore_in_progress', $updraftplus->nonce); $updraftplus->jobdata_set('second_loop_entities', $second_loop); $updraftplus->jobdata_set('backup_timestamp', $timestamp); } // All done - remove delete_site_option('updraft_restore_in_progress'); foreach (array('template', 'stylesheet', 'template_root', 'stylesheet_root') as $opt) { add_filter('pre_option_'.$opt, array($this, 'option_filter_'.$opt)); } # Clear any cached pages after the restore $updraftplus_restorer->clear_cache(); if (!function_exists('validate_current_theme')) require_once(ABSPATH.WPINC.'/themes'); # Have seen a case where the current theme in the DB began with a capital, but not on disk - and this breaks migrating from Windows to a case-sensitive system $template = get_option('template'); if (!empty($template) && $template != WP_DEFAULT_THEME && $template != strtolower($template)) { $theme_root = get_theme_root($template); $theme_root2 = get_theme_root(strtolower($template)); if (!file_exists("$theme_root/$template/style.css") && file_exists("$theme_root/".strtolower($template)."/style.css")) { $updraftplus->log_e("Theme directory (%s) not found, but lower-case version exists; updating database option accordingly", $template); update_option('template', strtolower($template)); } } if (!validate_current_theme()) { echo '<strong>'; $updraftplus->log_e("The current theme was not found; to prevent this stopping the site from loading, your theme has been reverted to the default theme"); echo '</strong>'; } echo '</div>'; //close the updraft_restore_progress div restore_error_handler(); return true; } public function option_filter_template($val) { global $updraftplus; return $updraftplus->option_filter_get('template'); } public function option_filter_stylesheet($val) { global $updraftplus; return $updraftplus->option_filter_get('stylesheet'); } public function option_filter_template_root($val) { global $updraftplus; return $updraftplus->option_filter_get('template_root'); } public function option_filter_stylesheet_root($val) { global $updraftplus; return $updraftplus->option_filter_get('stylesheet_root'); } public function sort_restoration_entities($a, $b) { if ($a == $b) return 0; // Put the database first // Put wpcore after plugins/uploads/themes (needed for restores of foreign all-in-one formats) if ('db' == $a || 'wpcore' == $b) return -1; if ('db' == $b || 'wpcore' == $a) return 1; // After wpcore, next last is others if ('others' == $b) return -1; if ('others' == $a) return 1; // And then uploads - this is only because we want to make sure uploads is after plugins, so that we know before we get to the uploads whether the version of UD which might have to unpack them can do this new-style or not. if ('uploads' == $b) return -1; if ('uploads' == $a) return 1; return strcmp($a, $b); } public function return_array($input) { if (!is_array($input)) $input = array(); return $input; } public function updraft_ajax_savesettings() { global $updraftplus; if (empty($_POST) || empty($_POST['subaction']) || 'savesettings' != $_POST['subaction'] || !isset($_POST['nonce']) || !is_user_logged_in() || !UpdraftPlus_Options::user_can_manage() || !wp_verify_nonce($_POST['nonce'], 'updraftplus-settings-nonce')) die('Security check'); if (empty($_POST['settings']) || !is_string($_POST['settings'])) die('Invalid data'); parse_str(stripslashes($_POST['settings']), $posted_settings); // We now have $posted_settings as an array echo json_encode($this->save_settings($posted_settings)); die; } private function backup_now_remote_message() { global $updraftplus; $service = $updraftplus->just_one(UpdraftPlus_Options::get_updraft_option('updraft_service')); if (is_string($service)) $service = array($service); if (!is_array($service)) $service = array(); $no_remote_configured = (empty($service) || array('none') === $service || array('') === $service) ? true : false; if ($no_remote_configured) { return '<input type="checkbox" disabled="disabled" id="backupnow_includecloud"> <em>'.sprintf(__("Backup won't be sent to any remote storage - none has been saved in the %s", 'updraftplus'), '<a href="'.UpdraftPlus_Options::admin_page_url().'?page=updraftplus&amp;tab=settings" id="updraft_backupnow_gotosettings">'.__('settings', 'updraftplus')).'</a>. '.__('Not got any remote storage?', 'updraftplus').' <a href="https://updraftplus.com/landing/vault">'.__("Check out UpdraftPlus Vault.", 'updraftplus').'</a></em>'; } else { return '<input type="checkbox" id="backupnow_includecloud" checked="checked"> <label for="backupnow_includecloud">'.__("Send this backup to remote storage", 'updraftplus').'</label>'; } } public function save_settings($settings) { global $updraftplus; // Make sure that settings filters are registered UpdraftPlus_Options::admin_init(); $return_array = array('saved' => true); $add_to_post_keys = array('updraft_interval', 'updraft_interval_database', 'updraft_starttime_files', 'updraft_starttime_db', 'updraft_startday_files', 'updraft_startday_db'); //If database and files are on same schedule, override the db day/time settings if (isset($settings['updraft_interval_database']) && isset($settings['updraft_interval_database']) && $settings['updraft_interval_database'] == $settings['updraft_interval'] && isset($settings['updraft_starttime_files'])) { $settings['updraft_starttime_db'] = $settings['updraft_starttime_files']; $settings['updraft_startday_db'] = $settings['updraft_startday_files']; } foreach ($add_to_post_keys as $key) { // For add-ons that look at $_POST to find saved settings, add the relevant keys to $_POST so that they find them there if (isset($settings[$key])) { $_POST[$key] = $settings[$key]; } } // Wipe the extra retention rules, as they are not saved correctly if the last one is deleted UpdraftPlus_Options::update_updraft_option('updraft_retain_extrarules', array()); UpdraftPlus_Options::update_updraft_option('updraft_email', array()); UpdraftPlus_Options::update_updraft_option('updraft_report_warningsonly', array()); UpdraftPlus_Options::update_updraft_option('updraft_report_wholebackup', array()); UpdraftPlus_Options::update_updraft_option('updraft_extradbs', array()); UpdraftPlus_Options::update_updraft_option('updraft_include_more_path', array()); $relevant_keys = $updraftplus->get_settings_keys(); if (method_exists('UpdraftPlus_Options', 'mass_options_update')) { $original_settings = $settings; $settings = UpdraftPlus_Options::mass_options_update($settings); $mass_updated = true; } foreach ($settings as $key => $value) { // $exclude_keys = array('option_page', 'action', '_wpnonce', '_wp_http_referer'); // if (!in_array($key, $exclude_keys)) { if (in_array($key, $relevant_keys)) { if ($key == "updraft_service" && is_array($value)){ foreach ($value as $subkey => $subvalue){ if ($subvalue == '0') unset($value[$subkey]); } } // This flag indicates that either the stored database option was changed, or that the supplied option was changed before being stored. It isn't comprehensive - it's only used to update some UI elements with invalid input. $updated = empty($mass_updated) ? (is_string($value) && $value != UpdraftPlus_Options::get_updraft_option($key)) : (is_string($value) && (!isset($original_settings[$key]) || $original_settings[$key] != $value)); $db_updated = empty($mass_updated) ? UpdraftPlus_Options::update_updraft_option($key, $value) : true; // Add information on what has changed to array to loop through to update links etc. // Restricting to strings for now, to prevent any unintended leakage (since this is just used for UI updating) if ($updated) { $value = UpdraftPlus_Options::get_updraft_option($key); if (is_string($value)) $return_array['changed'][$key] = $value; } } else { // When last active, it was catching: option_page, action, _wpnonce, _wp_http_referer, updraft_s3_endpoint, updraft_dreamobjects_endpoint. The latter two are empty; probably don't need to be in the page at all. //error_log("Non-UD key when saving from POSTed data: ".$key); } } // Checking for various possible messages $updraft_dir = $updraftplus->backups_dir_location(false); $really_is_writable = $updraftplus->really_is_writable($updraft_dir); $dir_info = $this->really_writable_message($really_is_writable, $updraft_dir); $button_title = esc_attr(__('This button is disabled because your backup directory is not writable (see the settings).', 'updraftplus')); $return_array['backup_now_message'] = $this->backup_now_remote_message(); $return_array['backup_dir'] = array('writable' => $really_is_writable, 'message' => $dir_info, 'button_title' => $button_title); //Because of the single AJAX call, we need to remove the existing UD messages from the 'all_admin_notices' action remove_all_actions('all_admin_notices'); //Moving from 2 to 1 ajax call ob_start(); $service = UpdraftPlus_Options::get_updraft_option('updraft_service'); $this->setup_all_admin_notices_global($service); $this->setup_all_admin_notices_udonly($service); do_action('all_admin_notices'); if (!$really_is_writable){ //Check if writable $this->show_admin_warning_unwritable(); } if ($return_array['saved'] == true){ // $this->show_admin_warning(__('Your settings have been saved.', 'updraftplus'), 'updated fade'); } $messages_output = ob_get_contents(); ob_clean(); // Backup schedule output $this->next_scheduled_backups_output(); $scheduled_output = ob_get_clean(); $return_array['messages'] = $messages_output; $return_array['scheduled'] = $scheduled_output; //*** Add the updated options to the return message, so we can update on screen ***\\ return $return_array; } }
Java
#!/bin/sh # SPDX-License-Identifier: LGPL-2.1-or-later set -eu cd "$MESON_SOURCE_ROOT" if [ ! -f .git/hooks/pre-commit.sample -o -f .git/hooks/pre-commit ]; then exit 2 # not needed fi cp -p .git/hooks/pre-commit.sample .git/hooks/pre-commit chmod +x .git/hooks/pre-commit echo 'Activated pre-commit hook'
Java
cmd_fs/jbd/checkpoint.o := /opt/buildroot-gcc342/bin/mipsel-linux-uclibc-gcc -Wp,-MD,fs/jbd/.checkpoint.o.d -nostdinc -isystem /root/asuswrt-bender/tools/brcm/K26/hndtools-mipsel-uclibc-4.2.4/bin/../lib/gcc/mipsel-linux-uclibc/4.2.4/include -D__KERNEL__ -Iinclude -include include/linux/autoconf.h -Wall -Wundef -Wstrict-prototypes -Wno-trigraphs -fno-strict-aliasing -fno-common -O2 -mabi=32 -G 0 -mno-abicalls -fno-pic -pipe -msoft-float -ffreestanding -march=mips32r2 -Wa,-mips32r2 -Wa,--trap -Iinclude/asm-mips/rt2880 -Iinclude/asm-mips/mach-generic -fomit-frame-pointer -gdwarf-2 -fno-stack-protector -membedded-data -muninit-const-in-rodata -funit-at-a-time -Wdeclaration-after-statement -Wno-pointer-sign -DMODULE -mlong-calls -D"KBUILD_STR(s)=\#s" -D"KBUILD_BASENAME=KBUILD_STR(checkpoint)" -D"KBUILD_MODNAME=KBUILD_STR(jbd)" -c -o fs/jbd/checkpoint.o fs/jbd/checkpoint.c deps_fs/jbd/checkpoint.o := \ fs/jbd/checkpoint.c \ include/linux/time.h \ include/linux/types.h \ $(wildcard include/config/uid16.h) \ $(wildcard include/config/lbd.h) \ $(wildcard include/config/lsf.h) \ $(wildcard include/config/resources/64bit.h) \ include/linux/posix_types.h \ include/linux/stddef.h \ include/linux/compiler.h \ $(wildcard include/config/enable/must/check.h) \ include/linux/compiler-gcc4.h \ $(wildcard include/config/forced/inlining.h) \ include/linux/compiler-gcc.h \ include/asm/posix_types.h \ include/asm/sgidefs.h \ include/asm/types.h \ $(wildcard include/config/highmem.h) \ $(wildcard include/config/64bit/phys/addr.h) \ $(wildcard include/config/64bit.h) \ include/linux/seqlock.h \ include/linux/spinlock.h \ $(wildcard include/config/smp.h) \ $(wildcard include/config/debug/spinlock.h) \ $(wildcard include/config/preempt.h) \ $(wildcard include/config/debug/lock/alloc.h) \ include/linux/preempt.h \ $(wildcard include/config/debug/preempt.h) \ include/linux/thread_info.h \ include/linux/bitops.h \ include/asm/bitops.h \ $(wildcard include/config/cpu/mipsr2.h) \ $(wildcard include/config/cpu/mips32.h) \ $(wildcard include/config/cpu/mips64.h) \ include/linux/irqflags.h \ $(wildcard include/config/trace/irqflags.h) \ $(wildcard include/config/trace/irqflags/support.h) \ $(wildcard include/config/x86.h) \ include/asm/irqflags.h \ $(wildcard include/config/mips/mt/smtc.h) \ $(wildcard include/config/irq/cpu.h) \ $(wildcard include/config/mips/mt/smtc/instant/replay.h) \ include/asm/hazards.h \ $(wildcard include/config/cpu/r10000.h) \ $(wildcard include/config/cpu/rm9000.h) \ $(wildcard include/config/cpu/sb1.h) \ include/asm/barrier.h \ $(wildcard include/config/cpu/has/sync.h) \ $(wildcard include/config/cpu/has/wb.h) \ $(wildcard include/config/weak/ordering.h) \ include/asm/bug.h \ $(wildcard include/config/bug.h) \ include/asm/break.h \ include/asm-generic/bug.h \ $(wildcard include/config/generic/bug.h) \ $(wildcard include/config/debug/bugverbose.h) \ include/asm/byteorder.h \ $(wildcard include/config/cpu/mips64/r2.h) \ include/linux/byteorder/little_endian.h \ include/linux/byteorder/swab.h \ include/linux/byteorder/generic.h \ include/asm/cpu-features.h \ $(wildcard include/config/32bit.h) \ $(wildcard include/config/cpu/mipsr2/irq/vi.h) \ $(wildcard include/config/cpu/mipsr2/irq/ei.h) \ include/asm/cpu.h \ include/asm/cpu-info.h \ $(wildcard include/config/sgi/ip27.h) \ $(wildcard include/config/mips/mt.h) \ include/asm/cache.h \ $(wildcard include/config/mips/l1/cache/shift.h) \ include/asm-mips/mach-generic/kmalloc.h \ $(wildcard include/config/dma/coherent.h) \ include/asm-mips/mach-generic/cpu-feature-overrides.h \ include/asm/war.h \ $(wildcard include/config/sgi/ip22.h) \ $(wildcard include/config/sni/rm.h) \ $(wildcard include/config/cpu/r5432.h) \ $(wildcard include/config/sb1/pass/1/workarounds.h) \ $(wildcard include/config/sb1/pass/2/workarounds.h) \ $(wildcard include/config/mips/malta.h) \ $(wildcard include/config/mips/atlas.h) \ $(wildcard include/config/mips/sead.h) \ $(wildcard include/config/cpu/tx49xx.h) \ $(wildcard include/config/momenco/jaguar/atx.h) \ $(wildcard include/config/pmc/yosemite.h) \ $(wildcard include/config/basler/excite.h) \ $(wildcard include/config/momenco/ocelot/3.h) \ include/asm-generic/bitops/non-atomic.h \ include/asm-generic/bitops/fls64.h \ include/asm-generic/bitops/ffz.h \ include/asm-generic/bitops/find.h \ include/asm-generic/bitops/sched.h \ include/asm-generic/bitops/hweight.h \ include/asm-generic/bitops/ext2-non-atomic.h \ include/asm-generic/bitops/le.h \ include/asm-generic/bitops/ext2-atomic.h \ include/asm-generic/bitops/minix.h \ include/asm/thread_info.h \ $(wildcard include/config/page/size/4kb.h) \ $(wildcard include/config/page/size/8kb.h) \ $(wildcard include/config/page/size/16kb.h) \ $(wildcard include/config/page/size/64kb.h) \ $(wildcard include/config/debug/stack/usage.h) \ include/asm/processor.h \ $(wildcard include/config/mips/mt/fpaff.h) \ $(wildcard include/config/cpu/has/prefetch.h) \ include/linux/cpumask.h \ $(wildcard include/config/hotplug/cpu.h) \ include/linux/kernel.h \ $(wildcard include/config/preempt/voluntary.h) \ $(wildcard include/config/debug/spinlock/sleep.h) \ $(wildcard include/config/printk.h) \ $(wildcard include/config/numa.h) \ /root/asuswrt-bender/tools/brcm/K26/hndtools-mipsel-uclibc-4.2.4/bin/../lib/gcc/mipsel-linux-uclibc/4.2.4/include/stdarg.h \ include/linux/linkage.h \ include/asm/linkage.h \ include/linux/log2.h \ $(wildcard include/config/arch/has/ilog2/u32.h) \ $(wildcard include/config/arch/has/ilog2/u64.h) \ include/linux/threads.h \ $(wildcard include/config/nr/cpus.h) \ $(wildcard include/config/base/small.h) \ include/linux/bitmap.h \ include/linux/string.h \ include/asm/string.h \ $(wildcard include/config/cpu/r3000.h) \ include/asm/cachectl.h \ include/asm/mipsregs.h \ $(wildcard include/config/cpu/vr41xx.h) \ include/asm/prefetch.h \ include/asm/system.h \ include/asm/addrspace.h \ $(wildcard include/config/cpu/r4300.h) \ $(wildcard include/config/cpu/r4x00.h) \ $(wildcard include/config/cpu/r5000.h) \ $(wildcard include/config/cpu/rm7000.h) \ $(wildcard include/config/cpu/nevada.h) \ $(wildcard include/config/cpu/r8000.h) \ $(wildcard include/config/cpu/sb1a.h) \ include/asm-mips/mach-generic/spaces.h \ $(wildcard include/config/dma/noncoherent.h) \ include/asm/dsp.h \ include/linux/stringify.h \ include/linux/bottom_half.h \ include/linux/spinlock_types.h \ include/linux/lockdep.h \ $(wildcard include/config/lockdep.h) \ $(wildcard include/config/generic/hardirqs.h) \ $(wildcard include/config/prove/locking.h) \ include/linux/spinlock_types_up.h \ include/linux/spinlock_up.h \ include/linux/spinlock_api_up.h \ include/asm/atomic.h \ include/asm-generic/atomic.h \ include/linux/fs.h \ $(wildcard include/config/dnotify.h) \ $(wildcard include/config/sysfs.h) \ $(wildcard include/config/quota.h) \ $(wildcard include/config/inotify.h) \ $(wildcard include/config/security.h) \ $(wildcard include/config/epoll.h) \ $(wildcard include/config/auditsyscall.h) \ $(wildcard include/config/block.h) \ $(wildcard include/config/fs/xip.h) \ $(wildcard include/config/migration.h) \ include/linux/limits.h \ include/linux/ioctl.h \ include/asm/ioctl.h \ include/linux/wait.h \ include/linux/list.h \ $(wildcard include/config/debug/list.h) \ include/linux/poison.h \ include/linux/prefetch.h \ include/asm/current.h \ include/linux/kdev_t.h \ include/linux/dcache.h \ $(wildcard include/config/profiling.h) \ include/linux/cache.h \ $(wildcard include/config/arch/has/cache/line/size.h) \ include/linux/rcupdate.h \ include/linux/percpu.h \ include/linux/slab.h \ $(wildcard include/config/slab/debug.h) \ $(wildcard include/config/slub.h) \ $(wildcard include/config/slob.h) \ $(wildcard include/config/debug/slab.h) \ include/linux/gfp.h \ $(wildcard include/config/zone/dma.h) \ $(wildcard include/config/zone/dma32.h) \ include/linux/mmzone.h \ $(wildcard include/config/force/max/zoneorder.h) \ $(wildcard include/config/memory/hotplug.h) \ $(wildcard include/config/arch/populates/node/map.h) \ $(wildcard include/config/discontigmem.h) \ $(wildcard include/config/flat/node/mem/map.h) \ $(wildcard include/config/have/memory/present.h) \ $(wildcard include/config/need/node/memmap/size.h) \ $(wildcard include/config/need/multiple/nodes.h) \ $(wildcard include/config/sparsemem.h) \ $(wildcard include/config/have/arch/early/pfn/to/nid.h) \ $(wildcard include/config/flatmem.h) \ $(wildcard include/config/sparsemem/extreme.h) \ $(wildcard include/config/nodes/span/other/nodes.h) \ $(wildcard include/config/holes/in/zone.h) \ include/linux/numa.h \ $(wildcard include/config/nodes/shift.h) \ include/linux/init.h \ $(wildcard include/config/modules.h) \ $(wildcard include/config/hotplug.h) \ $(wildcard include/config/acpi/hotplug/memory.h) \ include/linux/nodemask.h \ include/asm/page.h \ $(wildcard include/config/build/elf64.h) \ $(wildcard include/config/limited/dma.h) \ include/linux/pfn.h \ include/asm/io.h \ include/asm-generic/iomap.h \ include/asm/pgtable-bits.h \ $(wildcard include/config/cpu/mips32/r1.h) \ $(wildcard include/config/cpu/tx39xx.h) \ $(wildcard include/config/mips/uncached.h) \ include/asm-mips/mach-generic/ioremap.h \ include/asm-mips/mach-generic/mangle-port.h \ $(wildcard include/config/swap/io/space.h) \ include/asm-generic/memory_model.h \ $(wildcard include/config/out/of/line/pfn/to/page.h) \ include/asm-generic/page.h \ include/linux/memory_hotplug.h \ $(wildcard include/config/have/arch/nodedata/extension.h) \ include/linux/notifier.h \ include/linux/errno.h \ include/asm/errno.h \ include/asm-generic/errno-base.h \ include/linux/mutex.h \ $(wildcard include/config/debug/mutexes.h) \ include/linux/rwsem.h \ $(wildcard include/config/rwsem/generic/spinlock.h) \ include/linux/rwsem-spinlock.h \ include/linux/srcu.h \ include/linux/topology.h \ $(wildcard include/config/sched/smt.h) \ $(wildcard include/config/sched/mc.h) \ include/linux/smp.h \ include/asm/topology.h \ include/asm-mips/mach-generic/topology.h \ include/asm-generic/topology.h \ include/linux/slub_def.h \ include/linux/workqueue.h \ include/linux/timer.h \ $(wildcard include/config/timer/stats.h) \ include/linux/ktime.h \ $(wildcard include/config/ktime/scalar.h) \ include/linux/jiffies.h \ include/linux/calc64.h \ include/asm/div64.h \ include/asm-generic/div64.h \ include/linux/timex.h \ $(wildcard include/config/time/interpolation.h) \ $(wildcard include/config/no/hz.h) \ include/asm/param.h \ $(wildcard include/config/hz.h) \ include/asm/timex.h \ include/asm-mips/mach-generic/timex.h \ include/linux/kobject.h \ include/linux/sysfs.h \ include/linux/kref.h \ include/asm/percpu.h \ include/asm-generic/percpu.h \ include/linux/namei.h \ include/linux/stat.h \ include/asm/stat.h \ include/linux/radix-tree.h \ include/linux/prio_tree.h \ include/linux/pid.h \ include/asm/semaphore.h \ include/linux/quota.h \ include/linux/dqblk_xfs.h \ include/linux/dqblk_v1.h \ include/linux/dqblk_v2.h \ include/linux/nfs_fs_i.h \ include/linux/nfs.h \ include/linux/sunrpc/msg_prot.h \ include/linux/fcntl.h \ include/asm/fcntl.h \ include/asm-generic/fcntl.h \ include/linux/err.h \ include/linux/jbd.h \ $(wildcard include/config/jbd/debug.h) \ $(wildcard include/config/buffer/debug.h) \ include/linux/buffer_head.h \ include/linux/pagemap.h \ include/linux/mm.h \ $(wildcard include/config/sysctl.h) \ $(wildcard include/config/mmu.h) \ $(wildcard include/config/stack/growsup.h) \ $(wildcard include/config/debug/vm.h) \ $(wildcard include/config/shmem.h) \ $(wildcard include/config/split/ptlock/cpus.h) \ $(wildcard include/config/ia64.h) \ $(wildcard include/config/proc/fs.h) \ $(wildcard include/config/debug/pagealloc.h) \ include/linux/capability.h \ include/linux/rbtree.h \ include/linux/debug_locks.h \ $(wildcard include/config/debug/locking/api/selftests.h) \ include/linux/backing-dev.h \ include/linux/mm_types.h \ include/asm/pgtable.h \ include/asm/pgtable-32.h \ include/asm/fixmap.h \ include/asm-generic/pgtable-nopmd.h \ include/asm-generic/pgtable-nopud.h \ include/asm-generic/pgtable.h \ include/linux/page-flags.h \ $(wildcard include/config/s390.h) \ $(wildcard include/config/swap.h) \ include/linux/vmstat.h \ $(wildcard include/config/vm/event/counters.h) \ include/linux/highmem.h \ include/linux/uaccess.h \ include/asm/uaccess.h \ include/asm-generic/uaccess.h \ include/asm/cacheflush.h \ include/asm/kmap_types.h \ $(wildcard include/config/debug/highmem.h) \ include/linux/journal-head.h \ include/linux/bit_spinlock.h \ include/linux/sched.h \ $(wildcard include/config/detect/softlockup.h) \ $(wildcard include/config/keys.h) \ $(wildcard include/config/bsd/process/acct.h) \ $(wildcard include/config/taskstats.h) \ $(wildcard include/config/inotify/user.h) \ $(wildcard include/config/schedstats.h) \ $(wildcard include/config/task/delay/acct.h) \ $(wildcard include/config/blk/dev/io/trace.h) \ $(wildcard include/config/cc/stackprotector.h) \ $(wildcard include/config/sysvipc.h) \ $(wildcard include/config/rt/mutexes.h) \ $(wildcard include/config/task/xacct.h) \ $(wildcard include/config/cpusets.h) \ $(wildcard include/config/compat.h) \ $(wildcard include/config/fault/injection.h) \ include/linux/auxvec.h \ include/asm/auxvec.h \ include/asm/ptrace.h \ $(wildcard include/config/cpu/has/smartmips.h) \ include/asm/isadep.h \ include/asm/mmu.h \ include/asm/cputime.h \ include/asm-generic/cputime.h \ include/linux/sem.h \ include/linux/ipc.h \ $(wildcard include/config/ipc/ns.h) \ include/asm/ipcbuf.h \ include/asm/sembuf.h \ include/linux/signal.h \ include/asm/signal.h \ $(wildcard include/config/trad/signals.h) \ $(wildcard include/config/binfmt/irix.h) \ include/asm-generic/signal.h \ include/asm/sigcontext.h \ include/asm/siginfo.h \ include/asm-generic/siginfo.h \ include/linux/securebits.h \ include/linux/fs_struct.h \ include/linux/completion.h \ include/linux/seccomp.h \ $(wildcard include/config/seccomp.h) \ include/linux/futex.h \ $(wildcard include/config/futex.h) \ include/linux/rtmutex.h \ $(wildcard include/config/debug/rt/mutexes.h) \ include/linux/plist.h \ $(wildcard include/config/debug/pi/list.h) \ include/linux/param.h \ include/linux/resource.h \ include/asm/resource.h \ include/asm-generic/resource.h \ include/linux/hrtimer.h \ $(wildcard include/config/high/res/timers.h) \ include/linux/task_io_accounting.h \ $(wildcard include/config/task/io/accounting.h) \ include/linux/aio.h \ include/linux/aio_abi.h \ include/linux/uio.h \ fs/jbd/checkpoint.o: $(deps_fs/jbd/checkpoint.o) $(deps_fs/jbd/checkpoint.o):
Java
/* * Created on 5 Sep 2007 * * Copyright (c) 2004-2007 Paul John Leonard * * http://www.frinika.com * * This file is part of Frinika. * * Frinika 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. * Frinika 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 Frinika; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package com.frinika.tootX.midi; import java.util.logging.Level; import java.util.logging.Logger; import javax.sound.midi.InvalidMidiDataException; import javax.sound.midi.ShortMessage; public class MidiHashUtil { static public long hashValue(ShortMessage mess) { byte data[] = mess.getMessage(); long cmd = mess.getCommand(); if (cmd == ShortMessage.PITCH_BEND) { return ((long) data[0] << 8); } else { return (((long) data[0] << 8) + data[1]); } } static public void hashDisp(long hash) { long cntrl = hash & 0xFF; long cmd = (hash >> 8) & 0xFF; long chn = (hash >> 16) & 0xFF; System.out.println(chn + " " + cmd + " " + cntrl); } static ShortMessage reconstructShortMessage(long hash, ShortMessage mess) { if (mess == null) mess=new ShortMessage(); int status = (int) ((hash >> 8) & 0xFF); int data1 = (int) (hash & 0xFF); try { mess.setMessage(status, data1, 0); } catch (InvalidMidiDataException ex) { Logger.getLogger(MidiHashUtil.class.getName()).log(Level.SEVERE, null, ex); } return mess; } }
Java
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- * * Copyright (C) 2013 Richard Hughes <richard@hughsie.com> * * Licensed under the GNU General Public License Version 2 * * 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. */ /** * SECTION:huey-enum * @short_description: Types used by huey and libhuey * * These helper functions provide a way to marshal enumerated values to * text and back again. * * See also: #CdClient, #CdDevice */ #include "config.h" #include <glib.h> #include "huey-enum.h" /** * huey_rc_to_string: * * Since: 0.1.29 **/ const gchar * huey_rc_to_string (guchar value) { if (value == HUEY_RC_SUCCESS) return "success"; if (value == HUEY_RC_LOCKED) return "locked"; if (value == HUEY_RC_ERROR) return "error"; if (value == HUEY_RC_RETRY) return "retry"; if (value == HUEY_RC_UNKNOWN_5A) return "unknown5a"; if (value == HUEY_RC_UNKNOWN_81) return "unknown81"; return NULL; } /** * huey_cmd_code_to_string: * * Since: 0.1.29 **/ const gchar * huey_cmd_code_to_string (guchar value) { if (value == HUEY_CMD_GET_STATUS) return "get-status"; if (value == HUEY_CMD_READ_GREEN) return "read-green"; if (value == HUEY_CMD_READ_BLUE) return "read-blue"; if (value == HUEY_CMD_SET_INTEGRATION_TIME) return "set-integration-time"; if (value == HUEY_CMD_GET_INTEGRATION_TIME) return "get-integration-time"; if (value == HUEY_CMD_REGISTER_WRITE) return "reg-write"; if (value == HUEY_CMD_REGISTER_READ) return "reg-read"; if (value == HUEY_CMD_UNLOCK) return "unlock"; if (value == HUEY_CMD_UNKNOWN_0F) return "unknown0f"; if (value == HUEY_CMD_UNKNOWN_10) return "unknown10"; if (value == HUEY_CMD_UNKNOWN_11) return "unknown11"; if (value == HUEY_CMD_UNKNOWN_12) return "unknown12"; if (value == HUEY_CMD_SENSOR_MEASURE_RGB_CRT) return "measure-rgb-crt"; if (value == HUEY_CMD_UNKNOWN_15) return "unknown15(status?)"; if (value == HUEY_CMD_SENSOR_MEASURE_RGB) return "measure-rgb"; if (value == HUEY_CMD_UNKNOWN_21) return "unknown21"; if (value == HUEY_CMD_GET_AMBIENT) return "get-ambient"; if (value == HUEY_CMD_SET_LEDS) return "set-leds"; if (value == HUEY_CMD_SENSOR_MEASURE_RGB_ALT) return "measure-rgb-alt"; return NULL; }
Java
#include <iostream> #include "common.h" using namespace storage; using namespace std; StorageInterface* s = NULL; void test(const string& device) { ResizeInfo resize_info; ContentInfo content_info; if (s->getFreeInfo(device, true, resize_info, true, content_info, true)) { cout << device << " true" << endl; cout << " " << resize_info.resize_freeK << " " << resize_info.df_freeK << " " << resize_info.usedK << " " << resize_info.resize_ok << endl; cout << " " << content_info.windows << " " << content_info.efi << " " << content_info.homes << endl; } else { cout << device << " false" << endl; } } int main() { cout.setf(std::ios::boolalpha); setup_logger(); setup_system("thalassa"); s = createStorageInterface(TestEnvironment()); test("/dev/system/arvin"); test("/dev/system/root"); delete s; }
Java
#include <iostream> using namespace std; long long n, ans = 0; long long dn[500][500]; long long rec(long long prlvl, long long sum) { if (sum < 0) return 0; else if (sum == 0) return 1; else { if (dn[prlvl][sum] != -1) return dn[prlvl][sum]; else { long long res = 0; for (int i = 1; i<prlvl; i++) res += rec(i, sum - i); return dn[prlvl][sum] = res; } } } void memorySet() { for (int i = 0; i<500; i++) for (int j = 0; j<500; j++) dn[i][j] = -1; } int main() { memorySet(); cin >> n; for (int i = 1; i<n; i++) ans += rec(i, n - i); cout << ans << endl; }
Java
# OpenStack ocata installation script on Ubuntu 16.04.2 # by kasidit chanchio # vasabilab, dept of computer science, # Thammasat University, Thailand # # Copyright 2017 Kasidit Chanchio # # Run this with sudo or as root #!/bin/bash -x cd $HOME/OPSInstaller/controller pwd echo "check chrony" chronyc sources sleep 1 # #apt-get -y install debconf-utils #debconf-set-selections <<< 'mariadb-server-5.5 mysql-server/root_password password mysqlpassword' #debconf-set-selections <<< 'mariadb-server-5.5 mysql-server/root_password_again password mysqlpassword' apt-get -y install mariadb-server apt-get -y install python-pymysql # printf "* set openstack.cnf configuration... press any key\n" sleep 2 #read varkey #cp files/openstack.cnf /etc/mysql/conf.d/openstack.cnf cp files/99-openstack.cnf /etc/mysql/mariadb.conf.d/99-openstack.cnf #printf "* restart mysql & delete anonymous acct... press\n" #read varkey service mysql restart printf "\n *** First, enter blank for mysql password. Then set new password to\n mysqlpassword \n*** \n" sleep 2 mysql_secure_installation #mysql -u root -pmysqlpassword -e "UPDATE mysql.user SET Password=PASSWORD('mysqlpassword') WHERE User='root';" #mysql -u root -pmysqlpassword -e "DELETE FROM mysql.user WHERE User='root' AND Host NOT IN ('localhost', '127.0.0.1', '::1');" #mysql -u root -pmysqlpassword -e "DELETE FROM mysql.user WHERE User='';" #mysql -u root -pmysqlpassword -e "DELETE FROM mysql.db WHERE Db='test' OR Db='test\_%';" #mysql -u root -pmysqlpassword -e "FLUSH PRIVILEGES;" # #exit 0 #printf "* install nosql... press any key\n" #read varkey #apt-get -y install mongodb-server mongodb-clients python-pymongo #cp files/mongodb.conf /etc/mongodb.conf #service mongodb stop #rm /var/lib/mongodb/journal/prealloc.* #service mongodb start
Java
#!/bin/sh # # Copyright (c) 2006 Junio C Hamano # test_description='Binary diff and apply ' . ./test-lib.sh test_expect_success 'prepare repository' \ 'echo AIT >a && echo BIT >b && echo CIT >c && echo DIT >d && git update-index --add a b c d && echo git >a && cat "$TEST_DIRECTORY"/test4012.png >b && echo git >c && cat b b >d' cat > expected <<\EOF a | 2 +- b | Bin c | 2 +- d | Bin 4 files changed, 2 insertions(+), 2 deletions(-) EOF test_expect_success 'diff without --binary' \ 'git diff | git apply --stat --summary >current && test_cmp expected current' test_expect_success 'diff with --binary' \ 'git diff --binary | git apply --stat --summary >current && test_cmp expected current' # apply needs to be able to skip the binary material correctly # in order to report the line number of a corrupt patch. test_expect_success 'apply detecting corrupt patch correctly' \ 'git diff | sed -e 's/-CIT/xCIT/' >broken && if git apply --stat --summary broken 2>detected then echo unhappy - should have detected an error (exit 1) else echo happy fi && detected=`cat detected` && detected=`expr "$detected" : "fatal.*at line \\([0-9]*\\)\$"` && detected=`sed -ne "${detected}p" broken` && test "$detected" = xCIT' test_expect_success 'apply detecting corrupt patch correctly' \ 'git diff --binary | sed -e 's/-CIT/xCIT/' >broken && if git apply --stat --summary broken 2>detected then echo unhappy - should have detected an error (exit 1) else echo happy fi && detected=`cat detected` && detected=`expr "$detected" : "fatal.*at line \\([0-9]*\\)\$"` && detected=`sed -ne "${detected}p" broken` && test "$detected" = xCIT' test_expect_success 'initial commit' 'git commit -a -m initial' # Try removal (b), modification (d), and creation (e). test_expect_success 'diff-index with --binary' \ 'echo AIT >a && mv b e && echo CIT >c && cat e >d && git update-index --add --remove a b c d e && tree0=`git write-tree` && git diff --cached --binary >current && git apply --stat --summary current' test_expect_success 'apply binary patch' \ 'git reset --hard && git apply --binary --index <current && tree1=`git write-tree` && test "$tree1" = "$tree0"' q_to_nul() { perl -pe 'y/Q/\000/' } nul_to_q() { perl -pe 'y/\000/Q/' } test_expect_success 'diff --no-index with binary creation' ' echo Q | q_to_nul >binary && (:# hide error code from diff, which just indicates differences git diff --binary --no-index /dev/null binary >current || true ) && rm binary && git apply --binary <current && echo Q >expected && nul_to_q <binary >actual && test_cmp expected actual ' test_done
Java
/* * Copyright (C) 2001-2004 by David Brownell * * 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., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* this file is part of ehci-hcd.c */ /*-------------------------------------------------------------------------*/ /* * EHCI Root Hub ... the nonsharable stuff * * Registers don't need cpu_to_le32, that happens transparently */ #ifdef CONFIG_ARCH_MXS #define MXS_USB_HOST_HACK #include <linux/fsl_devices.h> #endif /*-------------------------------------------------------------------------*/ #define PORT_WAKE_BITS (PORT_WKOC_E|PORT_WKDISC_E|PORT_WKCONN_E) #ifdef CONFIG_PM static int ehci_hub_control( struct usb_hcd *hcd, u16 typeReq, u16 wValue, u16 wIndex, char *buf, u16 wLength ); /* After a power loss, ports that were owned by the companion must be * reset so that the companion can still own them. */ static void ehci_handover_companion_ports(struct ehci_hcd *ehci) { u32 __iomem *reg; u32 status; int port; __le32 buf; struct usb_hcd *hcd = ehci_to_hcd(ehci); if (!ehci->owned_ports) return; /* Give the connections some time to appear */ msleep(20); port = HCS_N_PORTS(ehci->hcs_params); while (port--) { if (test_bit(port, &ehci->owned_ports)) { reg = &ehci->regs->port_status[port]; status = ehci_readl(ehci, reg) & ~PORT_RWC_BITS; /* Port already owned by companion? */ if (status & PORT_OWNER) clear_bit(port, &ehci->owned_ports); else if (test_bit(port, &ehci->companion_ports)) ehci_writel(ehci, status & ~PORT_PE, reg); else ehci_hub_control(hcd, SetPortFeature, USB_PORT_FEAT_RESET, port + 1, NULL, 0); } } if (!ehci->owned_ports) return; msleep(90); /* Wait for resets to complete */ port = HCS_N_PORTS(ehci->hcs_params); while (port--) { if (test_bit(port, &ehci->owned_ports)) { ehci_hub_control(hcd, GetPortStatus, 0, port + 1, (char *) &buf, sizeof(buf)); /* The companion should now own the port, * but if something went wrong the port must not * remain enabled. */ reg = &ehci->regs->port_status[port]; status = ehci_readl(ehci, reg) & ~PORT_RWC_BITS; if (status & PORT_OWNER) ehci_writel(ehci, status | PORT_CSC, reg); else { ehci_dbg(ehci, "failed handover port %d: %x\n", port + 1, status); ehci_writel(ehci, status & ~PORT_PE, reg); } } } ehci->owned_ports = 0; } static void ehci_adjust_port_wakeup_flags(struct ehci_hcd *ehci, bool suspending) { int port; u32 temp; /* If remote wakeup is enabled for the root hub but disabled * for the controller, we must adjust all the port wakeup flags * when the controller is suspended or resumed. In all other * cases they don't need to be changed. */ if (!ehci_to_hcd(ehci)->self.root_hub->do_remote_wakeup || device_may_wakeup(ehci_to_hcd(ehci)->self.controller)) return; /* clear phy low-power mode before changing wakeup flags */ if (ehci->has_hostpc) { port = HCS_N_PORTS(ehci->hcs_params); while (port--) { u32 __iomem *hostpc_reg; hostpc_reg = (u32 __iomem *)((u8 *) ehci->regs + HOSTPC0 + 4 * port); temp = ehci_readl(ehci, hostpc_reg); ehci_writel(ehci, temp & ~HOSTPC_PHCD, hostpc_reg); } msleep(5); } port = HCS_N_PORTS(ehci->hcs_params); while (port--) { u32 __iomem *reg = &ehci->regs->port_status[port]; u32 t1 = ehci_readl(ehci, reg) & ~PORT_RWC_BITS; u32 t2 = t1 & ~PORT_WAKE_BITS; /* If we are suspending the controller, clear the flags. * If we are resuming the controller, set the wakeup flags. */ if (!suspending) { if (t1 & PORT_CONNECT) t2 |= PORT_WKOC_E | PORT_WKDISC_E; else t2 |= PORT_WKOC_E | PORT_WKCONN_E; } ehci_vdbg(ehci, "port %d, %08x -> %08x\n", port + 1, t1, t2); ehci_writel(ehci, t2, reg); } /* enter phy low-power mode again */ if (ehci->has_hostpc) { port = HCS_N_PORTS(ehci->hcs_params); while (port--) { u32 __iomem *hostpc_reg; hostpc_reg = (u32 __iomem *)((u8 *) ehci->regs + HOSTPC0 + 4 * port); temp = ehci_readl(ehci, hostpc_reg); ehci_writel(ehci, temp | HOSTPC_PHCD, hostpc_reg); } } } static int ehci_bus_suspend (struct usb_hcd *hcd) { struct ehci_hcd *ehci = hcd_to_ehci (hcd); int port; int mask; int changed; ehci_dbg(ehci, "suspend root hub\n"); if (time_before (jiffies, ehci->next_statechange)) msleep(5); del_timer_sync(&ehci->watchdog); del_timer_sync(&ehci->iaa_watchdog); spin_lock_irq (&ehci->lock); /* Once the controller is stopped, port resumes that are already * in progress won't complete. Hence if remote wakeup is enabled * for the root hub and any ports are in the middle of a resume or * remote wakeup, we must fail the suspend. */ if (hcd->self.root_hub->do_remote_wakeup) { port = HCS_N_PORTS(ehci->hcs_params); while (port--) { if (ehci->reset_done[port] != 0) { spin_unlock_irq(&ehci->lock); ehci_dbg(ehci, "suspend failed because " "port %d is resuming\n", port + 1); return -EBUSY; } } } /* stop schedules, clean any completed work */ if (HC_IS_RUNNING(hcd->state)) { ehci_quiesce (ehci); hcd->state = HC_STATE_QUIESCING; } ehci->command = ehci_readl(ehci, &ehci->regs->command); ehci_work(ehci); /* Unlike other USB host controller types, EHCI doesn't have * any notion of "global" or bus-wide suspend. The driver has * to manually suspend all the active unsuspended ports, and * then manually resume them in the bus_resume() routine. */ ehci->bus_suspended = 0; ehci->owned_ports = 0; changed = 0; port = HCS_N_PORTS(ehci->hcs_params); while (port--) { u32 __iomem *reg = &ehci->regs->port_status [port]; u32 t1 = ehci_readl(ehci, reg) & ~PORT_RWC_BITS; u32 t2 = t1 & ~PORT_WAKE_BITS; /* keep track of which ports we suspend */ if (t1 & PORT_OWNER) set_bit(port, &ehci->owned_ports); else if ((t1 & PORT_PE) && !(t1 & PORT_SUSPEND)) { t2 |= PORT_SUSPEND; set_bit(port, &ehci->bus_suspended); } /* enable remote wakeup on all ports, if told to do so */ if (hcd->self.root_hub->do_remote_wakeup) { /* only enable appropriate wake bits, otherwise the * hardware can not go phy low power mode. If a race * condition happens here(connection change during bits * set), the port change detection will finally fix it. */ if (t1 & PORT_CONNECT) t2 |= PORT_WKOC_E | PORT_WKDISC_E; else t2 |= PORT_WKOC_E | PORT_WKCONN_E; } if (t1 != t2) { ehci_vdbg (ehci, "port %d, %08x -> %08x\n", port + 1, t1, t2); ehci_writel(ehci, t2, reg); changed = 1; } } if (changed && ehci->has_hostpc) { spin_unlock_irq(&ehci->lock); msleep(5); /* 5 ms for HCD to enter low-power mode */ spin_lock_irq(&ehci->lock); port = HCS_N_PORTS(ehci->hcs_params); while (port--) { u32 __iomem *hostpc_reg; u32 t3; hostpc_reg = (u32 __iomem *)((u8 *) ehci->regs + HOSTPC0 + 4 * port); t3 = ehci_readl(ehci, hostpc_reg); ehci_writel(ehci, t3 | HOSTPC_PHCD, hostpc_reg); t3 = ehci_readl(ehci, hostpc_reg); ehci_dbg(ehci, "Port %d phy low-power mode %s\n", port, (t3 & HOSTPC_PHCD) ? "succeeded" : "failed"); } } /* Apparently some devices need a >= 1-uframe delay here */ if (ehci->bus_suspended) udelay(150); /* turn off now-idle HC */ ehci_halt (ehci); hcd->state = HC_STATE_SUSPENDED; if (ehci->reclaim) end_unlink_async(ehci); /* allow remote wakeup */ mask = INTR_MASK; if (!hcd->self.root_hub->do_remote_wakeup) mask &= ~STS_PCD; ehci_writel(ehci, mask, &ehci->regs->intr_enable); ehci_readl(ehci, &ehci->regs->intr_enable); ehci->next_statechange = jiffies + msecs_to_jiffies(10); spin_unlock_irq (&ehci->lock); /* ehci_work() may have re-enabled the watchdog timer, which we do not * want, and so we must delete any pending watchdog timer events. */ del_timer_sync(&ehci->watchdog); return 0; } /* caller has locked the root hub, and should reset/reinit on error */ static int ehci_bus_resume (struct usb_hcd *hcd) { struct ehci_hcd *ehci = hcd_to_ehci (hcd); u32 temp; u32 power_okay; int i; u8 resume_needed = 0; if (time_before (jiffies, ehci->next_statechange)) msleep(5); spin_lock_irq (&ehci->lock); if (!test_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags)) { spin_unlock_irq(&ehci->lock); return -ESHUTDOWN; } if (unlikely(ehci->debug)) { if (!dbgp_reset_prep()) ehci->debug = NULL; else dbgp_external_startup(); } /* Ideally and we've got a real resume here, and no port's power * was lost. (For PCI, that means Vaux was maintained.) But we * could instead be restoring a swsusp snapshot -- so that BIOS was * the last user of the controller, not reset/pm hardware keeping * state we gave to it. */ power_okay = ehci_readl(ehci, &ehci->regs->intr_enable); ehci_dbg(ehci, "resume root hub%s\n", power_okay ? "" : " after power loss"); /* at least some APM implementations will try to deliver * IRQs right away, so delay them until we're ready. */ ehci_writel(ehci, 0, &ehci->regs->intr_enable); /* re-init operational registers */ ehci_writel(ehci, 0, &ehci->regs->segment); ehci_writel(ehci, ehci->periodic_dma, &ehci->regs->frame_list); ehci_writel(ehci, (u32) ehci->async->qh_dma, &ehci->regs->async_next); /* restore CMD_RUN, framelist size, and irq threshold */ ehci_writel(ehci, ehci->command, &ehci->regs->command); /* Some controller/firmware combinations need a delay during which * they set up the port statuses. See Bugzilla #8190. */ spin_unlock_irq(&ehci->lock); msleep(8); spin_lock_irq(&ehci->lock); /* clear phy low-power mode before resume */ if (ehci->bus_suspended && ehci->has_hostpc) { i = HCS_N_PORTS(ehci->hcs_params); while (i--) { if (test_bit(i, &ehci->bus_suspended)) { u32 __iomem *hostpc_reg; hostpc_reg = (u32 __iomem *)((u8 *) ehci->regs + HOSTPC0 + 4 * i); temp = ehci_readl(ehci, hostpc_reg); ehci_writel(ehci, temp & ~HOSTPC_PHCD, hostpc_reg); } } spin_unlock_irq(&ehci->lock); msleep(5); spin_lock_irq(&ehci->lock); } /* manually resume the ports we suspended during bus_suspend() */ i = HCS_N_PORTS (ehci->hcs_params); while (i--) { temp = ehci_readl(ehci, &ehci->regs->port_status [i]); temp &= ~(PORT_RWC_BITS | PORT_WAKE_BITS); if (test_bit(i, &ehci->bus_suspended) && (temp & PORT_SUSPEND)) { temp |= PORT_RESUME; resume_needed = 1; } ehci_writel(ehci, temp, &ehci->regs->port_status [i]); } /* msleep for 20ms only if code is trying to resume port */ if (resume_needed) { spin_unlock_irq(&ehci->lock); msleep(20); #ifdef MXS_USB_HOST_HACK { struct fsl_usb2_platform_data *pdata; pdata = hcd->self.controller->platform_data; if (pdata && pdata->platform_resume) pdata->platform_resume(pdata); } #endif spin_lock_irq(&ehci->lock); } i = HCS_N_PORTS (ehci->hcs_params); while (i--) { temp = ehci_readl(ehci, &ehci->regs->port_status [i]); if (test_bit(i, &ehci->bus_suspended) && (temp & PORT_SUSPEND)) { temp &= ~(PORT_RWC_BITS | PORT_RESUME); ehci_writel(ehci, temp, &ehci->regs->port_status [i]); ehci_vdbg (ehci, "resumed port %d\n", i + 1); } } (void) ehci_readl(ehci, &ehci->regs->command); /* maybe re-activate the schedule(s) */ temp = 0; if (ehci->async->qh_next.qh) temp |= CMD_ASE; if (ehci->periodic_sched) temp |= CMD_PSE; if (temp) { ehci->command |= temp; ehci_writel(ehci, ehci->command, &ehci->regs->command); } ehci->next_statechange = jiffies + msecs_to_jiffies(5); hcd->state = HC_STATE_RUNNING; /* Now we can safely re-enable irqs */ ehci_writel(ehci, INTR_MASK, &ehci->regs->intr_enable); spin_unlock_irq (&ehci->lock); ehci_handover_companion_ports(ehci); return 0; } #else #define ehci_bus_suspend NULL #define ehci_bus_resume NULL #endif /* CONFIG_PM */ /*-------------------------------------------------------------------------*/ /* Display the ports dedicated to the companion controller */ static ssize_t show_companion(struct device *dev, struct device_attribute *attr, char *buf) { struct ehci_hcd *ehci; int nports, index, n; int count = PAGE_SIZE; char *ptr = buf; ehci = hcd_to_ehci(bus_to_hcd(dev_get_drvdata(dev))); nports = HCS_N_PORTS(ehci->hcs_params); for (index = 0; index < nports; ++index) { if (test_bit(index, &ehci->companion_ports)) { n = scnprintf(ptr, count, "%d\n", index + 1); ptr += n; count -= n; } } return ptr - buf; } /* * Sets the owner of a port */ static void set_owner(struct ehci_hcd *ehci, int portnum, int new_owner) { u32 __iomem *status_reg; u32 port_status; int try; status_reg = &ehci->regs->port_status[portnum]; /* * The controller won't set the OWNER bit if the port is * enabled, so this loop will sometimes require at least two * iterations: one to disable the port and one to set OWNER. */ for (try = 4; try > 0; --try) { spin_lock_irq(&ehci->lock); port_status = ehci_readl(ehci, status_reg); if ((port_status & PORT_OWNER) == new_owner || (port_status & (PORT_OWNER | PORT_CONNECT)) == 0) try = 0; else { port_status ^= PORT_OWNER; port_status &= ~(PORT_PE | PORT_RWC_BITS); ehci_writel(ehci, port_status, status_reg); } spin_unlock_irq(&ehci->lock); if (try > 1) msleep(5); } } /* * Dedicate or undedicate a port to the companion controller. * Syntax is "[-]portnum", where a leading '-' sign means * return control of the port to the EHCI controller. */ static ssize_t store_companion(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct ehci_hcd *ehci; int portnum, new_owner; ehci = hcd_to_ehci(bus_to_hcd(dev_get_drvdata(dev))); new_owner = PORT_OWNER; /* Owned by companion */ if (sscanf(buf, "%d", &portnum) != 1) return -EINVAL; if (portnum < 0) { portnum = - portnum; new_owner = 0; /* Owned by EHCI */ } if (portnum <= 0 || portnum > HCS_N_PORTS(ehci->hcs_params)) return -ENOENT; portnum--; if (new_owner) set_bit(portnum, &ehci->companion_ports); else clear_bit(portnum, &ehci->companion_ports); set_owner(ehci, portnum, new_owner); return count; } static DEVICE_ATTR(companion, 0644, show_companion, store_companion); static inline void create_companion_file(struct ehci_hcd *ehci) { int i; /* with integrated TT there is no companion! */ if (!ehci_is_TDI(ehci)) i = device_create_file(ehci_to_hcd(ehci)->self.controller, &dev_attr_companion); } static inline void remove_companion_file(struct ehci_hcd *ehci) { /* with integrated TT there is no companion! */ if (!ehci_is_TDI(ehci)) device_remove_file(ehci_to_hcd(ehci)->self.controller, &dev_attr_companion); } /*-------------------------------------------------------------------------*/ static int check_reset_complete ( struct ehci_hcd *ehci, int index, u32 __iomem *status_reg, int port_status ) { if (!(port_status & PORT_CONNECT)) return port_status; /* if reset finished and it's still not enabled -- handoff */ if (!(port_status & PORT_PE)) { /* with integrated TT, there's nobody to hand it to! */ if (ehci_is_TDI(ehci)) { ehci_dbg (ehci, "Failed to enable port %d on root hub TT\n", index+1); return port_status; } ehci_dbg (ehci, "port %d full speed --> companion\n", index + 1); // what happens if HCS_N_CC(params) == 0 ? port_status |= PORT_OWNER; port_status &= ~PORT_RWC_BITS; ehci_writel(ehci, port_status, status_reg); /* ensure 440EPX ohci controller state is operational */ if (ehci->has_amcc_usb23) set_ohci_hcfs(ehci, 1); } else { ehci_dbg (ehci, "port %d high speed\n", index + 1); /* ensure 440EPx ohci controller state is suspended */ if (ehci->has_amcc_usb23) set_ohci_hcfs(ehci, 0); } return port_status; } /*-------------------------------------------------------------------------*/ /* build "status change" packet (one or two bytes) from HC registers */ static int ehci_hub_status_data (struct usb_hcd *hcd, char *buf) { struct ehci_hcd *ehci = hcd_to_ehci (hcd); u32 temp, status = 0; u32 mask; int ports, i, retval = 1; unsigned long flags; /* if !USB_SUSPEND, root hub timers won't get shut down ... */ if (!HC_IS_RUNNING(hcd->state)) return 0; /* init status to no-changes */ buf [0] = 0; ports = HCS_N_PORTS (ehci->hcs_params); if (ports > 7) { buf [1] = 0; retval++; } /* Some boards (mostly VIA?) report bogus overcurrent indications, * causing massive log spam unless we completely ignore them. It * may be relevant that VIA VT8235 controllers, where PORT_POWER is * always set, seem to clear PORT_OCC and PORT_CSC when writing to * PORT_POWER; that's surprising, but maybe within-spec. */ if (!ignore_oc) mask = PORT_CSC | PORT_PEC | PORT_OCC; else mask = PORT_CSC | PORT_PEC; // PORT_RESUME from hardware ~= PORT_STAT_C_SUSPEND /* no hub change reports (bit 0) for now (power, ...) */ /* port N changes (bit N)? */ spin_lock_irqsave (&ehci->lock, flags); for (i = 0; i < ports; i++) { temp = ehci_readl(ehci, &ehci->regs->port_status [i]); /* * Return status information even for ports with OWNER set. * Otherwise khubd wouldn't see the disconnect event when a * high-speed device is switched over to the companion * controller by the user. */ if ((temp & mask) != 0 || test_bit(i, &ehci->port_c_suspend) || (ehci->reset_done[i] && time_after_eq( jiffies, ehci->reset_done[i]))) { if (i < 7) buf [0] |= 1 << (i + 1); else buf [1] |= 1 << (i - 7); status = STS_PCD; } } /* FIXME autosuspend idle root hubs */ spin_unlock_irqrestore (&ehci->lock, flags); return status ? retval : 0; } /*-------------------------------------------------------------------------*/ static void ehci_hub_descriptor ( struct ehci_hcd *ehci, struct usb_hub_descriptor *desc ) { int ports = HCS_N_PORTS (ehci->hcs_params); u16 temp; desc->bDescriptorType = 0x29; desc->bPwrOn2PwrGood = 10; /* ehci 1.0, 2.3.9 says 20ms max */ desc->bHubContrCurrent = 0; desc->bNbrPorts = ports; temp = 1 + (ports / 8); desc->bDescLength = 7 + 2 * temp; /* two bitmaps: ports removable, and usb 1.0 legacy PortPwrCtrlMask */ memset (&desc->bitmap [0], 0, temp); memset (&desc->bitmap [temp], 0xff, temp); temp = 0x0008; /* per-port overcurrent reporting */ if (HCS_PPC (ehci->hcs_params)) temp |= 0x0001; /* per-port power control */ else temp |= 0x0002; /* no power switching */ #if 0 // re-enable when we support USB_PORT_FEAT_INDICATOR below. if (HCS_INDICATOR (ehci->hcs_params)) temp |= 0x0080; /* per-port indicators (LEDs) */ #endif desc->wHubCharacteristics = cpu_to_le16(temp); } /*-------------------------------------------------------------------------*/ static int ehci_hub_control ( struct usb_hcd *hcd, u16 typeReq, u16 wValue, u16 wIndex, char *buf, u16 wLength ) { struct ehci_hcd *ehci = hcd_to_ehci (hcd); int ports = HCS_N_PORTS (ehci->hcs_params); u32 __iomem *status_reg = &ehci->regs->port_status[ (wIndex & 0xff) - 1]; u32 __iomem *hostpc_reg = NULL; u32 temp, temp1, status; unsigned long flags; int retval = 0; unsigned selector; /* * FIXME: support SetPortFeatures USB_PORT_FEAT_INDICATOR. * HCS_INDICATOR may say we can change LEDs to off/amber/green. * (track current state ourselves) ... blink for diagnostics, * power, "this is the one", etc. EHCI spec supports this. */ if (ehci->has_hostpc) hostpc_reg = (u32 __iomem *)((u8 *)ehci->regs + HOSTPC0 + 4 * ((wIndex & 0xff) - 1)); spin_lock_irqsave (&ehci->lock, flags); switch (typeReq) { case ClearHubFeature: switch (wValue) { case C_HUB_LOCAL_POWER: case C_HUB_OVER_CURRENT: /* no hub-wide feature/status flags */ break; default: goto error; } break; case ClearPortFeature: if (!wIndex || wIndex > ports) goto error; wIndex--; temp = ehci_readl(ehci, status_reg); /* * Even if OWNER is set, so the port is owned by the * companion controller, khubd needs to be able to clear * the port-change status bits (especially * USB_PORT_STAT_C_CONNECTION). */ switch (wValue) { case USB_PORT_FEAT_ENABLE: ehci_writel(ehci, temp & ~PORT_PE, status_reg); break; case USB_PORT_FEAT_C_ENABLE: ehci_writel(ehci, (temp & ~PORT_RWC_BITS) | PORT_PEC, status_reg); break; case USB_PORT_FEAT_SUSPEND: if (temp & PORT_RESET) goto error; if (ehci->no_selective_suspend) break; if (!(temp & PORT_SUSPEND)) break; if ((temp & PORT_PE) == 0) goto error; /* clear phy low-power mode before resume */ if (hostpc_reg) { temp1 = ehci_readl(ehci, hostpc_reg); ehci_writel(ehci, temp1 & ~HOSTPC_PHCD, hostpc_reg); spin_unlock_irqrestore(&ehci->lock, flags); msleep(5);/* wait to leave low-power mode */ spin_lock_irqsave(&ehci->lock, flags); } /* resume signaling for 20 msec */ temp &= ~(PORT_RWC_BITS | PORT_WAKE_BITS); ehci_writel(ehci, temp | PORT_RESUME, status_reg); ehci->reset_done[wIndex] = jiffies + msecs_to_jiffies(20); break; case USB_PORT_FEAT_C_SUSPEND: clear_bit(wIndex, &ehci->port_c_suspend); break; case USB_PORT_FEAT_POWER: if (HCS_PPC (ehci->hcs_params)) ehci_writel(ehci, temp & ~(PORT_RWC_BITS | PORT_POWER), status_reg); break; case USB_PORT_FEAT_C_CONNECTION: ehci_writel(ehci, (temp & ~PORT_RWC_BITS) | PORT_CSC, status_reg); break; case USB_PORT_FEAT_C_OVER_CURRENT: ehci_writel(ehci, (temp & ~PORT_RWC_BITS) | PORT_OCC, status_reg); break; case USB_PORT_FEAT_C_RESET: /* GetPortStatus clears reset */ break; default: goto error; } ehci_readl(ehci, &ehci->regs->command); /* unblock posted write */ break; case GetHubDescriptor: ehci_hub_descriptor (ehci, (struct usb_hub_descriptor *) buf); break; case GetHubStatus: /* no hub-wide feature/status flags */ memset (buf, 0, 4); //cpu_to_le32s ((u32 *) buf); break; case GetPortStatus: if (!wIndex || wIndex > ports) goto error; wIndex--; status = 0; temp = ehci_readl(ehci, status_reg); // wPortChange bits if (temp & PORT_CSC) status |= USB_PORT_STAT_C_CONNECTION << 16; if (temp & PORT_PEC) status |= USB_PORT_STAT_C_ENABLE << 16; if ((temp & PORT_OCC) && !ignore_oc){ status |= USB_PORT_STAT_C_OVERCURRENT << 16; /* * Hubs should disable port power on over-current. * However, not all EHCI implementations do this * automatically, even if they _do_ support per-port * power switching; they're allowed to just limit the * current. khubd will turn the power back on. */ if (HCS_PPC (ehci->hcs_params)){ ehci_writel(ehci, temp & ~(PORT_RWC_BITS | PORT_POWER), status_reg); } } /* whoever resumes must GetPortStatus to complete it!! */ if (temp & PORT_RESUME) { /* Remote Wakeup received? */ if (!ehci->reset_done[wIndex]) { /* resume signaling for 20 msec */ ehci->reset_done[wIndex] = jiffies + msecs_to_jiffies(20); /* check the port again */ mod_timer(&ehci_to_hcd(ehci)->rh_timer, ehci->reset_done[wIndex]); } /* resume completed? */ else if (time_after_eq(jiffies, ehci->reset_done[wIndex])) { clear_bit(wIndex, &ehci->suspended_ports); set_bit(wIndex, &ehci->port_c_suspend); ehci->reset_done[wIndex] = 0; /* stop resume signaling */ temp = ehci_readl(ehci, status_reg); ehci_writel(ehci, temp & ~(PORT_RWC_BITS | PORT_RESUME), status_reg); retval = handshake(ehci, status_reg, PORT_RESUME, 0, 2000 /* 2msec */); if (retval != 0) { ehci_err(ehci, "port %d resume error %d\n", wIndex + 1, retval); goto error; } temp &= ~(PORT_SUSPEND|PORT_RESUME|(3<<10)); } } /* whoever resets must GetPortStatus to complete it!! */ if ((temp & PORT_RESET) && time_after_eq(jiffies, ehci->reset_done[wIndex])) { status |= USB_PORT_STAT_C_RESET << 16; ehci->reset_done [wIndex] = 0; /* force reset to complete */ ehci_writel(ehci, temp & ~(PORT_RWC_BITS | PORT_RESET), status_reg); /* REVISIT: some hardware needs 550+ usec to clear * this bit; seems too long to spin routinely... */ retval = handshake(ehci, status_reg, PORT_RESET, 0, 1000); if (retval != 0) { ehci_err (ehci, "port %d reset error %d\n", wIndex + 1, retval); goto error; } /* see what we found out */ temp = check_reset_complete (ehci, wIndex, status_reg, ehci_readl(ehci, status_reg)); } if (!(temp & (PORT_RESUME|PORT_RESET))) ehci->reset_done[wIndex] = 0; /* transfer dedicated ports to the companion hc */ if ((temp & PORT_CONNECT) && test_bit(wIndex, &ehci->companion_ports)) { temp &= ~PORT_RWC_BITS; temp |= PORT_OWNER; ehci_writel(ehci, temp, status_reg); ehci_dbg(ehci, "port %d --> companion\n", wIndex + 1); temp = ehci_readl(ehci, status_reg); } /* * Even if OWNER is set, there's no harm letting khubd * see the wPortStatus values (they should all be 0 except * for PORT_POWER anyway). */ if (temp & PORT_CONNECT) { status |= USB_PORT_STAT_CONNECTION; // status may be from integrated TT if (ehci->has_hostpc) { temp1 = ehci_readl(ehci, hostpc_reg); status |= ehci_port_speed(ehci, temp1); } else status |= ehci_port_speed(ehci, temp); } if (temp & PORT_PE) status |= USB_PORT_STAT_ENABLE; /* maybe the port was unsuspended without our knowledge */ if (temp & (PORT_SUSPEND|PORT_RESUME)) { status |= USB_PORT_STAT_SUSPEND; } else if (test_bit(wIndex, &ehci->suspended_ports)) { clear_bit(wIndex, &ehci->suspended_ports); ehci->reset_done[wIndex] = 0; if (temp & PORT_PE) set_bit(wIndex, &ehci->port_c_suspend); } if (temp & PORT_OC) status |= USB_PORT_STAT_OVERCURRENT; if (temp & PORT_RESET) status |= USB_PORT_STAT_RESET; if (temp & PORT_POWER) status |= USB_PORT_STAT_POWER; if (test_bit(wIndex, &ehci->port_c_suspend)) status |= USB_PORT_STAT_C_SUSPEND << 16; #ifndef VERBOSE_DEBUG if (status & ~0xffff) /* only if wPortChange is interesting */ #endif dbg_port (ehci, "GetStatus", wIndex + 1, temp); put_unaligned_le32(status, buf); break; case SetHubFeature: switch (wValue) { case C_HUB_LOCAL_POWER: case C_HUB_OVER_CURRENT: /* no hub-wide feature/status flags */ break; default: goto error; } break; case SetPortFeature: selector = wIndex >> 8; wIndex &= 0xff; if (unlikely(ehci->debug)) { /* If the debug port is active any port * feature requests should get denied */ if (wIndex == HCS_DEBUG_PORT(ehci->hcs_params) && (readl(&ehci->debug->control) & DBGP_ENABLED)) { retval = -ENODEV; goto error_exit; } } if (!wIndex || wIndex > ports) goto error; wIndex--; temp = ehci_readl(ehci, status_reg); if (temp & PORT_OWNER) break; temp &= ~PORT_RWC_BITS; switch (wValue) { case USB_PORT_FEAT_SUSPEND: if (ehci->no_selective_suspend) break; if ((temp & PORT_PE) == 0 || (temp & PORT_RESET) != 0) goto error; /* After above check the port must be connected. * Set appropriate bit thus could put phy into low power * mode if we have hostpc feature */ temp &= ~PORT_WKCONN_E; temp |= PORT_WKDISC_E | PORT_WKOC_E; ehci_writel(ehci, temp | PORT_SUSPEND, status_reg); #ifdef MXS_USB_HOST_HACK spin_unlock_irqrestore(&ehci->lock, flags); { struct fsl_usb2_platform_data *pdata; pdata = hcd->self.controller->platform_data; if (pdata && pdata->platform_suspend) pdata->platform_suspend(pdata); } spin_lock_irqsave(&ehci->lock, flags); #endif if (hostpc_reg) { spin_unlock_irqrestore(&ehci->lock, flags); msleep(5);/* 5ms for HCD enter low pwr mode */ spin_lock_irqsave(&ehci->lock, flags); temp1 = ehci_readl(ehci, hostpc_reg); ehci_writel(ehci, temp1 | HOSTPC_PHCD, hostpc_reg); temp1 = ehci_readl(ehci, hostpc_reg); ehci_dbg(ehci, "Port%d phy low pwr mode %s\n", wIndex, (temp1 & HOSTPC_PHCD) ? "succeeded" : "failed"); } set_bit(wIndex, &ehci->suspended_ports); break; case USB_PORT_FEAT_POWER: if (HCS_PPC (ehci->hcs_params)) ehci_writel(ehci, temp | PORT_POWER, status_reg); break; case USB_PORT_FEAT_RESET: if (temp & PORT_RESUME) goto error; /* line status bits may report this as low speed, * which can be fine if this root hub has a * transaction translator built in. */ if ((temp & (PORT_PE|PORT_CONNECT)) == PORT_CONNECT && !ehci_is_TDI(ehci) && PORT_USB11 (temp)) { ehci_dbg (ehci, "port %d low speed --> companion\n", wIndex + 1); temp |= PORT_OWNER; } else { ehci_vdbg (ehci, "port %d reset\n", wIndex + 1); temp |= PORT_RESET; temp &= ~PORT_PE; /* * caller must wait, then call GetPortStatus * usb 2.0 spec says 50 ms resets on root */ ehci->reset_done [wIndex] = jiffies + msecs_to_jiffies (50); } ehci_writel(ehci, temp, status_reg); break; /* For downstream facing ports (these): one hub port is put * into test mode according to USB2 11.24.2.13, then the hub * must be reset (which for root hub now means rmmod+modprobe, * or else system reboot). See EHCI 2.3.9 and 4.14 for info * about the EHCI-specific stuff. */ case USB_PORT_FEAT_TEST: if (!selector || selector > 5) goto error; ehci_quiesce(ehci); ehci_halt(ehci); temp |= selector << 16; ehci_writel(ehci, temp, status_reg); break; default: goto error; } ehci_readl(ehci, &ehci->regs->command); /* unblock posted writes */ break; default: error: /* "stall" on error */ retval = -EPIPE; } error_exit: spin_unlock_irqrestore (&ehci->lock, flags); return retval; } static void ehci_relinquish_port(struct usb_hcd *hcd, int portnum) { struct ehci_hcd *ehci = hcd_to_ehci(hcd); if (ehci_is_TDI(ehci)) return; set_owner(ehci, --portnum, PORT_OWNER); } static int ehci_port_handed_over(struct usb_hcd *hcd, int portnum) { struct ehci_hcd *ehci = hcd_to_ehci(hcd); u32 __iomem *reg; if (ehci_is_TDI(ehci)) return 0; reg = &ehci->regs->port_status[portnum - 1]; return ehci_readl(ehci, reg) & PORT_OWNER; }
Java
/** * @file error.c Error functions * * purple * * Purple is the legal property of its developers, whose names are too numerous * to list here. Please refer to the COPYRIGHT file distributed with this * source distribution. * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "nateon.h" #include "error.h" const char * nateon_error_get_text(unsigned int type, gboolean *debug) { static char msg[NATEON_BUF_LEN]; *debug = FALSE; switch (type) { // case 0: // g_snprintf(msg, sizeof(msg), // _("Unable to parse message")); // *debug = TRUE; // break; // case 200: // g_snprintf(msg, sizeof(msg), // _("Syntax Error (probably a client bug)")); // *debug = TRUE; // break; // case 201: // g_snprintf(msg, sizeof(msg), // _("Invalid e-mail address")); // break; // case 205: // g_snprintf(msg, sizeof(msg), _("User does not exist")); // break; // case 206: // g_snprintf(msg, sizeof(msg), // _("Fully qualified domain name missing")); // break; // case 207: // g_snprintf(msg, sizeof(msg), _("Already logged in")); // break; // case 208: // g_snprintf(msg, sizeof(msg), _("Invalid screen name")); // break; // case 209: // g_snprintf(msg, sizeof(msg), _("Invalid friendly name")); // break; // case 210: // g_snprintf(msg, sizeof(msg), _("List full")); // break; // case 215: // g_snprintf(msg, sizeof(msg), _("Already there")); // *debug = TRUE; // break; // case 216: // g_snprintf(msg, sizeof(msg), _("Not on list")); // break; // case 217: // g_snprintf(msg, sizeof(msg), _("User is offline")); // break; // case 218: // g_snprintf(msg, sizeof(msg), _("Already in the mode")); // *debug = TRUE; // break; // case 219: // g_snprintf(msg, sizeof(msg), _("Already in opposite list")); // *debug = TRUE; // break; // case 223: // g_snprintf(msg, sizeof(msg), _("Too many groups")); // break; // case 224: // g_snprintf(msg, sizeof(msg), _("Invalid group")); // break; // case 225: // g_snprintf(msg, sizeof(msg), _("User not in group")); // break; // case 229: // g_snprintf(msg, sizeof(msg), _("Group name too long")); // break; // case 230: // g_snprintf(msg, sizeof(msg), _("Cannot remove group zero")); // *debug = TRUE; // break; // case 231: // g_snprintf(msg, sizeof(msg), // _("Tried to add a user to a group " // "that doesn't exist")); // break; // case 280: // g_snprintf(msg, sizeof(msg), _("Switchboard failed")); // *debug = TRUE; // break; // case 281: // g_snprintf(msg, sizeof(msg), _("Notify transfer failed")); // *debug = TRUE; // break; // // case 300: // g_snprintf(msg, sizeof(msg), _("Required fields missing")); // *debug = TRUE; // break; // case 301: // g_snprintf(msg, sizeof(msg), _("Too many hits to a FND")); // *debug = TRUE; // break; // case 302: // g_snprintf(msg, sizeof(msg), _("Not logged in")); // break; // // case 500: // g_snprintf(msg, sizeof(msg), _("Service temporarily unavailable")); // break; // case 501: // g_snprintf(msg, sizeof(msg), _("Database server error")); // *debug = TRUE; // break; // case 502: // g_snprintf(msg, sizeof(msg), _("Command disabled")); // *debug = TRUE; // break; // case 510: // g_snprintf(msg, sizeof(msg), _("File operation error")); // *debug = TRUE; // break; // case 520: // g_snprintf(msg, sizeof(msg), _("Memory allocation error")); // *debug = TRUE; // break; // case 540: // g_snprintf(msg, sizeof(msg), _("Wrong CHL value sent to server")); // *debug = TRUE; // break; // // case 600: // g_snprintf(msg, sizeof(msg), _("Server busy")); // break; // case 601: // g_snprintf(msg, sizeof(msg), _("Server unavailable")); // break; // case 602: // g_snprintf(msg, sizeof(msg), _("Peer notification server down")); // *debug = TRUE; // break; // case 603: // g_snprintf(msg, sizeof(msg), _("Database connect error")); // *debug = TRUE; // break; // case 604: // g_snprintf(msg, sizeof(msg), // _("Server is going down (abandon ship)")); // break; // case 605: // g_snprintf(msg, sizeof(msg), _("Server unavailable")); // break; // // case 707: // g_snprintf(msg, sizeof(msg), _("Error creating connection")); // *debug = TRUE; // break; // case 710: // g_snprintf(msg, sizeof(msg), // _("CVR parameters are either unknown or not allowed")); // *debug = TRUE; // break; // case 711: // g_snprintf(msg, sizeof(msg), _("Unable to write")); // break; // case 712: // g_snprintf(msg, sizeof(msg), _("Session overload")); // *debug = TRUE; // break; // case 713: // g_snprintf(msg, sizeof(msg), _("User is too active")); // break; // case 714: // g_snprintf(msg, sizeof(msg), _("Too many sessions")); // break; // case 715: // g_snprintf(msg, sizeof(msg), _("Passport not verified")); // break; // case 717: // g_snprintf(msg, sizeof(msg), _("Bad friend file")); // *debug = TRUE; // break; // case 731: // g_snprintf(msg, sizeof(msg), _("Not expected")); // *debug = TRUE; // break; // // case 800: // g_snprintf(msg, sizeof(msg), // _("Friendly name changes too rapidly")); // break; // // case 910: // case 912: // case 918: // case 919: // case 921: // case 922: // g_snprintf(msg, sizeof(msg), _("Server too busy")); // break; // case 911: // case 917: // g_snprintf(msg, sizeof(msg), _("Authentication failed")); // break; // case 913: // g_snprintf(msg, sizeof(msg), _("Not allowed when offline")); // break; // case 914: // case 915: // case 916: // g_snprintf(msg, sizeof(msg), _("Server unavailable")); // break; // case 920: // g_snprintf(msg, sizeof(msg), _("Not accepting new users")); // break; // case 923: // g_snprintf(msg, sizeof(msg), // _("Kids Passport without parental consent")); // break; // case 924: // g_snprintf(msg, sizeof(msg), // _("Passport account not yet verified")); // break; // case 928: // g_snprintf(msg, sizeof(msg), _("Bad ticket")); // *debug = TRUE; // break; default: g_snprintf(msg, sizeof(msg), _("Unknown Error Code %d"), type); *debug = TRUE; break; } return msg; } void nateon_error_handle(NateonSession *session, unsigned int type) { char buf[NATEON_BUF_LEN]; gboolean debug; g_snprintf(buf, sizeof(buf), _("NATEON Error: %s\n"), nateon_error_get_text(type, &debug)); if (debug) purple_debug_warning("nateon", "error %d: %s\n", type, buf); else purple_notify_error(session->account->gc, NULL, buf, NULL); }
Java
<?php class Zend_View_Helper_WebSectionTemplate extends Zend_View_Helper_Abstract { public function webSectionTemplate($area) { $html = ''; $html.= '<div class="row-fluid">'; $html.= '<div class="span12">'; $html.= '<div class="page-header">'; $html.= '<h1>Header Layout Default</h1>'; $html.= '</div>'; $html.= '</div>'; $html.= '</div>'; $html.= '<div class="row-fluid">'; $html.= '<div class="span12">'; $html.= '<div class="page-header">'; $html.= '<h1>Menu <a href="/">'.$lang->translate('Home').'</a></h1>'; $html.= '</div>'; $html.= '</div>'; $html.= '</div>'; $html.= '<div class="row-fluid">'; $html.= '<div class="span6">'; $html.= '<div class="row-fluid">'; $html.= '<div class="page-header">'; $html.= '<h2>area 1</h2>'; $html.= $area[1]; $html.= '</div>'; $html.= '</div>'; $html.= '</div>'; $html.= '<div class="span6">'; $html.= '<div class="row-fluid">'; $html.= '<div class="page-header">'; $html.= '<h2>area 2</h2>'; $html.= $area[2]; $html.= '</div>'; $html.= '</div>'; $html.= '<div class="row-fluid">'; $html.= '<div class="page-header">'; $html.= '<h2>area 3</h2>'; $html.= $area[3]; $html.= '</div>'; $html.= '</div>'; $html.= '</div>'; $html.= '</div>'; //$html.= $area_1.' '.$area_2.' '.$area_3; return $html; } }
Java
var EFA = { log: [], /* Prevent backspace being used as back button in infopath form in modal. Source: http://johnliu.net/blog/2012/3/27/infopath-disabling-backspace-key-in-browser-form.html grab a reference to the modal window object in SharePoint */ OpenPopUpPage: function( url ){ var options = SP.UI.$create_DialogOptions(); options.url = url; var w = SP.UI.ModalDialog.showModalDialog(options); /* Attempt to prevent backspace acting as navigation key on read only input - Doesn't currently work. if (w) { // get the modal window's iFrame element var f = w.get_frameElement(); EFA.f = f; // watch frame's readyState change - when page load is complete, re-attach keydown event // on the new document $(f).ready(function(){ var fwin = this.contentWindow || this.contentDocument; $(fwin.document).on('focus',"input[readonly]",function(){ $(this).blur(); }); }); }*/ }, // get current user checkCurrentUser: function (callback){ ExecuteOrDelayUntilScriptLoaded(checkCurrentUserLoaded, "sp.js"); function checkCurrentUserLoaded() { var context = SP.ClientContext.get_current(); var siteColl = context.get_site(); var web = siteColl.get_rootWeb(); this._currentUser = web.get_currentUser(); context.load(this._currentUser); context.executeQueryAsync(Function.createDelegate(this, callback),Function.createDelegate(this, callback)); } }, CheckUserSucceeded: function(){ EFA['User'] = this._currentUser; }, CheckUserfailed: function(){ //console.log('Failed to get user'); }, DoesUserHaveCreatePermissions: function(url, callback) { var Xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\ <soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\ <soap:Body>\ <DoesCurrentUserHavePermissionsToList xmlns=\"http://tempuri.org/\">\ <url>"+ url +"</url>\ </DoesCurrentUserHavePermissionsToList>\ </soap:Body>\ </soap:Envelope>"; $.ajax({ url: "/_layouts/EFA/EFAWebServices.asmx", type: "POST", dataType: "xml", data: Xml, complete: function(xData, Status){ if(Status != 'success') throw "Failed to determine user permissions for " + url; callback(xData); }, contentType: "text/xml; charset=\"utf-8\"" }); } }; /* To access the mapping need to uses keys, therefore need to check if its available for browser and add it if not. Then we can loop through the mapping like so: $.each(keys(config.mapping), function(){ console.log(config.mapping[this.toString()]) }); using this to build the query and create the resultant html */ // SOURCE: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys if (!Object.keys) { Object.keys = (function () { var hasOwnProperty = Object.prototype.hasOwnProperty, hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'), dontEnums = [ 'toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor' ], dontEnumsLength = dontEnums.length; return function (obj) { if (typeof obj !== 'object' && typeof obj !== 'function' || obj === null) throw new TypeError('Object.keys called on non-object'); var result = []; for (var prop in obj) { if (hasOwnProperty.call(obj, prop)) result.push(prop); } if (hasDontEnumBug) { for (var i=0; i < dontEnumsLength; i++) { if (hasOwnProperty.call(obj, dontEnums[i])) result.push(dontEnums[i]); } } return result; }; })(); } /* Array.indexOf for IE https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf */ if (!Array.prototype.indexOf) { Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) { 'use strict'; if (this == null) { throw new TypeError(); } var n, k, t = Object(this), len = t.length >>> 0; if (len === 0) { return -1; } n = 0; if (arguments.length > 1) { n = Number(arguments[1]); if (n != n) { // shortcut for verifying if it's NaN n = 0; } else if (n != 0 && n != Infinity && n != -Infinity) { n = (n > 0 || -1) * Math.floor(Math.abs(n)); } } if (n >= len) { return -1; } for (k = n >= 0 ? n : Math.max(len - Math.abs(n), 0); k < len; k++) { if (k in t && t[k] === searchElement) { return k; } } return -1; }; } /* Test for Canvas Suppport Source: http://stackoverflow.com/questions/2745432/best-way-to-detect-that-html5-canvas-is-not-supported/2746983#2746983 */ function isCanvasSupported(){ var elem = document.createElement('canvas'); return !!(elem.getContext && elem.getContext('2d')); } /* Console.log() for IE 8 */ (function() { if (!window.console) { window.console = {}; } // union of Chrome, FF, IE, and Safari console methods var m = [ "log", "info", "warn", "error", "debug", "trace", "dir", "group", "groupCollapsed", "groupEnd", "time", "timeEnd", "profile", "profileEnd", "dirxml", "assert", "count", "markTimeline", "timeStamp", "clear" ]; // define undefined methods as noops to prevent errors for (var i = 0; i < m.length; i++) { if (!window.console[m[i]]) { window.console[m[i]] = function() {}; } } })();
Java
/* * arch/arm/include/asm/pgtable.h * * Copyright (C) 1995-2002 Russell King * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #ifndef _ASMARM_PGTABLE_H #define _ASMARM_PGTABLE_H #include <linux/const.h> #include <asm/proc-fns.h> #ifndef CONFIG_MMU #include <asm-generic/4level-fixup.h> #include "pgtable-nommu.h" #else #include <asm-generic/pgtable-nopud.h> #include <asm/memory.h> #include <asm/pgtable-hwdef.h> #ifdef CONFIG_ARM_LPAE #include <asm/pgtable-3level.h> #else #include <asm/pgtable-2level.h> #endif /* * Just any arbitrary offset to the start of the vmalloc VM area: the * current 8MB value just means that there will be a 8MB "hole" after the * physical memory until the kernel virtual memory starts. That means that * any out-of-bounds memory accesses will hopefully be caught. * The vmalloc() routines leaves a hole of 4kB between each vmalloced * area for the same reason. ;) */ #define VMALLOC_OFFSET (8*1024*1024) #define VMALLOC_START (((unsigned long)high_memory + VMALLOC_OFFSET) & ~(VMALLOC_OFFSET-1)) #define VMALLOC_END 0xff000000UL #define LIBRARY_TEXT_START 0x0c000000 #ifndef __ASSEMBLY__ extern void __pte_error(const char *file, int line, pte_t); extern void __pmd_error(const char *file, int line, pmd_t); extern void __pgd_error(const char *file, int line, pgd_t); #define pte_ERROR(pte) __pte_error(__FILE__, __LINE__, pte) #define pmd_ERROR(pmd) __pmd_error(__FILE__, __LINE__, pmd) #define pgd_ERROR(pgd) __pgd_error(__FILE__, __LINE__, pgd) /* * This is the lowest virtual address we can permit any user space * mapping to be mapped at. This is particularly important for * non-high vector CPUs. */ #define FIRST_USER_ADDRESS PAGE_SIZE /* * The pgprot_* and protection_map entries will be fixed up in runtime * to include the cachable and bufferable bits based on memory policy, * as well as any architecture dependent bits like global/ASID and SMP * shared mapping bits. */ #define _L_PTE_DEFAULT L_PTE_PRESENT | L_PTE_YOUNG extern pgprot_t pgprot_user; extern pgprot_t pgprot_kernel; #define _MOD_PROT(p, b) __pgprot(pgprot_val(p) | (b)) #define PAGE_NONE _MOD_PROT(pgprot_user, L_PTE_XN | L_PTE_RDONLY) #define PAGE_SHARED _MOD_PROT(pgprot_user, L_PTE_USER | L_PTE_XN) #define PAGE_SHARED_EXEC _MOD_PROT(pgprot_user, L_PTE_USER) #define PAGE_COPY _MOD_PROT(pgprot_user, L_PTE_USER | L_PTE_RDONLY | L_PTE_XN) #define PAGE_COPY_EXEC _MOD_PROT(pgprot_user, L_PTE_USER | L_PTE_RDONLY) #define PAGE_READONLY _MOD_PROT(pgprot_user, L_PTE_USER | L_PTE_RDONLY | L_PTE_XN) #define PAGE_READONLY_EXEC _MOD_PROT(pgprot_user, L_PTE_USER | L_PTE_RDONLY) #define PAGE_KERNEL _MOD_PROT(pgprot_kernel, L_PTE_XN) #define PAGE_KERNEL_EXEC pgprot_kernel #define __PAGE_NONE __pgprot(_L_PTE_DEFAULT | L_PTE_RDONLY | L_PTE_XN) #define __PAGE_SHARED __pgprot(_L_PTE_DEFAULT | L_PTE_USER | L_PTE_XN) #define __PAGE_SHARED_EXEC __pgprot(_L_PTE_DEFAULT | L_PTE_USER) #define __PAGE_COPY __pgprot(_L_PTE_DEFAULT | L_PTE_USER | L_PTE_RDONLY | L_PTE_XN) #define __PAGE_COPY_EXEC __pgprot(_L_PTE_DEFAULT | L_PTE_USER | L_PTE_RDONLY) #define __PAGE_READONLY __pgprot(_L_PTE_DEFAULT | L_PTE_USER | L_PTE_RDONLY | L_PTE_XN) #define __PAGE_READONLY_EXEC __pgprot(_L_PTE_DEFAULT | L_PTE_USER | L_PTE_RDONLY) #define __pgprot_modify(prot,mask,bits) \ __pgprot((pgprot_val(prot) & ~(mask)) | (bits)) #define pgprot_noncached(prot) \ __pgprot_modify(prot, L_PTE_MT_MASK, L_PTE_MT_UNCACHED) #define pgprot_writecombine(prot) \ __pgprot_modify(prot, L_PTE_MT_MASK, L_PTE_MT_BUFFERABLE) #define pgprot_stronglyordered(prot) \ __pgprot_modify(prot, L_PTE_MT_MASK, L_PTE_MT_UNCACHED) #define pgprot_device(prot) \ __pgprot_modify(prot, L_PTE_MT_MASK, L_PTE_MT_DEV_NONSHARED) #define pgprot_writethroughcache(prot) \ __pgprot_modify(prot, L_PTE_MT_MASK, L_PTE_MT_WRITETHROUGH) #define pgprot_writebackcache(prot) \ __pgprot_modify(prot, L_PTE_MT_MASK, L_PTE_MT_WRITEBACK) #define pgprot_writebackwacache(prot) \ __pgprot_modify(prot, L_PTE_MT_MASK, L_PTE_MT_WRITEALLOC) #ifdef CONFIG_ARM_DMA_MEM_BUFFERABLE #define pgprot_dmacoherent(prot) \ __pgprot_modify(prot, L_PTE_MT_MASK, L_PTE_MT_BUFFERABLE | L_PTE_XN) #define __HAVE_PHYS_MEM_ACCESS_PROT #define COHERENT_IS_NORMAL 1 struct file; extern pgprot_t phys_mem_access_prot(struct file *file, unsigned long pfn, unsigned long size, pgprot_t vma_prot); #else #define pgprot_dmacoherent(prot) \ __pgprot_modify(prot, L_PTE_MT_MASK, L_PTE_MT_UNCACHED | L_PTE_XN) #define COHERENT_IS_NORMAL 0 #endif #endif /* __ASSEMBLY__ */ /* * The table below defines the page protection levels that we insert into our * Linux page table version. These get translated into the best that the * architecture can perform. Note that on most ARM hardware: * 1) We cannot do execute protection * 2) If we could do execute protection, then read is implied * 3) write implies read permissions */ #define __P000 __PAGE_NONE #define __P001 __PAGE_READONLY #define __P010 __PAGE_COPY #define __P011 __PAGE_COPY #define __P100 __PAGE_READONLY_EXEC #define __P101 __PAGE_READONLY_EXEC #define __P110 __PAGE_COPY_EXEC #define __P111 __PAGE_COPY_EXEC #define __S000 __PAGE_NONE #define __S001 __PAGE_READONLY #define __S010 __PAGE_SHARED #define __S011 __PAGE_SHARED #define __S100 __PAGE_READONLY_EXEC #define __S101 __PAGE_READONLY_EXEC #define __S110 __PAGE_SHARED_EXEC #define __S111 __PAGE_SHARED_EXEC #ifndef __ASSEMBLY__ /* * ZERO_PAGE is a global shared page that is always zero: used * for zero-mapped memory areas etc.. */ extern struct page *empty_zero_page; #define ZERO_PAGE(vaddr) (empty_zero_page) extern pgd_t swapper_pg_dir[PTRS_PER_PGD]; /* to find an entry in a page-table-directory */ #define pgd_index(addr) ((addr) >> PGDIR_SHIFT) #define pgd_offset(mm, addr) ((mm)->pgd + pgd_index(addr)) /* to find an entry in a kernel page-table-directory */ #define pgd_offset_k(addr) pgd_offset(&init_mm, addr) #define pmd_none(pmd) (!pmd_val(pmd)) #define pmd_present(pmd) (pmd_val(pmd)) static inline pte_t *pmd_page_vaddr(pmd_t pmd) { return __va(pmd_val(pmd) & PHYS_MASK & (s32)PAGE_MASK); } #define pmd_page(pmd) pfn_to_page(__phys_to_pfn(pmd_val(pmd) & PHYS_MASK)) #ifndef CONFIG_HIGHPTE #define __pte_map(pmd) pmd_page_vaddr(*(pmd)) #define __pte_unmap(pte) do { } while (0) #else #define __pte_map(pmd) (pte_t *)kmap_atomic(pmd_page(*(pmd))) #define __pte_unmap(pte) kunmap_atomic(pte) #endif #define pte_index(addr) (((addr) >> PAGE_SHIFT) & (PTRS_PER_PTE - 1)) #define pte_offset_kernel(pmd,addr) (pmd_page_vaddr(*(pmd)) + pte_index(addr)) #define pte_offset_map(pmd,addr) (__pte_map(pmd) + pte_index(addr)) #define pte_unmap(pte) __pte_unmap(pte) #define pte_pfn(pte) ((pte_val(pte) & PHYS_MASK) >> PAGE_SHIFT) #define pfn_pte(pfn,prot) __pte(__pfn_to_phys(pfn) | pgprot_val(prot)) #define pte_page(pte) pfn_to_page(pte_pfn(pte)) #define mk_pte(page,prot) pfn_pte(page_to_pfn(page), prot) #define pte_clear(mm,addr,ptep) set_pte_ext(ptep, __pte(0), 0) #define pte_none(pte) (!pte_val(pte)) #define pte_present(pte) (pte_val(pte) & L_PTE_PRESENT) #define pte_write(pte) (!(pte_val(pte) & L_PTE_RDONLY)) #define pte_dirty(pte) (pte_val(pte) & L_PTE_DIRTY) #define pte_young(pte) (pte_val(pte) & L_PTE_YOUNG) #define pte_exec(pte) (!(pte_val(pte) & L_PTE_XN)) #define pte_special(pte) (0) #define pte_present_user(pte) \ ((pte_val(pte) & (L_PTE_PRESENT | L_PTE_USER)) == \ (L_PTE_PRESENT | L_PTE_USER)) #if __LINUX_ARM_ARCH__ < 6 static inline void __sync_icache_dcache(pte_t pteval) { } #else extern void __sync_icache_dcache(pte_t pteval); #endif static inline void set_pte_at(struct mm_struct *mm, unsigned long addr, pte_t *ptep, pte_t pteval) { unsigned long ext = 0; if (addr < TASK_SIZE && pte_present_user(pteval)) { __sync_icache_dcache(pteval); ext |= PTE_EXT_NG; } set_pte_ext(ptep, pteval, ext); } #define PTE_BIT_FUNC(fn,op) \ static inline pte_t pte_##fn(pte_t pte) { pte_val(pte) op; return pte; } PTE_BIT_FUNC(wrprotect, |= L_PTE_RDONLY); PTE_BIT_FUNC(mkwrite, &= ~L_PTE_RDONLY); PTE_BIT_FUNC(mkclean, &= ~L_PTE_DIRTY); PTE_BIT_FUNC(mkdirty, |= L_PTE_DIRTY); PTE_BIT_FUNC(mkold, &= ~L_PTE_YOUNG); PTE_BIT_FUNC(mkyoung, |= L_PTE_YOUNG); static inline pte_t pte_mkspecial(pte_t pte) { return pte; } static inline pte_t pte_modify(pte_t pte, pgprot_t newprot) { const pteval_t mask = L_PTE_XN | L_PTE_RDONLY | L_PTE_USER; pte_val(pte) = (pte_val(pte) & ~mask) | (pgprot_val(newprot) & mask); return pte; } /* * Encode and decode a swap entry. Swap entries are stored in the Linux * page tables as follows: * * 3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 * 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 * <--------------- offset ----------------------> < type -> 0 0 0 * * This gives us up to 31 swap files and 64GB per swap file. Note that * the offset field is always non-zero. */ #define __SWP_TYPE_SHIFT 3 #define __SWP_TYPE_BITS 5 #define __SWP_TYPE_MASK ((1 << __SWP_TYPE_BITS) - 1) #define __SWP_OFFSET_SHIFT (__SWP_TYPE_BITS + __SWP_TYPE_SHIFT) #define __swp_type(x) (((x).val >> __SWP_TYPE_SHIFT) & __SWP_TYPE_MASK) #define __swp_offset(x) ((x).val >> __SWP_OFFSET_SHIFT) #define __swp_entry(type,offset) ((swp_entry_t) { ((type) << __SWP_TYPE_SHIFT) | ((offset) << __SWP_OFFSET_SHIFT) }) #define __pte_to_swp_entry(pte) ((swp_entry_t) { pte_val(pte) }) #define __swp_entry_to_pte(swp) ((pte_t) { (swp).val }) /* * It is an error for the kernel to have more swap files than we can * encode in the PTEs. This ensures that we know when MAX_SWAPFILES * is increased beyond what we presently support. */ #define MAX_SWAPFILES_CHECK() BUILD_BUG_ON(MAX_SWAPFILES_SHIFT > __SWP_TYPE_BITS) /* * Encode and decode a file entry. File entries are stored in the Linux * page tables as follows: * * 3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 * 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 * <----------------------- offset ------------------------> 1 0 0 */ #define pte_file(pte) (pte_val(pte) & L_PTE_FILE) #define pte_to_pgoff(x) (pte_val(x) >> 3) #define pgoff_to_pte(x) __pte(((x) << 3) | L_PTE_FILE) #define PTE_FILE_MAX_BITS 29 /* Needs to be defined here and not in linux/mm.h, as it is arch dependent */ /* FIXME: this is not correct */ #define kern_addr_valid(addr) (1) #include <asm-generic/pgtable.h> /* * We provide our own arch_get_unmapped_area to cope with VIPT caches. */ #define HAVE_ARCH_UNMAPPED_AREA #define HAVE_ARCH_UNMAPPED_AREA_TOPDOWN /* * remap a physical page `pfn' of size `size' with page protection `prot' * into virtual address `from' */ #define io_remap_pfn_range(vma,from,pfn,size,prot) \ remap_pfn_range(vma,from,pfn,size,prot) #define pgtable_cache_init() do { } while (0) #endif /* !__ASSEMBLY__ */ #endif /* CONFIG_MMU */ #endif /* _ASMARM_PGTABLE_H */
Java
""" Small event module ======================= """ import numpy as np import logging logger = logging.getLogger(__name__) from ...utils.decorators import face_lookup from ...geometry.sheet_geometry import SheetGeometry from ...topology.sheet_topology import cell_division from .actions import ( exchange, remove, merge_vertices, detach_vertices, increase, decrease, increase_linear_tension, ) def reconnect(sheet, manager, **kwargs): """Performs reconnections (vertex merging / splitting) following Finegan et al. 2019 kwargs overwrite their corresponding `sheet.settings` entries Keyword Arguments ----------------- threshold_length : the threshold length at which vertex merging is performed p_4 : the probability per unit time to perform a detachement from a rank 4 vertex p_5p : the probability per unit time to perform a detachement from a rank 5 or more vertex See Also -------- **The tricellular vertex-specific adhesion molecule Sidekick facilitates polarised cell intercalation during Drosophila axis extension** _Tara M Finegan, Nathan Hervieux, Alexander Nestor-Bergmann, Alexander G. Fletcher, Guy B Blanchard, Benedicte Sanson_ bioRxiv 704932; doi: https://doi.org/10.1101/704932 """ sheet.settings.update(kwargs) nv = sheet.Nv merge_vertices(sheet) if nv != sheet.Nv: logger.info(f"Merged {nv - sheet.Nv+1} vertices") nv = sheet.Nv retval = detach_vertices(sheet) if retval: logger.info("Failed to detach, skipping") if nv != sheet.Nv: logger.info(f"Detached {sheet.Nv - nv} vertices") manager.append(reconnect, **kwargs) default_division_spec = { "face_id": -1, "face": -1, "growth_rate": 0.1, "critical_vol": 2.0, "geom": SheetGeometry, } @face_lookup def division(sheet, manager, **kwargs): """Cell division happens through cell growth up to a critical volume, followed by actual division of the face. Parameters ---------- sheet : a `Sheet` object manager : an `EventManager` instance face_id : int, index of the mother face growth_rate : float, default 0.1 rate of increase of the prefered volume critical_vol : float, default 2. volume at which the cells stops to grow and devides """ division_spec = default_division_spec division_spec.update(**kwargs) face = division_spec["face"] division_spec["critical_vol"] *= sheet.specs["face"]["prefered_vol"] print(sheet.face_df.loc[face, "vol"], division_spec["critical_vol"]) if sheet.face_df.loc[face, "vol"] < division_spec["critical_vol"]: increase( sheet, "face", face, division_spec["growth_rate"], "prefered_vol", True ) manager.append(division, **division_spec) else: daughter = cell_division(sheet, face, division_spec["geom"]) sheet.face_df.loc[daughter, "id"] = sheet.face_df.id.max() + 1 default_contraction_spec = { "face_id": -1, "face": -1, "contractile_increase": 1.0, "critical_area": 1e-2, "max_contractility": 10, "multiply": False, "contraction_column": "contractility", "unique": True, } @face_lookup def contraction(sheet, manager, **kwargs): """Single step contraction event.""" contraction_spec = default_contraction_spec contraction_spec.update(**kwargs) face = contraction_spec["face"] if (sheet.face_df.loc[face, "area"] < contraction_spec["critical_area"]) or ( sheet.face_df.loc[face, contraction_spec["contraction_column"]] > contraction_spec["max_contractility"] ): return increase( sheet, "face", face, contraction_spec["contractile_increase"], contraction_spec["contraction_column"], contraction_spec["multiply"], ) default_type1_transition_spec = { "face_id": -1, "face": -1, "critical_length": 0.1, "geom": SheetGeometry, } @face_lookup def type1_transition(sheet, manager, **kwargs): """Custom type 1 transition event that tests if the the shorter edge of the face is smaller than the critical length. """ type1_transition_spec = default_type1_transition_spec type1_transition_spec.update(**kwargs) face = type1_transition_spec["face"] edges = sheet.edge_df[sheet.edge_df["face"] == face] if min(edges["length"]) < type1_transition_spec["critical_length"]: exchange(sheet, face, type1_transition_spec["geom"]) default_face_elimination_spec = {"face_id": -1, "face": -1, "geom": SheetGeometry} @face_lookup def face_elimination(sheet, manager, **kwargs): """Removes the face with if face_id from the sheet.""" face_elimination_spec = default_face_elimination_spec face_elimination_spec.update(**kwargs) remove(sheet, face_elimination_spec["face"], face_elimination_spec["geom"]) default_check_tri_face_spec = {"geom": SheetGeometry} def check_tri_faces(sheet, manager, **kwargs): """Three neighbourghs cell elimination Add all cells with three neighbourghs in the manager to be eliminated at the next time step. Parameters ---------- sheet : a :class:`tyssue.sheet` object manager : a :class:`tyssue.events.EventManager` object """ check_tri_faces_spec = default_check_tri_face_spec check_tri_faces_spec.update(**kwargs) tri_faces = sheet.face_df[(sheet.face_df["num_sides"] < 4)].id manager.extend( [ (face_elimination, {"face_id": f, "geom": check_tri_faces_spec["geom"]}) for f in tri_faces ] ) default_contraction_line_tension_spec = { "face_id": -1, "face": -1, "shrink_rate": 1.05, "contractile_increase": 1.0, "critical_area": 1e-2, "max_contractility": 10, "multiply": True, "contraction_column": "line_tension", "unique": True, } @face_lookup def contraction_line_tension(sheet, manager, **kwargs): """ Single step contraction event """ contraction_spec = default_contraction_line_tension_spec contraction_spec.update(**kwargs) face = contraction_spec["face"] if sheet.face_df.loc[face, "area"] < contraction_spec["critical_area"]: return # reduce prefered_area decrease( sheet, "face", face, contraction_spec["shrink_rate"], col="prefered_area", divide=True, bound=contraction_spec["critical_area"] / 2, ) increase_linear_tension( sheet, face, contraction_spec["contractile_increase"], multiply=contraction_spec["multiply"], isotropic=True, limit=100, )
Java
<?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>Qt 4.3: mainwindow.cpp Example File (sql/masterdetail/mainwindow.cpp)</title> <link href="classic.css" rel="stylesheet" type="text/css" /> </head> <body> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr> <td align="left" valign="top" width="32"><a href="http://www.trolltech.com/products/qt"><img src="images/qt-logo.png" align="left" width="32" height="32" border="0" /></a></td> <td width="1">&nbsp;&nbsp;</td><td class="postheader" valign="center"><a href="index.html"><font color="#004faf">Home</font></a>&nbsp;&middot; <a href="classes.html"><font color="#004faf">All&nbsp;Classes</font></a>&nbsp;&middot; <a href="mainclasses.html"><font color="#004faf">Main&nbsp;Classes</font></a>&nbsp;&middot; <a href="groups.html"><font color="#004faf">Grouped&nbsp;Classes</font></a>&nbsp;&middot; <a href="modules.html"><font color="#004faf">Modules</font></a>&nbsp;&middot; <a href="functions.html"><font color="#004faf">Functions</font></a></td> <td align="right" valign="top" width="230"><a href="http://www.trolltech.com"><img src="images/trolltech-logo.png" align="right" width="203" height="32" border="0" /></a></td></tr></table><h1 class="title">mainwindow.cpp Example File<br /><span class="small-subtitle">sql/masterdetail/mainwindow.cpp</span> </h1> <pre><span class="comment"> /**************************************************************************** ** ** Copyright (C) 2006-2008 Trolltech ASA. All rights reserved. ** ** This file is part of the example classes of the Qt Toolkit. ** ** This file may be used under the terms of the GNU General Public ** License versions 2.0 or 3.0 as published by the Free Software ** Foundation and appearing in the files LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Alternatively you may (at ** your option) use any later version of the GNU General Public ** License if such license has been publicly approved by Trolltech ASA ** (or its successors, if any) and the KDE Free Qt Foundation. In ** addition, as a special exception, Trolltech gives you certain ** additional rights. These rights are described in the Trolltech GPL ** Exception version 1.2, which can be found at ** http://www.trolltech.com/products/qt/gplexception/ and in the file ** GPL_EXCEPTION.txt in this package. ** ** Please review the following information to ensure GNU General ** Public Licensing requirements will be met: ** http://trolltech.com/products/qt/licenses/licensing/opensource/. If ** you are unsure which license is appropriate for your use, please ** review the following information: ** http://trolltech.com/products/qt/licenses/licensing/licensingoverview ** or contact the sales department at sales@trolltech.com. ** ** In addition, as a special exception, Trolltech, as the sole ** copyright holder for Qt Designer, grants users of the Qt/Eclipse ** Integration plug-in the right for the Qt/Eclipse Integration to ** link to functionality provided by Qt Designer and its related ** libraries. ** ** This file is provided &quot;AS IS&quot; with NO WARRANTY OF ANY KIND, ** INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE. Trolltech reserves all rights not expressly ** granted herein. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ****************************************************************************/</span> #include &quot;mainwindow.h&quot; #include &quot;dialog.h&quot; #include &lt;QtGui&gt; #include &lt;QtSql&gt; #include &lt;QtXml&gt; extern int uniqueAlbumId; extern int uniqueArtistId; MainWindow::MainWindow(const QString &amp;artistTable, const QString &amp;albumTable, QFile *albumDetails, QWidget *parent) : QMainWindow(parent) { file = albumDetails; readAlbumData(); model = new QSqlRelationalTableModel(this); model-&gt;setTable(albumTable); model-&gt;setRelation(2, QSqlRelation(artistTable, &quot;id&quot;, &quot;artist&quot;)); model-&gt;select(); QGroupBox *artists = createArtistGroupBox(); QGroupBox *albums = createAlbumGroupBox(); QGroupBox *details = createDetailsGroupBox(); artistView-&gt;setCurrentIndex(0); uniqueAlbumId = model-&gt;rowCount(); uniqueArtistId = artistView-&gt;count(); connect(model, SIGNAL(rowsInserted(QModelIndex, int, int)), this, SLOT(updateHeader(QModelIndex, int, int))); connect(model, SIGNAL(rowsRemoved(QModelIndex, int, int)), this, SLOT(updateHeader(QModelIndex, int, int))); QGridLayout *layout = new QGridLayout; layout-&gt;addWidget(artists, 0, 0); layout-&gt;addWidget(albums, 1, 0); layout-&gt;addWidget(details, 0, 1, 2, 1); layout-&gt;setColumnStretch(1, 1); layout-&gt;setColumnMinimumWidth(0, 500); QWidget *widget = new QWidget; widget-&gt;setLayout(layout); setCentralWidget(widget); createMenuBar(); showImageLabel(); resize(850, 400); setWindowTitle(tr(&quot;Music Archive&quot;)); } void MainWindow::changeArtist(int row) { if (row &gt; 0) { QModelIndex index = model-&gt;relationModel(2)-&gt;index(row, 1); model-&gt;setFilter(&quot;artist = '&quot; + index.data().toString() + &quot;'&quot;) ; showArtistProfile(index); } else if (row == 0) { model-&gt;setFilter(&quot;&quot;); showImageLabel(); } else { return; } } void MainWindow::showArtistProfile(QModelIndex index) { QSqlRecord record = model-&gt;relationModel(2)-&gt;record(index.row()); QString name = record.value(&quot;artist&quot;).toString(); QString count = record.value(&quot;albumcount&quot;).toString(); profileLabel-&gt;setText(tr(&quot;Artist : %1 \n&quot; \ &quot;Number of Albums: %2&quot;).arg(name).arg(count)); profileLabel-&gt;show(); iconLabel-&gt;show(); titleLabel-&gt;hide(); trackList-&gt;hide(); imageLabel-&gt;hide(); } void MainWindow::showAlbumDetails(QModelIndex index) { QSqlRecord record = model-&gt;record(index.row()); QString artist = record.value(&quot;artist&quot;).toString(); QString title = record.value(&quot;title&quot;).toString(); QString year = record.value(&quot;year&quot;).toString(); QString albumId = record.value(&quot;albumid&quot;).toString(); showArtistProfile(indexOfArtist(artist)); titleLabel-&gt;setText(tr(&quot;Title: %1 (%2)&quot;).arg(title).arg(year)); titleLabel-&gt;show(); QDomNodeList albums = albumData.elementsByTagName(&quot;album&quot;); for (int i = 0; i &lt; albums.count(); i++) { QDomNode album = albums.item(i); if (album.toElement().attribute(&quot;id&quot;) == albumId) { getTrackList(album.toElement()); break; } } if (!trackList-&gt;count() == 0) trackList-&gt;show(); } void MainWindow::getTrackList(QDomNode album) { trackList-&gt;clear(); QDomNodeList tracks = album.childNodes(); QDomNode track; QString trackNumber; for (int j = 0; j &lt; tracks.count(); j++) { track = tracks.item(j); trackNumber = track.toElement().attribute(&quot;number&quot;); QListWidgetItem *item = new QListWidgetItem(trackList); item-&gt;setText(trackNumber + &quot;: &quot; + track.toElement().text()); } } void MainWindow::addAlbum() { Dialog *dialog = new Dialog(model, albumData, file, this); int accepted = dialog-&gt;exec(); if (accepted == 1) { int lastRow = model-&gt;rowCount() - 1; albumView-&gt;selectRow(lastRow); albumView-&gt;scrollToBottom(); showAlbumDetails(model-&gt;index(lastRow, 0)); } } void MainWindow::deleteAlbum() { QModelIndexList selection = albumView-&gt;selectionModel()-&gt;selectedRows(0); if (!selection.empty()) { QModelIndex idIndex = selection.at(0); int id = idIndex.data().toInt(); QString title = idIndex.sibling(idIndex.row(), 1).data().toString(); QString artist = idIndex.sibling(idIndex.row(), 2).data().toString(); QMessageBox::StandardButton button; button = QMessageBox::question(this, tr(&quot;Delete Album&quot;), QString(tr(&quot;Are you sure you want to &quot; \ &quot;delete '%1' by '%2'?&quot;)) .arg(title).arg(artist), QMessageBox::Yes | QMessageBox::No); if (button == QMessageBox::Yes) { removeAlbumFromFile(id); removeAlbumFromDatabase(idIndex); decreaseAlbumCount(indexOfArtist(artist)); showImageLabel(); } } else { QMessageBox::information(this, tr(&quot;Delete Album&quot;), tr(&quot;Select the album you want to delete.&quot;)); } } void MainWindow::removeAlbumFromFile(int id) { QDomNodeList albums = albumData.elementsByTagName(&quot;album&quot;); for (int i = 0; i &lt; albums.count(); i++) { QDomNode node = albums.item(i); if (node.toElement().attribute(&quot;id&quot;).toInt() == id) { albumData.elementsByTagName(&quot;archive&quot;).item(0).removeChild(node); break; } } <span class="comment"> /* The following code is commented out since the example uses an in memory database, i.e., altering the XML file will bring the data out of sync. if (!file-&gt;open(QIODevice::WriteOnly)) { return; } else { QTextStream stream(file); albumData.elementsByTagName(&quot;archive&quot;).item(0).save(stream, 4); file-&gt;close(); } */</span> } void MainWindow::removeAlbumFromDatabase(QModelIndex index) { model-&gt;removeRow(index.row()); } void MainWindow::decreaseAlbumCount(QModelIndex artistIndex) { int row = artistIndex.row(); QModelIndex albumCountIndex = artistIndex.sibling(row, 2); int albumCount = albumCountIndex.data().toInt(); QSqlTableModel *artists = model-&gt;relationModel(2); if (albumCount == 1) { artists-&gt;removeRow(row); showImageLabel(); } else { artists-&gt;setData(albumCountIndex, QVariant(albumCount - 1)); } } void MainWindow::readAlbumData() { if (!file-&gt;open(QIODevice::ReadOnly)) return; if (!albumData.setContent(file)) { file-&gt;close(); return; } file-&gt;close(); } QGroupBox* MainWindow::createArtistGroupBox() { artistView = new QComboBox; artistView-&gt;setModel(model-&gt;relationModel(2)); artistView-&gt;setModelColumn(1); connect(artistView, SIGNAL(currentIndexChanged(int)), this, SLOT(changeArtist(int))); QGroupBox *box = new QGroupBox(tr(&quot;Artist&quot;)); QGridLayout *layout = new QGridLayout; layout-&gt;addWidget(artistView, 0, 0); box-&gt;setLayout(layout); return box; } QGroupBox* MainWindow::createAlbumGroupBox() { QGroupBox *box = new QGroupBox(tr(&quot;Album&quot;)); albumView = new QTableView; albumView-&gt;setEditTriggers(QAbstractItemView::NoEditTriggers); albumView-&gt;setSortingEnabled(true); albumView-&gt;setSelectionBehavior(QAbstractItemView::SelectRows); albumView-&gt;setSelectionMode(QAbstractItemView::SingleSelection); albumView-&gt;setShowGrid(false); albumView-&gt;verticalHeader()-&gt;hide(); albumView-&gt;setAlternatingRowColors(true); albumView-&gt;setModel(model); adjustHeader(); QLocale locale = albumView-&gt;locale(); locale.setNumberOptions(QLocale::OmitGroupSeparator); albumView-&gt;setLocale(locale); connect(albumView, SIGNAL(clicked(QModelIndex)), this, SLOT(showAlbumDetails(QModelIndex))); connect(albumView, SIGNAL(activated(QModelIndex)), this, SLOT(showAlbumDetails(QModelIndex))); QVBoxLayout *layout = new QVBoxLayout; layout-&gt;addWidget(albumView, 0, 0); box-&gt;setLayout(layout); return box; } QGroupBox* MainWindow::createDetailsGroupBox() { QGroupBox *box = new QGroupBox(tr(&quot;Details&quot;)); profileLabel = new QLabel; profileLabel-&gt;setWordWrap(true); profileLabel-&gt;setAlignment(Qt::AlignBottom); titleLabel = new QLabel; titleLabel-&gt;setWordWrap(true); titleLabel-&gt;setAlignment(Qt::AlignBottom); iconLabel = new QLabel(); iconLabel-&gt;setAlignment(Qt::AlignBottom | Qt::AlignRight); iconLabel-&gt;setPixmap(QPixmap(&quot;:/images/icon.png&quot;)); imageLabel = new QLabel; imageLabel-&gt;setWordWrap(true); imageLabel-&gt;setAlignment(Qt::AlignCenter); imageLabel-&gt;setPixmap(QPixmap(&quot;:/images/image.png&quot;)); trackList = new QListWidget; QGridLayout *layout = new QGridLayout; layout-&gt;addWidget(imageLabel, 0, 0, 3, 2); layout-&gt;addWidget(profileLabel, 0, 0); layout-&gt;addWidget(iconLabel, 0, 1); layout-&gt;addWidget(titleLabel, 1, 0, 1, 2); layout-&gt;addWidget(trackList, 2, 0, 1, 2); layout-&gt;setRowStretch(2, 1); box-&gt;setLayout(layout); return box; } void MainWindow::createMenuBar() { QAction *addAction = new QAction(tr(&quot;&amp;Add album...&quot;), this); QAction *deleteAction = new QAction(tr(&quot;&amp;Delete album...&quot;), this); QAction *quitAction = new QAction(tr(&quot;&amp;Quit&quot;), this); QAction *aboutAction = new QAction(tr(&quot;&amp;About&quot;), this); QAction *aboutQtAction = new QAction(tr(&quot;About &amp;Qt&quot;), this); addAction-&gt;setShortcut(tr(&quot;Ctrl+A&quot;)); deleteAction-&gt;setShortcut(tr(&quot;Ctrl+D&quot;)); quitAction-&gt;setShortcut(tr(&quot;Ctrl+Q&quot;)); QMenu *fileMenu = menuBar()-&gt;addMenu(tr(&quot;&amp;File&quot;)); fileMenu-&gt;addAction(addAction); fileMenu-&gt;addAction(deleteAction); fileMenu-&gt;addSeparator(); fileMenu-&gt;addAction(quitAction); QMenu *helpMenu = menuBar()-&gt;addMenu(tr(&quot;&amp;Help&quot;)); helpMenu-&gt;addAction(aboutAction); helpMenu-&gt;addAction(aboutQtAction); connect(addAction, SIGNAL(triggered(bool)), this, SLOT(addAlbum())); connect(deleteAction, SIGNAL(triggered(bool)), this, SLOT(deleteAlbum())); connect(quitAction, SIGNAL(triggered(bool)), this, SLOT(close())); connect(aboutAction, SIGNAL(triggered(bool)), this, SLOT(about())); connect(aboutQtAction, SIGNAL(triggered(bool)), qApp, SLOT(aboutQt())); } void MainWindow::showImageLabel() { profileLabel-&gt;hide(); titleLabel-&gt;hide(); iconLabel-&gt;hide(); trackList-&gt;hide(); imageLabel-&gt;show(); } QModelIndex MainWindow::indexOfArtist(const QString &amp;artist) { QSqlTableModel *artistModel = model-&gt;relationModel(2); for (int i = 0; i &lt; artistModel-&gt;rowCount(); i++) { QSqlRecord record = artistModel-&gt;record(i); if (record.value(&quot;artist&quot;) == artist) return artistModel-&gt;index(i, 1); } return QModelIndex(); } void MainWindow::updateHeader(QModelIndex, int, int) { adjustHeader(); } void MainWindow::adjustHeader() { albumView-&gt;hideColumn(0); albumView-&gt;horizontalHeader()-&gt;setResizeMode(1, QHeaderView::Stretch); albumView-&gt;resizeColumnToContents(2); albumView-&gt;resizeColumnToContents(3); } void MainWindow::about() { QMessageBox::about(this, tr(&quot;About Music Archive&quot;), tr(&quot;&lt;p&gt;The &lt;b&gt;Music Archive&lt;/b&gt; example shows how to present &quot; &quot;data from different data sources in the same application. &quot; &quot;The album titles, and the corresponding artists and release dates, &quot; &quot;are kept in a database, while each album's tracks are stored &quot; &quot;in an XML file. &lt;/p&gt;&lt;p&gt;The example also shows how to add as &quot; &quot;well as remove data from both the database and the &quot; &quot;associated XML file using the API provided by the QtSql and &quot; &quot;QtXml modules, respectively.&lt;/p&gt;&quot;)); }</pre> <p /><address><hr /><div align="center"> <table width="100%" cellspacing="0" border="0"><tr class="address"> <td width="30%">Copyright &copy; 2008 <a href="trolltech.html">Trolltech</a></td> <td width="40%" align="center"><a href="trademarks.html">Trademarks</a></td> <td width="30%" align="right"><div align="right">Qt 4.3.6</div></td> </tr></table></div></address></body> </html>
Java
/* * rtl_tcp_andro is a library that uses libusb and librtlsdr to * turn your Realtek RTL2832 based DVB dongle into a SDR receiver. * It independently implements the rtl-tcp API protocol for native Android usage. * Copyright (C) 2016 by Martin Marinov <martintzvetomirov@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "queue.h" #include <string.h> #include <stdio.h> typedef struct queue_element queue_element_t; struct queue_element { queue_element_t * next; queue_element_t * prev; queue_element_t * last; void * payload; }; void queue_add(queue_t * queue, void * ptr) { if (*queue == NULL) { queue_element_t * new_el = (queue_element_t *) malloc(sizeof(queue_element_t)); new_el->last = new_el; new_el->next = NULL; new_el->prev = NULL; new_el->payload = ptr; *queue = (void *) new_el; } else { queue_element_t * qe = (queue_element_t *) *queue; queue_element_t * new_el = (queue_element_t *) malloc(sizeof(queue_element_t)); new_el->last = NULL; new_el->next = NULL; new_el->prev = qe->last; new_el->payload = ptr; qe->last->next = new_el; qe->last = new_el; } } void * queue_pop(queue_t * queue) { if (*queue == NULL) return NULL; queue_element_t * qe = (queue_element_t *) *queue; if (qe->next != NULL) { qe->next->prev = NULL; qe->next->last = qe->last; } void * result = qe->payload; *queue = (void *) qe->next; free(qe); return result; } /* Usage: void queue_unit_test(void) { queue_t queue = NULL; int a = 1; int b = 3; int c = 5; int d = 18; queue_add(&queue, (void *) &a); queue_add(&queue, (void *) &b); queue_add(&queue, (void *) &c); queue_add(&queue, (void *) &d); c = 12; int * ans; while ((ans = (int *) queue_pop(&queue))) printf("%d ", *ans); // prints out 1 3 12 18 } */
Java